6c16372cc4bdc30f958b3a2c5927cfbcd3f5ee55
[oweals/minetest.git] / src / game.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "game.h"
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
26 #include <IGUIFont.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
29 #include "client.h"
30 #include "server.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
34 #include "tool.h"
35 #include "guiChatConsole.h"
36 #include "config.h"
37 #include "version.h"
38 #include "clouds.h"
39 #include "particles.h"
40 #include "camera.h"
41 #include "mapblock.h"
42 #include "settings.h"
43 #include "profiler.h"
44 #include "mainmenumanager.h"
45 #include "gettext.h"
46 #include "log.h"
47 #include "filesys.h"
48 // Needed for determining pointing to nodes
49 #include "nodedef.h"
50 #include "nodemetadata.h"
51 #include "main.h" // For g_settings
52 #include "itemdef.h"
53 #include "tile.h" // For TextureSource
54 #include "shader.h" // For ShaderSource
55 #include "logoutputbuffer.h"
56 #include "subgame.h"
57 #include "quicktune_shortcutter.h"
58 #include "clientmap.h"
59 #include "hud.h"
60 #include "sky.h"
61 #include "sound.h"
62 #if USE_SOUND
63         #include "sound_openal.h"
64 #endif
65 #include "event_manager.h"
66 #include <iomanip>
67 #include <list>
68 #include "util/directiontables.h"
69 #include "util/pointedthing.h"
70 #include "drawscene.h"
71 #include "content_cao.h"
72
73 #ifdef HAVE_TOUCHSCREENGUI
74 #include "touchscreengui.h"
75 #endif
76
77 /*
78         Text input system
79 */
80
81 struct TextDestNodeMetadata : public TextDest
82 {
83         TextDestNodeMetadata(v3s16 p, Client *client)
84         {
85                 m_p = p;
86                 m_client = client;
87         }
88         // This is deprecated I guess? -celeron55
89         void gotText(std::wstring text)
90         {
91                 std::string ntext = wide_to_narrow(text);
92                 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
93                                 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
94                 std::map<std::string, std::string> fields;
95                 fields["text"] = ntext;
96                 m_client->sendNodemetaFields(m_p, "", fields);
97         }
98         void gotText(std::map<std::string, std::string> fields)
99         {
100                 m_client->sendNodemetaFields(m_p, "", fields);
101         }
102
103         v3s16 m_p;
104         Client *m_client;
105 };
106
107 struct TextDestPlayerInventory : public TextDest
108 {
109         TextDestPlayerInventory(Client *client)
110         {
111                 m_client = client;
112                 m_formname = "";
113         }
114         TextDestPlayerInventory(Client *client, std::string formname)
115         {
116                 m_client = client;
117                 m_formname = formname;
118         }
119         void gotText(std::map<std::string, std::string> fields)
120         {
121                 m_client->sendInventoryFields(m_formname, fields);
122         }
123
124         Client *m_client;
125 };
126
127 struct LocalFormspecHandler : public TextDest
128 {
129         LocalFormspecHandler();
130         LocalFormspecHandler(std::string formname) :
131                 m_client(0)
132         {
133                 m_formname = formname;
134         }
135
136         LocalFormspecHandler(std::string formname, Client *client) :
137                 m_client(client)
138         {
139                 m_formname = formname;
140         }
141
142         void gotText(std::wstring message) {
143                 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
144         }
145
146         void gotText(std::map<std::string, std::string> fields)
147         {
148                 if (m_formname == "MT_PAUSE_MENU") {
149                         if (fields.find("btn_sound") != fields.end()) {
150                                 g_gamecallback->changeVolume();
151                                 return;
152                         }
153
154                         if (fields.find("btn_exit_menu") != fields.end()) {
155                                 g_gamecallback->disconnect();
156                                 return;
157                         }
158
159                         if (fields.find("btn_exit_os") != fields.end()) {
160                                 g_gamecallback->exitToOS();
161                                 return;
162                         }
163
164                         if (fields.find("btn_change_password") != fields.end()) {
165                                 g_gamecallback->changePassword();
166                                 return;
167                         }
168
169                         if (fields.find("quit") != fields.end()) {
170                                 return;
171                         }
172
173                         if (fields.find("btn_continue") != fields.end()) {
174                                 return;
175                         }
176                 }
177                 if (m_formname == "MT_CHAT_MENU") {
178                         assert(m_client != 0);
179                         if ((fields.find("btn_send") != fields.end()) ||
180                                         (fields.find("quit") != fields.end())) {
181                                 if (fields.find("f_text") != fields.end()) {
182                                         m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
183                                 }
184                                 return;
185                         }
186                 }
187
188                 if (m_formname == "MT_DEATH_SCREEN") {
189                         assert(m_client != 0);
190                         if ((fields.find("btn_respawn") != fields.end())) {
191                                 m_client->sendRespawn();
192                                 return;
193                         }
194
195                         if (fields.find("quit") != fields.end()) {
196                                 m_client->sendRespawn();
197                                 return;
198                         }
199                 }
200
201                 // don't show error message for unhandled cursor keys
202                 if ( (fields.find("key_up") != fields.end()) ||
203                         (fields.find("key_down") != fields.end()) ||
204                         (fields.find("key_left") != fields.end()) ||
205                         (fields.find("key_right") != fields.end())) {
206                         return;
207                 }
208
209                 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
210                 int i = 0;
211                 for (std::map<std::string,std::string>::iterator iter = fields.begin();
212                                 iter != fields.end(); iter++) {
213                         errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
214                         i++;
215                 }
216         }
217
218         Client *m_client;
219 };
220
221 /* Form update callback */
222
223 class NodeMetadataFormSource: public IFormSource
224 {
225 public:
226         NodeMetadataFormSource(ClientMap *map, v3s16 p):
227                 m_map(map),
228                 m_p(p)
229         {
230         }
231         std::string getForm()
232         {
233                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
234                 if(!meta)
235                         return "";
236                 return meta->getString("formspec");
237         }
238         std::string resolveText(std::string str)
239         {
240                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
241                 if(!meta)
242                         return str;
243                 return meta->resolveString(str);
244         }
245
246         ClientMap *m_map;
247         v3s16 m_p;
248 };
249
250 class PlayerInventoryFormSource: public IFormSource
251 {
252 public:
253         PlayerInventoryFormSource(Client *client):
254                 m_client(client)
255         {
256         }
257         std::string getForm()
258         {
259                 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
260                 return player->inventory_formspec;
261         }
262
263         Client *m_client;
264 };
265
266 /*
267         Check if a node is pointable
268 */
269 inline bool isPointableNode(const MapNode& n,
270                 Client *client, bool liquids_pointable)
271 {
272         const ContentFeatures &features = client->getNodeDefManager()->get(n);
273         return features.pointable ||
274                 (liquids_pointable && features.isLiquid());
275 }
276
277 /*
278         Find what the player is pointing at
279 */
280 PointedThing getPointedThing(Client *client, v3f player_position,
281                 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
282                 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
283                 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
284 {
285         PointedThing result;
286
287         hilightboxes.clear();
288         selected_object = NULL;
289
290         INodeDefManager *nodedef = client->getNodeDefManager();
291         ClientMap &map = client->getEnv().getClientMap();
292
293         f32 mindistance = BS * 1001;
294
295         // First try to find a pointed at active object
296         if(look_for_object)
297         {
298                 selected_object = client->getSelectedActiveObject(d*BS,
299                                 camera_position, shootline);
300
301                 if(selected_object != NULL)
302                 {
303                         if(selected_object->doShowSelectionBox())
304                         {
305                                 aabb3f *selection_box = selected_object->getSelectionBox();
306                                 // Box should exist because object was
307                                 // returned in the first place
308                                 assert(selection_box);
309
310                                 v3f pos = selected_object->getPosition();
311                                 hilightboxes.push_back(aabb3f(
312                                                 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
313                                                 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
314                         }
315
316                         mindistance = (selected_object->getPosition() - camera_position).getLength();
317
318                         result.type = POINTEDTHING_OBJECT;
319                         result.object_id = selected_object->getId();
320                 }
321         }
322
323         // That didn't work, try to find a pointed at node
324
325
326         v3s16 pos_i = floatToInt(player_position, BS);
327
328         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
329                         <<std::endl;*/
330
331         s16 a = d;
332         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
333         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
334         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
335         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
336         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
337         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
338
339         // Prevent signed number overflow
340         if(yend==32767)
341                 yend=32766;
342         if(zend==32767)
343                 zend=32766;
344         if(xend==32767)
345                 xend=32766;
346
347         for(s16 y = ystart; y <= yend; y++)
348         for(s16 z = zstart; z <= zend; z++)
349         for(s16 x = xstart; x <= xend; x++)
350         {
351                 MapNode n;
352                 try
353                 {
354                         n = map.getNode(v3s16(x,y,z));
355                 }
356                 catch(InvalidPositionException &e)
357                 {
358                         continue;
359                 }
360                 if(!isPointableNode(n, client, liquids_pointable))
361                         continue;
362
363                 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
364
365                 v3s16 np(x,y,z);
366                 v3f npf = intToFloat(np, BS);
367
368                 for(std::vector<aabb3f>::const_iterator
369                                 i = boxes.begin();
370                                 i != boxes.end(); i++)
371                 {
372                         aabb3f box = *i;
373                         box.MinEdge += npf;
374                         box.MaxEdge += npf;
375
376                         for(u16 j=0; j<6; j++)
377                         {
378                                 v3s16 facedir = g_6dirs[j];
379                                 aabb3f facebox = box;
380
381                                 f32 d = 0.001*BS;
382                                 if(facedir.X > 0)
383                                         facebox.MinEdge.X = facebox.MaxEdge.X-d;
384                                 else if(facedir.X < 0)
385                                         facebox.MaxEdge.X = facebox.MinEdge.X+d;
386                                 else if(facedir.Y > 0)
387                                         facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
388                                 else if(facedir.Y < 0)
389                                         facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
390                                 else if(facedir.Z > 0)
391                                         facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
392                                 else if(facedir.Z < 0)
393                                         facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
394
395                                 v3f centerpoint = facebox.getCenter();
396                                 f32 distance = (centerpoint - camera_position).getLength();
397                                 if(distance >= mindistance)
398                                         continue;
399                                 if(!facebox.intersectsWithLine(shootline))
400                                         continue;
401
402                                 v3s16 np_above = np + facedir;
403
404                                 result.type = POINTEDTHING_NODE;
405                                 result.node_undersurface = np;
406                                 result.node_abovesurface = np_above;
407                                 mindistance = distance;
408
409                                 hilightboxes.clear();
410                                 for(std::vector<aabb3f>::const_iterator
411                                                 i2 = boxes.begin();
412                                                 i2 != boxes.end(); i2++)
413                                 {
414                                         aabb3f box = *i2;
415                                         box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
416                                         box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
417                                         hilightboxes.push_back(box);
418                                 }
419                         }
420                 }
421         } // for coords
422
423         return result;
424 }
425
426 /* Profiler display */
427
428 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
429                 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
430                 u32 show_profiler_max)
431 {
432         if(show_profiler == 0)
433         {
434                 guitext_profiler->setVisible(false);
435         }
436         else
437         {
438
439                 std::ostringstream os(std::ios_base::binary);
440                 g_profiler->printPage(os, show_profiler, show_profiler_max);
441                 std::wstring text = narrow_to_wide(os.str());
442                 guitext_profiler->setText(text.c_str());
443                 guitext_profiler->setVisible(true);
444
445                 s32 w = font->getDimension(text.c_str()).Width;
446                 if(w < 400)
447                         w = 400;
448                 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
449                                 8+(text_height+5)*2 +
450                                 font->getDimension(text.c_str()).Height);
451                 guitext_profiler->setRelativePosition(rect);
452                 guitext_profiler->setVisible(true);
453         }
454 }
455
456 class ProfilerGraph
457 {
458 private:
459         struct Piece{
460                 Profiler::GraphValues values;
461         };
462         struct Meta{
463                 float min;
464                 float max;
465                 video::SColor color;
466                 Meta(float initial=0, video::SColor color=
467                                 video::SColor(255,255,255,255)):
468                         min(initial),
469                         max(initial),
470                         color(color)
471                 {}
472         };
473         std::list<Piece> m_log;
474 public:
475         u32 m_log_max_size;
476
477         ProfilerGraph():
478                 m_log_max_size(200)
479         {}
480
481         void put(const Profiler::GraphValues &values)
482         {
483                 Piece piece;
484                 piece.values = values;
485                 m_log.push_back(piece);
486                 while(m_log.size() > m_log_max_size)
487                         m_log.erase(m_log.begin());
488         }
489
490         void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
491                         gui::IGUIFont* font) const
492         {
493                 std::map<std::string, Meta> m_meta;
494                 for(std::list<Piece>::const_iterator k = m_log.begin();
495                                 k != m_log.end(); k++)
496                 {
497                         const Piece &piece = *k;
498                         for(Profiler::GraphValues::const_iterator i = piece.values.begin();
499                                         i != piece.values.end(); i++){
500                                 const std::string &id = i->first;
501                                 const float &value = i->second;
502                                 std::map<std::string, Meta>::iterator j =
503                                                 m_meta.find(id);
504                                 if(j == m_meta.end()){
505                                         m_meta[id] = Meta(value);
506                                         continue;
507                                 }
508                                 if(value < j->second.min)
509                                         j->second.min = value;
510                                 if(value > j->second.max)
511                                         j->second.max = value;
512                         }
513                 }
514
515                 // Assign colors
516                 static const video::SColor usable_colors[] = {
517                         video::SColor(255,255,100,100),
518                         video::SColor(255,90,225,90),
519                         video::SColor(255,100,100,255),
520                         video::SColor(255,255,150,50),
521                         video::SColor(255,220,220,100)
522                 };
523                 static const u32 usable_colors_count =
524                                 sizeof(usable_colors) / sizeof(*usable_colors);
525                 u32 next_color_i = 0;
526                 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
527                                 i != m_meta.end(); i++){
528                         Meta &meta = i->second;
529                         video::SColor color(255,200,200,200);
530                         if(next_color_i < usable_colors_count)
531                                 color = usable_colors[next_color_i++];
532                         meta.color = color;
533                 }
534
535                 s32 graphh = 50;
536                 s32 textx = x_left + m_log_max_size + 15;
537                 s32 textx2 = textx + 200 - 15;
538
539                 // Draw background
540                 /*{
541                         u32 num_graphs = m_meta.size();
542                         core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
543                                         textx2, y_bottom);
544                         video::SColor bgcolor(120,0,0,0);
545                         driver->draw2DRectangle(bgcolor, rect, NULL);
546                 }*/
547
548                 s32 meta_i = 0;
549                 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
550                                 i != m_meta.end(); i++){
551                         const std::string &id = i->first;
552                         const Meta &meta = i->second;
553                         s32 x = x_left;
554                         s32 y = y_bottom - meta_i * 50;
555                         float show_min = meta.min;
556                         float show_max = meta.max;
557                         if(show_min >= -0.0001 && show_max >= -0.0001){
558                                 if(show_min <= show_max * 0.5)
559                                         show_min = 0;
560                         }
561                         s32 texth = 15;
562                         char buf[10];
563                         snprintf(buf, 10, "%.3g", show_max);
564                         font->draw(narrow_to_wide(buf).c_str(),
565                                         core::rect<s32>(textx, y - graphh,
566                                         textx2, y - graphh + texth),
567                                         meta.color);
568                         snprintf(buf, 10, "%.3g", show_min);
569                         font->draw(narrow_to_wide(buf).c_str(),
570                                         core::rect<s32>(textx, y - texth,
571                                         textx2, y),
572                                         meta.color);
573                         font->draw(narrow_to_wide(id).c_str(),
574                                         core::rect<s32>(textx, y - graphh/2 - texth/2,
575                                         textx2, y - graphh/2 + texth/2),
576                                         meta.color);
577                         s32 graph1y = y;
578                         s32 graph1h = graphh;
579                         bool relativegraph = (show_min != 0 && show_min != show_max);
580                         float lastscaledvalue = 0.0;
581                         bool lastscaledvalue_exists = false;
582                         for(std::list<Piece>::const_iterator j = m_log.begin();
583                                         j != m_log.end(); j++)
584                         {
585                                 const Piece &piece = *j;
586                                 float value = 0;
587                                 bool value_exists = false;
588                                 Profiler::GraphValues::const_iterator k =
589                                                 piece.values.find(id);
590                                 if(k != piece.values.end()){
591                                         value = k->second;
592                                         value_exists = true;
593                                 }
594                                 if(!value_exists){
595                                         x++;
596                                         lastscaledvalue_exists = false;
597                                         continue;
598                                 }
599                                 float scaledvalue = 1.0;
600                                 if(show_max != show_min)
601                                         scaledvalue = (value - show_min) / (show_max - show_min);
602                                 if(scaledvalue == 1.0 && value == 0){
603                                         x++;
604                                         lastscaledvalue_exists = false;
605                                         continue;
606                                 }
607                                 if(relativegraph){
608                                         if(lastscaledvalue_exists){
609                                                 s32 ivalue1 = lastscaledvalue * graph1h;
610                                                 s32 ivalue2 = scaledvalue * graph1h;
611                                                 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
612                                                                 v2s32(x, graph1y - ivalue2), meta.color);
613                                         }
614                                         lastscaledvalue = scaledvalue;
615                                         lastscaledvalue_exists = true;
616                                 } else{
617                                         s32 ivalue = scaledvalue * graph1h;
618                                         driver->draw2DLine(v2s32(x, graph1y),
619                                                         v2s32(x, graph1y - ivalue), meta.color);
620                                 }
621                                 x++;
622                         }
623                         meta_i++;
624                 }
625         }
626 };
627
628 class NodeDugEvent: public MtEvent
629 {
630 public:
631         v3s16 p;
632         MapNode n;
633
634         NodeDugEvent(v3s16 p, MapNode n):
635                 p(p),
636                 n(n)
637         {}
638         const char* getType() const
639         {return "NodeDug";}
640 };
641
642 class SoundMaker
643 {
644         ISoundManager *m_sound;
645         INodeDefManager *m_ndef;
646 public:
647         float m_player_step_timer;
648
649         SimpleSoundSpec m_player_step_sound;
650         SimpleSoundSpec m_player_leftpunch_sound;
651         SimpleSoundSpec m_player_rightpunch_sound;
652
653         SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
654                 m_sound(sound),
655                 m_ndef(ndef),
656                 m_player_step_timer(0)
657         {
658         }
659
660         void playPlayerStep()
661         {
662                 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
663                         m_player_step_timer = 0.03;
664                         m_sound->playSound(m_player_step_sound, false);
665                 }
666         }
667
668         static void viewBobbingStep(MtEvent *e, void *data)
669         {
670                 SoundMaker *sm = (SoundMaker*)data;
671                 sm->playPlayerStep();
672         }
673
674         static void playerRegainGround(MtEvent *e, void *data)
675         {
676                 SoundMaker *sm = (SoundMaker*)data;
677                 sm->playPlayerStep();
678         }
679
680         static void playerJump(MtEvent *e, void *data)
681         {
682                 //SoundMaker *sm = (SoundMaker*)data;
683         }
684
685         static void cameraPunchLeft(MtEvent *e, void *data)
686         {
687                 SoundMaker *sm = (SoundMaker*)data;
688                 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
689         }
690
691         static void cameraPunchRight(MtEvent *e, void *data)
692         {
693                 SoundMaker *sm = (SoundMaker*)data;
694                 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
695         }
696
697         static void nodeDug(MtEvent *e, void *data)
698         {
699                 SoundMaker *sm = (SoundMaker*)data;
700                 NodeDugEvent *nde = (NodeDugEvent*)e;
701                 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
702         }
703
704         static void playerDamage(MtEvent *e, void *data)
705         {
706                 SoundMaker *sm = (SoundMaker*)data;
707                 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
708         }
709
710         static void playerFallingDamage(MtEvent *e, void *data)
711         {
712                 SoundMaker *sm = (SoundMaker*)data;
713                 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
714         }
715
716         void registerReceiver(MtEventManager *mgr)
717         {
718                 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
719                 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
720                 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
721                 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
722                 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
723                 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
724                 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
725                 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
726         }
727
728         void step(float dtime)
729         {
730                 m_player_step_timer -= dtime;
731         }
732 };
733
734 // Locally stored sounds don't need to be preloaded because of this
735 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
736 {
737         std::set<std::string> m_fetched;
738 public:
739
740         void fetchSounds(const std::string &name,
741                         std::set<std::string> &dst_paths,
742                         std::set<std::string> &dst_datas)
743         {
744                 if(m_fetched.count(name))
745                         return;
746                 m_fetched.insert(name);
747                 std::string base = porting::path_share + DIR_DELIM + "testsounds";
748                 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
749                 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
750                 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
751                 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
752                 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
753                 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
754                 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
755                 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
756                 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
757                 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
758                 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
759         }
760 };
761
762 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
763 {
764         Sky *m_sky;
765         bool *m_force_fog_off;
766         f32 *m_fog_range;
767         Client *m_client;
768
769 public:
770         GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
771                         f32 *fog_range, Client *client):
772                 m_sky(sky),
773                 m_force_fog_off(force_fog_off),
774                 m_fog_range(fog_range),
775                 m_client(client)
776         {}
777         ~GameGlobalShaderConstantSetter() {}
778
779         virtual void onSetConstants(video::IMaterialRendererServices *services,
780                         bool is_highlevel)
781         {
782                 if(!is_highlevel)
783                         return;
784
785                 // Background color
786                 video::SColor bgcolor = m_sky->getBgColor();
787                 video::SColorf bgcolorf(bgcolor);
788                 float bgcolorfa[4] = {
789                         bgcolorf.r,
790                         bgcolorf.g,
791                         bgcolorf.b,
792                         bgcolorf.a,
793                 };
794                 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
795
796                 // Fog distance
797                 float fog_distance = 10000*BS;
798                 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
799                         fog_distance = *m_fog_range;
800                 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
801
802                 // Day-night ratio
803                 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
804                 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
805                 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
806
807                 u32 animation_timer = porting::getTimeMs() % 100000;
808                 float animation_timer_f = (float)animation_timer / 100000.0;
809                 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
810                 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
811
812                 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
813                 v3f eye_position = player->getEyePosition();
814                 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
815                 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
816
817                 // Uniform sampler layers
818                 int layer0 = 0;
819                 int layer1 = 1;
820                 int layer2 = 2;
821                 // before 1.8 there isn't a "integer interface", only float
822 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
823                 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
824                 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
825                 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
826 #else
827                 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
828                 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
829                 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
830 #endif
831         }
832 };
833
834 bool nodePlacementPrediction(Client &client,
835                 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
836 {
837         std::string prediction = playeritem_def.node_placement_prediction;
838         INodeDefManager *nodedef = client.ndef();
839         ClientMap &map = client.getEnv().getClientMap();
840
841         if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
842         {
843                 verbosestream<<"Node placement prediction for "
844                                 <<playeritem_def.name<<" is "
845                                 <<prediction<<std::endl;
846                 v3s16 p = neighbourpos;
847                 // Place inside node itself if buildable_to
848                 try{
849                         MapNode n_under = map.getNode(nodepos);
850                         if(nodedef->get(n_under).buildable_to)
851                                 p = nodepos;
852                         else if (!nodedef->get(map.getNode(p)).buildable_to)
853                                 return false;
854                 }catch(InvalidPositionException &e){}
855                 // Find id of predicted node
856                 content_t id;
857                 bool found = nodedef->getId(prediction, id);
858                 if(!found){
859                         errorstream<<"Node placement prediction failed for "
860                                         <<playeritem_def.name<<" (places "
861                                         <<prediction
862                                         <<") - Name not known"<<std::endl;
863                         return false;
864                 }
865                 // Predict param2 for facedir and wallmounted nodes
866                 u8 param2 = 0;
867                 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
868                         v3s16 dir = nodepos - neighbourpos;
869                         if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
870                                 param2 = dir.Y < 0 ? 1 : 0;
871                         } else if(abs(dir.X) > abs(dir.Z)){
872                                 param2 = dir.X < 0 ? 3 : 2;
873                         } else {
874                                 param2 = dir.Z < 0 ? 5 : 4;
875                         }
876                 }
877                 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
878                         v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
879                         if(abs(dir.X) > abs(dir.Z)){
880                                 param2 = dir.X < 0 ? 3 : 1;
881                         } else {
882                                 param2 = dir.Z < 0 ? 2 : 0;
883                         }
884                 }
885                 assert(param2 >= 0 && param2 <= 5);
886                 //Check attachment if node is in group attached_node
887                 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
888                         static v3s16 wallmounted_dirs[8] = {
889                                 v3s16(0,1,0),
890                                 v3s16(0,-1,0),
891                                 v3s16(1,0,0),
892                                 v3s16(-1,0,0),
893                                 v3s16(0,0,1),
894                                 v3s16(0,0,-1),
895                         };
896                         v3s16 pp;
897                         if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
898                                 pp = p + wallmounted_dirs[param2];
899                         else
900                                 pp = p + v3s16(0,-1,0);
901                         if(!nodedef->get(map.getNode(pp)).walkable)
902                                 return false;
903                 }
904                 // Add node to client map
905                 MapNode n(id, 0, param2);
906                 try{
907                         LocalPlayer* player = client.getEnv().getLocalPlayer();
908
909                         // Dont place node when player would be inside new node
910                         // NOTE: This is to be eventually implemented by a mod as client-side Lua
911                         if (!nodedef->get(n).walkable ||
912                                 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
913                                 (nodedef->get(n).walkable &&
914                                 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
915                                 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
916
917                                         // This triggers the required mesh update too
918                                         client.addNode(p, n);
919                                         return true;
920                                 }
921                 }catch(InvalidPositionException &e){
922                         errorstream<<"Node placement prediction failed for "
923                                         <<playeritem_def.name<<" (places "
924                                         <<prediction
925                                         <<") - Position not loaded"<<std::endl;
926                 }
927         }
928         return false;
929 }
930
931 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
932                 InventoryManager *invmgr, IGameDef *gamedef,
933                 IWritableTextureSource* tsrc, IrrlichtDevice * device,
934                 IFormSource* fs_src, TextDest* txt_dest
935                 ) {
936
937         if (*cur_formspec == 0) {
938                 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
939                                 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec );
940                 (*cur_formspec)->doPause = false;
941                 (*cur_formspec)->drop();
942         }
943         else {
944                 (*cur_formspec)->setFormSource(fs_src);
945                 (*cur_formspec)->setTextDest(txt_dest);
946         }
947 }
948
949 #ifdef __ANDROID__
950 #define SIZE_TAG "size[11,5.5]"
951 #else
952 #define SIZE_TAG "size[11,5.5,true]"
953 #endif
954
955 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
956                 InventoryManager *invmgr, IGameDef *gamedef,
957                 IWritableTextureSource* tsrc, IrrlichtDevice * device,
958                 Client* client, std::string text)
959 {
960         std::string formspec =
961                 FORMSPEC_VERSION_STRING
962                 SIZE_TAG
963                 "field[3,2.35;6,0.5;f_text;;" + text + "]"
964                 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
965                 ;
966
967         /* Create menu */
968         /* Note: FormspecFormSource and LocalFormspecHandler
969          * are deleted by guiFormSpecMenu                     */
970         FormspecFormSource* fs_src = new FormspecFormSource(formspec);
971         LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
972
973         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
974 }
975
976 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
977                 InventoryManager *invmgr, IGameDef *gamedef,
978                 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
979 {
980         std::string formspec =
981                 std::string(FORMSPEC_VERSION_STRING) +
982                 SIZE_TAG
983                 "bgcolor[#320000b4;true]"
984                 "label[4.85,1.35;You died.]"
985                 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
986                 ;
987
988         /* Create menu */
989         /* Note: FormspecFormSource and LocalFormspecHandler
990          * are deleted by guiFormSpecMenu                     */
991         FormspecFormSource* fs_src = new FormspecFormSource(formspec);
992         LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
993
994         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst);
995 }
996
997 /******************************************************************************/
998 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
999                 InventoryManager *invmgr, IGameDef *gamedef,
1000                 IWritableTextureSource* tsrc, IrrlichtDevice * device,
1001                 bool singleplayermode)
1002 {
1003 #ifdef __ANDROID__
1004         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1005                         "No menu visible:\n"
1006                         "- single tap: button activate\n"
1007                         "- double tap: place/use\n"
1008                         "- slide finger: look around\n"
1009                         "Menu/Inventory visible:\n"
1010                         "- double tap (outside):\n"
1011                         " -->close\n"
1012                         "- touch stack, touch slot:\n"
1013                         " --> move stack\n"
1014                         "- touch&drag, tap 2nd finger\n"
1015                         " --> place single item to slot\n"
1016                         ));
1017 #else
1018         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1019                         "- WASD: move\n"
1020                         "- Space: jump/climb\n"
1021                         "- Shift: sneak/go down\n"
1022                         "- Q: drop item\n"
1023                         "- I: inventory\n"
1024                         "- Mouse: turn/look\n"
1025                         "- Mouse left: dig/punch\n"
1026                         "- Mouse right: place/use\n"
1027                         "- Mouse wheel: select item\n"
1028                         "- T: chat\n"
1029                         ));
1030 #endif
1031         float ypos = singleplayermode ? 1.0 : 0.5;
1032         std::ostringstream os;
1033
1034         os << FORMSPEC_VERSION_STRING  << SIZE_TAG
1035                         << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1036                                         << wide_to_narrow(wstrgettext("Continue"))     << "]";
1037
1038         if (!singleplayermode) {
1039                 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1040                                         << wide_to_narrow(wstrgettext("Change Password")) << "]";
1041                 }
1042
1043         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1044                                         << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1045         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1046                                         << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1047         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1048                                         << wide_to_narrow(wstrgettext("Exit to OS"))   << "]"
1049                         << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1050                         << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1051                         << minetest_build_info << "\n"
1052                         << "path_user = " << wrap_rows(porting::path_user, 20)
1053                         << "\n;]";
1054
1055         /* Create menu */
1056         /* Note: FormspecFormSource and LocalFormspecHandler  *
1057          * are deleted by guiFormSpecMenu                     */
1058         FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1059         LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1060
1061         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst);
1062
1063         (*cur_formspec)->doPause = true;
1064 }
1065
1066 /******************************************************************************/
1067 void the_game(bool &kill, bool random_input, InputHandler *input,
1068         IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1069         std::string playername, std::string password,
1070         std::string address /* If "", local server is used */,
1071         u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1072         const SubgameSpec &gamespec /* Used for local game */,
1073         bool simple_singleplayer_mode)
1074 {
1075         GUIFormSpecMenu* current_formspec = 0;
1076         video::IVideoDriver* driver = device->getVideoDriver();
1077         scene::ISceneManager* smgr = device->getSceneManager();
1078
1079         // Calculate text height using the font
1080         u32 text_height = font->getDimension(L"Random test string").Height;
1081
1082         /*
1083                 Draw "Loading" screen
1084         */
1085
1086         {
1087                 wchar_t* text = wgettext("Loading...");
1088                 draw_load_screen(text, device, guienv, font, 0, 0);
1089                 delete[] text;
1090         }
1091
1092         // Create texture source
1093         IWritableTextureSource *tsrc = createTextureSource(device);
1094
1095         // Create shader source
1096         IWritableShaderSource *shsrc = createShaderSource(device);
1097
1098         // These will be filled by data received from the server
1099         // Create item definition manager
1100         IWritableItemDefManager *itemdef = createItemDefManager();
1101         // Create node definition manager
1102         IWritableNodeDefManager *nodedef = createNodeDefManager();
1103
1104         // Sound fetcher (useful when testing)
1105         GameOnDemandSoundFetcher soundfetcher;
1106
1107         // Sound manager
1108         ISoundManager *sound = NULL;
1109         bool sound_is_dummy = false;
1110 #if USE_SOUND
1111         if(g_settings->getBool("enable_sound")){
1112                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1113                 sound = createOpenALSoundManager(&soundfetcher);
1114                 if(!sound)
1115                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1116         } else {
1117                 infostream<<"Sound disabled."<<std::endl;
1118         }
1119 #endif
1120         if(!sound){
1121                 infostream<<"Using dummy audio."<<std::endl;
1122                 sound = &dummySoundManager;
1123                 sound_is_dummy = true;
1124         }
1125
1126         Server *server = NULL;
1127
1128         try{
1129         // Event manager
1130         EventManager eventmgr;
1131
1132         // Sound maker
1133         SoundMaker soundmaker(sound, nodedef);
1134         soundmaker.registerReceiver(&eventmgr);
1135
1136         // Add chat log output for errors to be shown in chat
1137         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1138
1139         // Create UI for modifying quicktune values
1140         QuicktuneShortcutter quicktune;
1141
1142         /*
1143                 Create server.
1144         */
1145
1146         if(address == ""){
1147                 wchar_t* text = wgettext("Creating server....");
1148                 draw_load_screen(text, device, guienv, font, 0, 25);
1149                 delete[] text;
1150                 infostream<<"Creating server"<<std::endl;
1151
1152                 std::string bind_str = g_settings->get("bind_address");
1153                 Address bind_addr(0,0,0,0, port);
1154
1155                 if (g_settings->getBool("ipv6_server")) {
1156                         bind_addr.setAddress((IPv6AddressBytes*) NULL);
1157                 }
1158                 try {
1159                         bind_addr.Resolve(bind_str.c_str());
1160                         address = bind_str;
1161                 } catch (ResolveError &e) {
1162                         infostream << "Resolving bind address \"" << bind_str
1163                                            << "\" failed: " << e.what()
1164                                            << " -- Listening on all addresses." << std::endl;
1165                 }
1166
1167                 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1168                         error_message = L"Unable to listen on " +
1169                                 narrow_to_wide(bind_addr.serializeString()) +
1170                                 L" because IPv6 is disabled";
1171                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1172                         // Break out of client scope
1173                         return;
1174                 }
1175
1176                 server = new Server(map_dir, gamespec,
1177                                 simple_singleplayer_mode,
1178                                 bind_addr.isIPv6());
1179
1180                 server->start(bind_addr);
1181         }
1182
1183         do{ // Client scope (breakable do-while(0))
1184
1185         /*
1186                 Create client
1187         */
1188
1189         {
1190                 wchar_t* text = wgettext("Creating client...");
1191                 draw_load_screen(text, device, guienv, font, 0, 50);
1192                 delete[] text;
1193         }
1194         infostream<<"Creating client"<<std::endl;
1195
1196         MapDrawControl draw_control;
1197
1198         {
1199                 wchar_t* text = wgettext("Resolving address...");
1200                 draw_load_screen(text, device, guienv, font, 0, 75);
1201                 delete[] text;
1202         }
1203         Address connect_address(0,0,0,0, port);
1204         try {
1205                 connect_address.Resolve(address.c_str());
1206                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1207                         //connect_address.Resolve("localhost");
1208                         if (connect_address.isIPv6()) {
1209                                 IPv6AddressBytes addr_bytes;
1210                                 addr_bytes.bytes[15] = 1;
1211                                 connect_address.setAddress(&addr_bytes);
1212                         } else {
1213                                 connect_address.setAddress(127,0,0,1);
1214                         }
1215                 }
1216         }
1217         catch(ResolveError &e) {
1218                 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1219                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1220                 // Break out of client scope
1221                 break;
1222         }
1223         if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1224                 error_message = L"Unable to connect to " +
1225                         narrow_to_wide(connect_address.serializeString()) +
1226                         L" because IPv6 is disabled";
1227                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1228                 // Break out of client scope
1229                 break;
1230         }
1231
1232         /*
1233                 Create client
1234         */
1235         Client client(device, playername.c_str(), password, draw_control,
1236                 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1237                 connect_address.isIPv6());
1238
1239         // Client acts as our GameDef
1240         IGameDef *gamedef = &client;
1241
1242         /*
1243                 Attempt to connect to the server
1244         */
1245
1246         infostream<<"Connecting to server at ";
1247         connect_address.print(&infostream);
1248         infostream<<std::endl;
1249         client.connect(connect_address);
1250
1251         /*
1252                 Wait for server to accept connection
1253         */
1254         bool could_connect = false;
1255         bool connect_aborted = false;
1256         try{
1257                 float time_counter = 0.0;
1258                 input->clear();
1259                 float fps_max = g_settings->getFloat("fps_max");
1260                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1261                 u32 lasttime = device->getTimer()->getTime();
1262                 while(device->run())
1263                 {
1264                         f32 dtime = 0.033; // in seconds
1265                         if (cloud_menu_background) {
1266                                 u32 time = device->getTimer()->getTime();
1267                                 if(time > lasttime)
1268                                         dtime = (time - lasttime) / 1000.0;
1269                                 else
1270                                         dtime = 0;
1271                                 lasttime = time;
1272                         }
1273                         // Update client and server
1274                         client.step(dtime);
1275                         if(server != NULL)
1276                                 server->step(dtime);
1277
1278                         // End condition
1279                         if(client.getState() == LC_Init) {
1280                                 could_connect = true;
1281                                 break;
1282                         }
1283                         // Break conditions
1284                         if(client.accessDenied()) {
1285                                 error_message = L"Access denied. Reason: "
1286                                                 +client.accessDeniedReason();
1287                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1288                                 break;
1289                         }
1290                         if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1291                                 connect_aborted = true;
1292                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1293                                 break;
1294                         }
1295
1296                         // Display status
1297                         {
1298                                 wchar_t* text = wgettext("Connecting to server...");
1299                                 draw_load_screen(text, device, guienv, font, dtime, 100);
1300                                 delete[] text;
1301                         }
1302
1303                         // On some computers framerate doesn't seem to be
1304                         // automatically limited
1305                         if (cloud_menu_background) {
1306                                 // Time of frame without fps limit
1307                                 float busytime;
1308                                 u32 busytime_u32;
1309                                 // not using getRealTime is necessary for wine
1310                                 u32 time = device->getTimer()->getTime();
1311                                 if(time > lasttime)
1312                                         busytime_u32 = time - lasttime;
1313                                 else
1314                                         busytime_u32 = 0;
1315                                 busytime = busytime_u32 / 1000.0;
1316
1317                                 // FPS limiter
1318                                 u32 frametime_min = 1000./fps_max;
1319
1320                                 if(busytime_u32 < frametime_min) {
1321                                         u32 sleeptime = frametime_min - busytime_u32;
1322                                         device->sleep(sleeptime);
1323                                 }
1324                         } else {
1325                                 sleep_ms(25);
1326                         }
1327                         time_counter += dtime;
1328                 }
1329         }
1330         catch(con::PeerNotFoundException &e)
1331         {}
1332
1333         /*
1334                 Handle failure to connect
1335         */
1336         if(!could_connect) {
1337                 if(error_message == L"" && !connect_aborted) {
1338                         error_message = L"Connection failed";
1339                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1340                 }
1341                 // Break out of client scope
1342                 break;
1343         }
1344
1345         /*
1346                 Wait until content has been received
1347         */
1348         bool got_content = false;
1349         bool content_aborted = false;
1350         {
1351                 float time_counter = 0.0;
1352                 input->clear();
1353                 float fps_max = g_settings->getFloat("fps_max");
1354                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1355                 u32 lasttime = device->getTimer()->getTime();
1356                 while (device->run()) {
1357                         f32 dtime = 0.033; // in seconds
1358                         if (cloud_menu_background) {
1359                                 u32 time = device->getTimer()->getTime();
1360                                 if(time > lasttime)
1361                                         dtime = (time - lasttime) / 1000.0;
1362                                 else
1363                                         dtime = 0;
1364                                 lasttime = time;
1365                         }
1366                         // Update client and server
1367                         client.step(dtime);
1368                         if (server != NULL)
1369                                 server->step(dtime);
1370
1371                         // End condition
1372                         if (client.mediaReceived() &&
1373                                         client.itemdefReceived() &&
1374                                         client.nodedefReceived()) {
1375                                 got_content = true;
1376                                 break;
1377                         }
1378                         // Break conditions
1379                         if (client.accessDenied()) {
1380                                 error_message = L"Access denied. Reason: "
1381                                                 +client.accessDeniedReason();
1382                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1383                                 break;
1384                         }
1385                         if (client.getState() < LC_Init) {
1386                                 error_message = L"Client disconnected";
1387                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1388                                 break;
1389                         }
1390                         if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1391                                 content_aborted = true;
1392                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1393                                 break;
1394                         }
1395
1396                         // Display status
1397                         int progress=0;
1398                         if (!client.itemdefReceived())
1399                         {
1400                                 wchar_t* text = wgettext("Item definitions...");
1401                                 progress = 0;
1402                                 draw_load_screen(text, device, guienv, font, dtime, progress);
1403                                 delete[] text;
1404                         }
1405                         else if (!client.nodedefReceived())
1406                         {
1407                                 wchar_t* text = wgettext("Node definitions...");
1408                                 progress = 25;
1409                                 draw_load_screen(text, device, guienv, font, dtime, progress);
1410                                 delete[] text;
1411                         }
1412                         else
1413                         {
1414
1415                                 std::stringstream message;
1416                                 message.precision(3);
1417                                 message << gettext("Media...");
1418
1419                                 if ( ( USE_CURL == 0) ||
1420                                                 (!g_settings->getBool("enable_remote_media_server"))) {
1421                                         float cur = client.getCurRate();
1422                                         std::string cur_unit = gettext(" KB/s");
1423
1424                                         if (cur > 900) {
1425                                                 cur /= 1024.0;
1426                                                 cur_unit = gettext(" MB/s");
1427                                         }
1428                                         message << " ( " << cur << cur_unit << " )";
1429                                 }
1430                                 progress = 50+client.mediaReceiveProgress()*50+0.5;
1431                                 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1432                                                 guienv, font, dtime, progress);
1433                         }
1434
1435                         // On some computers framerate doesn't seem to be
1436                         // automatically limited
1437                         if (cloud_menu_background) {
1438                                 // Time of frame without fps limit
1439                                 float busytime;
1440                                 u32 busytime_u32;
1441                                 // not using getRealTime is necessary for wine
1442                                 u32 time = device->getTimer()->getTime();
1443                                 if(time > lasttime)
1444                                         busytime_u32 = time - lasttime;
1445                                 else
1446                                         busytime_u32 = 0;
1447                                 busytime = busytime_u32 / 1000.0;
1448
1449                                 // FPS limiter
1450                                 u32 frametime_min = 1000./fps_max;
1451
1452                                 if(busytime_u32 < frametime_min) {
1453                                         u32 sleeptime = frametime_min - busytime_u32;
1454                                         device->sleep(sleeptime);
1455                                 }
1456                         } else {
1457                                 sleep_ms(25);
1458                         }
1459                         time_counter += dtime;
1460                 }
1461         }
1462
1463         if(!got_content){
1464                 if(error_message == L"" && !content_aborted){
1465                         error_message = L"Something failed";
1466                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1467                 }
1468                 // Break out of client scope
1469                 break;
1470         }
1471
1472         /*
1473                 After all content has been received:
1474                 Update cached textures, meshes and materials
1475         */
1476         client.afterContentReceived(device,font);
1477
1478         /*
1479                 Create the camera node
1480         */
1481         Camera camera(smgr, draw_control, gamedef);
1482         if (!camera.successfullyCreated(error_message))
1483                 return;
1484
1485         f32 camera_yaw = 0; // "right/left"
1486         f32 camera_pitch = 0; // "up/down"
1487
1488         /*
1489                 Clouds
1490         */
1491
1492         Clouds *clouds = NULL;
1493         if(g_settings->getBool("enable_clouds"))
1494         {
1495                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1496         }
1497
1498         /*
1499                 Skybox thingy
1500         */
1501
1502         Sky *sky = NULL;
1503         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1504
1505         scene::ISceneNode* skybox = NULL;
1506
1507         /*
1508                 A copy of the local inventory
1509         */
1510         Inventory local_inventory(itemdef);
1511
1512         /*
1513                 Find out size of crack animation
1514         */
1515         int crack_animation_length = 5;
1516         {
1517                 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1518                 v2u32 size = t->getOriginalSize();
1519                 crack_animation_length = size.Y / size.X;
1520         }
1521
1522         /*
1523                 Add some gui stuff
1524         */
1525
1526         // First line of debug text
1527         gui::IGUIStaticText *guitext = guienv->addStaticText(
1528                         L"Minetest",
1529                         core::rect<s32>(0, 0, 0, 0),
1530                         false, false);
1531         // Second line of debug text
1532         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1533                         L"",
1534                         core::rect<s32>(0, 0, 0, 0),
1535                         false, false);
1536         // At the middle of the screen
1537         // Object infos are shown in this
1538         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1539                         L"",
1540                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1541                         false, true);
1542
1543         // Status text (displays info when showing and hiding GUI stuff, etc.)
1544         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1545                         L"<Status>",
1546                         core::rect<s32>(0,0,0,0),
1547                         false, false);
1548         guitext_status->setVisible(false);
1549
1550         std::wstring statustext;
1551         float statustext_time = 0;
1552
1553         // Chat text
1554         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1555                         L"",
1556                         core::rect<s32>(0,0,0,0),
1557                         //false, false); // Disable word wrap as of now
1558                         false, true);
1559         // Remove stale "recent" chat messages from previous connections
1560         chat_backend.clearRecentChat();
1561         // Chat backend and console
1562         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1563
1564         // Profiler text (size is updated when text is updated)
1565         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1566                         L"<Profiler>",
1567                         core::rect<s32>(0,0,0,0),
1568                         false, false);
1569         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1570         guitext_profiler->setVisible(false);
1571         guitext_profiler->setWordWrap(true);
1572
1573 #ifdef HAVE_TOUCHSCREENGUI
1574         if (g_touchscreengui)
1575                 g_touchscreengui->init(tsrc,porting::getDisplayDensity());
1576 #endif
1577
1578         /*
1579                 Some statistics are collected in these
1580         */
1581         u32 drawtime = 0;
1582         u32 beginscenetime = 0;
1583         u32 endscenetime = 0;
1584
1585         float recent_turn_speed = 0.0;
1586
1587         ProfilerGraph graph;
1588         // Initially clear the profiler
1589         Profiler::GraphValues dummyvalues;
1590         g_profiler->graphGet(dummyvalues);
1591
1592         float nodig_delay_timer = 0.0;
1593         float dig_time = 0.0;
1594         u16 dig_index = 0;
1595         PointedThing pointed_old;
1596         bool digging = false;
1597         bool ldown_for_dig = false;
1598
1599         float damage_flash = 0;
1600
1601         float jump_timer = 0;
1602         bool reset_jump_timer = false;
1603
1604         const float object_hit_delay = 0.2;
1605         float object_hit_delay_timer = 0.0;
1606         float time_from_last_punch = 10;
1607
1608         float update_draw_list_timer = 0.0;
1609         v3f update_draw_list_last_cam_dir;
1610
1611         bool invert_mouse = g_settings->getBool("invert_mouse");
1612
1613         bool update_wielded_item_trigger = true;
1614
1615         bool show_hud = true;
1616         bool show_chat = true;
1617         bool force_fog_off = false;
1618         f32 fog_range = 100*BS;
1619         bool disable_camera_update = false;
1620         bool show_debug = g_settings->getBool("show_debug");
1621         bool show_profiler_graph = false;
1622         u32 show_profiler = 0;
1623         u32 show_profiler_max = 3;  // Number of pages
1624
1625         float time_of_day = 0;
1626         float time_of_day_smooth = 0;
1627
1628         float repeat_rightclick_timer = 0;
1629
1630         /*
1631                 Shader constants
1632         */
1633         shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1634                         sky, &force_fog_off, &fog_range, &client));
1635
1636         /*
1637                 Main loop
1638         */
1639
1640         bool first_loop_after_window_activation = true;
1641
1642         // TODO: Convert the static interval timers to these
1643         // Interval limiter for profiler
1644         IntervalLimiter m_profiler_interval;
1645
1646         // Time is in milliseconds
1647         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1648         // NOTE: So we have to use getTime() and call run()s between them
1649         u32 lasttime = device->getTimer()->getTime();
1650
1651         LocalPlayer* player = client.getEnv().getLocalPlayer();
1652         player->hurt_tilt_timer = 0;
1653         player->hurt_tilt_strength = 0;
1654
1655         /*
1656                 HUD object
1657         */
1658         Hud hud(driver, smgr, guienv, font, text_height,
1659                         gamedef, player, &local_inventory);
1660
1661         core::stringw str = L"Minetest [";
1662         str += driver->getName();
1663         str += "]";
1664         device->setWindowCaption(str.c_str());
1665
1666         // Info text
1667         std::wstring infotext;
1668
1669         for(;;)
1670         {
1671                 if(device->run() == false || kill == true ||
1672                                 g_gamecallback->shutdown_requested)
1673                         break;
1674
1675                 v2u32 screensize = driver->getScreenSize();
1676
1677                 // Time of frame without fps limit
1678                 float busytime;
1679                 u32 busytime_u32;
1680                 {
1681                         // not using getRealTime is necessary for wine
1682                         u32 time = device->getTimer()->getTime();
1683                         if(time > lasttime)
1684                                 busytime_u32 = time - lasttime;
1685                         else
1686                                 busytime_u32 = 0;
1687                         busytime = busytime_u32 / 1000.0;
1688                 }
1689
1690                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1691
1692                 // Necessary for device->getTimer()->getTime()
1693                 device->run();
1694
1695                 /*
1696                         FPS limiter
1697                 */
1698
1699                 {
1700                         float fps_max = g_menumgr.pausesGame() ?
1701                                         g_settings->getFloat("pause_fps_max") :
1702                                         g_settings->getFloat("fps_max");
1703                         u32 frametime_min = 1000./fps_max;
1704
1705                         if(busytime_u32 < frametime_min)
1706                         {
1707                                 u32 sleeptime = frametime_min - busytime_u32;
1708                                 device->sleep(sleeptime);
1709                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1710                         }
1711                 }
1712
1713                 // Necessary for device->getTimer()->getTime()
1714                 device->run();
1715
1716                 /*
1717                         Time difference calculation
1718                 */
1719                 f32 dtime; // in seconds
1720
1721                 u32 time = device->getTimer()->getTime();
1722                 if(time > lasttime)
1723                         dtime = (time - lasttime) / 1000.0;
1724                 else
1725                         dtime = 0;
1726                 lasttime = time;
1727
1728                 g_profiler->graphAdd("mainloop_dtime", dtime);
1729
1730                 /* Run timers */
1731
1732                 if(nodig_delay_timer >= 0)
1733                         nodig_delay_timer -= dtime;
1734                 if(object_hit_delay_timer >= 0)
1735                         object_hit_delay_timer -= dtime;
1736                 time_from_last_punch += dtime;
1737
1738                 g_profiler->add("Elapsed time", dtime);
1739                 g_profiler->avg("FPS", 1./dtime);
1740
1741                 /*
1742                         Time average and jitter calculation
1743                 */
1744
1745                 static f32 dtime_avg1 = 0.0;
1746                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1747                 f32 dtime_jitter1 = dtime - dtime_avg1;
1748
1749                 static f32 dtime_jitter1_max_sample = 0.0;
1750                 static f32 dtime_jitter1_max_fraction = 0.0;
1751                 {
1752                         static f32 jitter1_max = 0.0;
1753                         static f32 counter = 0.0;
1754                         if(dtime_jitter1 > jitter1_max)
1755                                 jitter1_max = dtime_jitter1;
1756                         counter += dtime;
1757                         if(counter > 0.0)
1758                         {
1759                                 counter -= 3.0;
1760                                 dtime_jitter1_max_sample = jitter1_max;
1761                                 dtime_jitter1_max_fraction
1762                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1763                                 jitter1_max = 0.0;
1764                         }
1765                 }
1766
1767                 /*
1768                         Busytime average and jitter calculation
1769                 */
1770
1771                 static f32 busytime_avg1 = 0.0;
1772                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1773                 f32 busytime_jitter1 = busytime - busytime_avg1;
1774
1775                 static f32 busytime_jitter1_max_sample = 0.0;
1776                 static f32 busytime_jitter1_min_sample = 0.0;
1777                 {
1778                         static f32 jitter1_max = 0.0;
1779                         static f32 jitter1_min = 0.0;
1780                         static f32 counter = 0.0;
1781                         if(busytime_jitter1 > jitter1_max)
1782                                 jitter1_max = busytime_jitter1;
1783                         if(busytime_jitter1 < jitter1_min)
1784                                 jitter1_min = busytime_jitter1;
1785                         counter += dtime;
1786                         if(counter > 0.0){
1787                                 counter -= 3.0;
1788                                 busytime_jitter1_max_sample = jitter1_max;
1789                                 busytime_jitter1_min_sample = jitter1_min;
1790                                 jitter1_max = 0.0;
1791                                 jitter1_min = 0.0;
1792                         }
1793                 }
1794
1795                 /*
1796                         Handle miscellaneous stuff
1797                 */
1798
1799                 if(client.accessDenied())
1800                 {
1801                         error_message = L"Access denied. Reason: "
1802                                         +client.accessDeniedReason();
1803                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1804                         break;
1805                 }
1806
1807                 if(g_gamecallback->disconnect_requested)
1808                 {
1809                         g_gamecallback->disconnect_requested = false;
1810                         break;
1811                 }
1812
1813                 if(g_gamecallback->changepassword_requested)
1814                 {
1815                         (new GUIPasswordChange(guienv, guiroot, -1,
1816                                 &g_menumgr, &client))->drop();
1817                         g_gamecallback->changepassword_requested = false;
1818                 }
1819
1820                 if(g_gamecallback->changevolume_requested)
1821                 {
1822                         (new GUIVolumeChange(guienv, guiroot, -1,
1823                                 &g_menumgr, &client))->drop();
1824                         g_gamecallback->changevolume_requested = false;
1825                 }
1826
1827                 /* Process TextureSource's queue */
1828                 tsrc->processQueue();
1829
1830                 /* Process ItemDefManager's queue */
1831                 itemdef->processQueue(gamedef);
1832
1833                 /*
1834                         Process ShaderSource's queue
1835                 */
1836                 shsrc->processQueue();
1837
1838                 /*
1839                         Random calculations
1840                 */
1841                 hud.resizeHotbar();
1842
1843                 // Hilight boxes collected during the loop and displayed
1844                 std::vector<aabb3f> hilightboxes;
1845
1846                 /* reset infotext */
1847                 infotext = L"";
1848                 /*
1849                         Profiler
1850                 */
1851                 float profiler_print_interval =
1852                                 g_settings->getFloat("profiler_print_interval");
1853                 bool print_to_log = true;
1854                 if(profiler_print_interval == 0){
1855                         print_to_log = false;
1856                         profiler_print_interval = 5;
1857                 }
1858                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1859                 {
1860                         if(print_to_log){
1861                                 infostream<<"Profiler:"<<std::endl;
1862                                 g_profiler->print(infostream);
1863                         }
1864
1865                         update_profiler_gui(guitext_profiler, font, text_height,
1866                                         show_profiler, show_profiler_max);
1867
1868                         g_profiler->clear();
1869                 }
1870
1871                 /*
1872                         Direct handling of user input
1873                 */
1874
1875                 // Reset input if window not active or some menu is active
1876                 if(device->isWindowActive() == false
1877                                 || noMenuActive() == false
1878                                 || guienv->hasFocus(gui_chat_console))
1879                 {
1880                         input->clear();
1881                 }
1882                 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1883                 {
1884                         gui_chat_console->closeConsoleAtOnce();
1885                 }
1886
1887                 // Input handler step() (used by the random input generator)
1888                 input->step(dtime);
1889 #ifdef HAVE_TOUCHSCREENGUI
1890                 if (g_touchscreengui) {
1891                         g_touchscreengui->step(dtime);
1892                 }
1893 #endif
1894 #ifdef __ANDROID__
1895                 if (current_formspec != 0)
1896                         current_formspec->getAndroidUIInput();
1897 #endif
1898
1899                 // Increase timer for doubleclick of "jump"
1900                 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1901                         jump_timer += dtime;
1902
1903                 /*
1904                         Launch menus and trigger stuff according to keys
1905                 */
1906                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1907                 {
1908                         // drop selected item
1909                         IDropAction *a = new IDropAction();
1910                         a->count = 0;
1911                         a->from_inv.setCurrentPlayer();
1912                         a->from_list = "main";
1913                         a->from_i = client.getPlayerItem();
1914                         client.inventoryAction(a);
1915                 }
1916                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1917                 {
1918                         infostream<<"the_game: "
1919                                         <<"Launching inventory"<<std::endl;
1920
1921                         PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1922                         TextDest* txt_dst = new TextDestPlayerInventory(&client);
1923
1924                         create_formspec_menu(&current_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst);
1925
1926                         InventoryLocation inventoryloc;
1927                         inventoryloc.setCurrentPlayer();
1928                         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1929                 }
1930                 else if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey))
1931                 {
1932                         show_pause_menu(&current_formspec, &client, gamedef, tsrc, device,
1933                                         simple_singleplayer_mode);
1934                 }
1935                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1936                 {
1937                         show_chat_menu(&current_formspec, &client, gamedef, tsrc, device,
1938                                         &client,"");
1939                 }
1940                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1941                 {
1942                         show_chat_menu(&current_formspec, &client, gamedef, tsrc, device,
1943                                         &client,"/");
1944                 }
1945                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1946                 {
1947                         if (!gui_chat_console->isOpenInhibited())
1948                         {
1949                                 // Open up to over half of the screen
1950                                 gui_chat_console->openConsole(0.6);
1951                                 guienv->setFocus(gui_chat_console);
1952                         }
1953                 }
1954                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1955                 {
1956                         if(g_settings->getBool("free_move"))
1957                         {
1958                                 g_settings->set("free_move","false");
1959                                 statustext = L"free_move disabled";
1960                                 statustext_time = 0;
1961                         }
1962                         else
1963                         {
1964                                 g_settings->set("free_move","true");
1965                                 statustext = L"free_move enabled";
1966                                 statustext_time = 0;
1967                                 if(!client.checkPrivilege("fly"))
1968                                         statustext += L" (note: no 'fly' privilege)";
1969                         }
1970                 }
1971                 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1972                 {
1973                         if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1974                         {
1975                                 if(g_settings->getBool("free_move"))
1976                                 {
1977                                         g_settings->set("free_move","false");
1978                                         statustext = L"free_move disabled";
1979                                         statustext_time = 0;
1980                                 }
1981                                 else
1982                                 {
1983                                         g_settings->set("free_move","true");
1984                                         statustext = L"free_move enabled";
1985                                         statustext_time = 0;
1986                                         if(!client.checkPrivilege("fly"))
1987                                                 statustext += L" (note: no 'fly' privilege)";
1988                                 }
1989                         }
1990                         reset_jump_timer = true;
1991                 }
1992                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1993                 {
1994                         if(g_settings->getBool("fast_move"))
1995                         {
1996                                 g_settings->set("fast_move","false");
1997                                 statustext = L"fast_move disabled";
1998                                 statustext_time = 0;
1999                         }
2000                         else
2001                         {
2002                                 g_settings->set("fast_move","true");
2003                                 statustext = L"fast_move enabled";
2004                                 statustext_time = 0;
2005                                 if(!client.checkPrivilege("fast"))
2006                                         statustext += L" (note: no 'fast' privilege)";
2007                         }
2008                 }
2009                 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2010                 {
2011                         if(g_settings->getBool("noclip"))
2012                         {
2013                                 g_settings->set("noclip","false");
2014                                 statustext = L"noclip disabled";
2015                                 statustext_time = 0;
2016                         }
2017                         else
2018                         {
2019                                 g_settings->set("noclip","true");
2020                                 statustext = L"noclip enabled";
2021                                 statustext_time = 0;
2022                                 if(!client.checkPrivilege("noclip"))
2023                                         statustext += L" (note: no 'noclip' privilege)";
2024                         }
2025                 }
2026                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2027                 {
2028                         irr::video::IImage* const image = driver->createScreenShot();
2029                         if (image) {
2030                                 irr::c8 filename[256];
2031                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
2032                                                  g_settings->get("screenshot_path").c_str(),
2033                                                  device->getTimer()->getRealTime());
2034                                 if (driver->writeImageToFile(image, filename)) {
2035                                         std::wstringstream sstr;
2036                                         sstr<<"Saved screenshot to '"<<filename<<"'";
2037                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2038                                         statustext = sstr.str();
2039                                         statustext_time = 0;
2040                                 } else{
2041                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2042                                 }
2043                                 image->drop();
2044                         }
2045                 }
2046                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2047                 {
2048                         show_hud = !show_hud;
2049                         if(show_hud)
2050                                 statustext = L"HUD shown";
2051                         else
2052                                 statustext = L"HUD hidden";
2053                         statustext_time = 0;
2054                 }
2055                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2056                 {
2057                         show_chat = !show_chat;
2058                         if(show_chat)
2059                                 statustext = L"Chat shown";
2060                         else
2061                                 statustext = L"Chat hidden";
2062                         statustext_time = 0;
2063                 }
2064                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2065                 {
2066                         force_fog_off = !force_fog_off;
2067                         if(force_fog_off)
2068                                 statustext = L"Fog disabled";
2069                         else
2070                                 statustext = L"Fog enabled";
2071                         statustext_time = 0;
2072                 }
2073                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2074                 {
2075                         disable_camera_update = !disable_camera_update;
2076                         if(disable_camera_update)
2077                                 statustext = L"Camera update disabled";
2078                         else
2079                                 statustext = L"Camera update enabled";
2080                         statustext_time = 0;
2081                 }
2082                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2083                 {
2084                         // Initial / 3x toggle: Chat only
2085                         // 1x toggle: Debug text with chat
2086                         // 2x toggle: Debug text with profiler graph
2087                         if(!show_debug)
2088                         {
2089                                 show_debug = true;
2090                                 show_profiler_graph = false;
2091                                 statustext = L"Debug info shown";
2092                                 statustext_time = 0;
2093                         }
2094                         else if(show_profiler_graph)
2095                         {
2096                                 show_debug = false;
2097                                 show_profiler_graph = false;
2098                                 statustext = L"Debug info and profiler graph hidden";
2099                                 statustext_time = 0;
2100                         }
2101                         else
2102                         {
2103                                 show_profiler_graph = true;
2104                                 statustext = L"Profiler graph shown";
2105                                 statustext_time = 0;
2106                         }
2107                 }
2108                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2109                 {
2110                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2111
2112                         // FIXME: This updates the profiler with incomplete values
2113                         update_profiler_gui(guitext_profiler, font, text_height,
2114                                         show_profiler, show_profiler_max);
2115
2116                         if(show_profiler != 0)
2117                         {
2118                                 std::wstringstream sstr;
2119                                 sstr<<"Profiler shown (page "<<show_profiler
2120                                         <<" of "<<show_profiler_max<<")";
2121                                 statustext = sstr.str();
2122                                 statustext_time = 0;
2123                         }
2124                         else
2125                         {
2126                                 statustext = L"Profiler hidden";
2127                                 statustext_time = 0;
2128                         }
2129                 }
2130                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2131                 {
2132                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2133                         s16 range_new = range + 10;
2134                         g_settings->set("viewing_range_nodes_min", itos(range_new));
2135                         statustext = narrow_to_wide(
2136                                         "Minimum viewing range changed to "
2137                                         + itos(range_new));
2138                         statustext_time = 0;
2139                 }
2140                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2141                 {
2142                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2143                         s16 range_new = range - 10;
2144                         if(range_new < 0)
2145                                 range_new = range;
2146                         g_settings->set("viewing_range_nodes_min",
2147                                         itos(range_new));
2148                         statustext = narrow_to_wide(
2149                                         "Minimum viewing range changed to "
2150                                         + itos(range_new));
2151                         statustext_time = 0;
2152                 }
2153
2154                 // Reset jump_timer
2155                 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2156                 {
2157                         reset_jump_timer = false;
2158                         jump_timer = 0.0;
2159                 }
2160
2161                 // Handle QuicktuneShortcutter
2162                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2163                         quicktune.next();
2164                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2165                         quicktune.prev();
2166                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2167                         quicktune.inc();
2168                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2169                         quicktune.dec();
2170                 {
2171                         std::string msg = quicktune.getMessage();
2172                         if(msg != ""){
2173                                 statustext = narrow_to_wide(msg);
2174                                 statustext_time = 0;
2175                         }
2176                 }
2177
2178                 // Item selection with mouse wheel
2179                 u16 new_playeritem = client.getPlayerItem();
2180                 {
2181                         s32 wheel = input->getMouseWheel();
2182                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2183                                         player->hud_hotbar_itemcount-1);
2184
2185                         if(wheel < 0)
2186                         {
2187                                 if(new_playeritem < max_item)
2188                                         new_playeritem++;
2189                                 else
2190                                         new_playeritem = 0;
2191                         }
2192                         else if(wheel > 0)
2193                         {
2194                                 if(new_playeritem > 0)
2195                                         new_playeritem--;
2196                                 else
2197                                         new_playeritem = max_item;
2198                         }
2199                 }
2200
2201                 // Item selection
2202                 for(u16 i=0; i<10; i++)
2203                 {
2204                         const KeyPress *kp = NumberKey + (i + 1) % 10;
2205                         if(input->wasKeyDown(*kp))
2206                         {
2207                                 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2208                                 {
2209                                         new_playeritem = i;
2210
2211                                         infostream<<"Selected item: "
2212                                                         <<new_playeritem<<std::endl;
2213                                 }
2214                         }
2215                 }
2216
2217                 // Viewing range selection
2218                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2219                 {
2220                         draw_control.range_all = !draw_control.range_all;
2221                         if(draw_control.range_all)
2222                         {
2223                                 infostream<<"Enabled full viewing range"<<std::endl;
2224                                 statustext = L"Enabled full viewing range";
2225                                 statustext_time = 0;
2226                         }
2227                         else
2228                         {
2229                                 infostream<<"Disabled full viewing range"<<std::endl;
2230                                 statustext = L"Disabled full viewing range";
2231                                 statustext_time = 0;
2232                         }
2233                 }
2234
2235                 // Print debug stacks
2236                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2237                 {
2238                         dstream<<"-----------------------------------------"
2239                                         <<std::endl;
2240                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2241                         dstream<<"-----------------------------------------"
2242                                         <<std::endl;
2243                         debug_stacks_print();
2244                 }
2245
2246                 /*
2247                         Mouse and camera control
2248                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2249                 */
2250
2251                 float turn_amount = 0;
2252                 if((device->isWindowActive() && noMenuActive()) || random_input)
2253                 {
2254 #ifndef __ANDROID__
2255                         if(!random_input)
2256                         {
2257                                 // Mac OSX gets upset if this is set every frame
2258                                 if(device->getCursorControl()->isVisible())
2259                                         device->getCursorControl()->setVisible(false);
2260                         }
2261 #endif
2262
2263                         if(first_loop_after_window_activation){
2264                                 //infostream<<"window active, first loop"<<std::endl;
2265                                 first_loop_after_window_activation = false;
2266                         } else {
2267 #ifdef HAVE_TOUCHSCREENGUI
2268                                 if (g_touchscreengui) {
2269                                         camera_yaw   = g_touchscreengui->getYaw();
2270                                         camera_pitch = g_touchscreengui->getPitch();
2271                                 } else {
2272 #endif
2273                                         s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2274                                         s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2275                                 if ((invert_mouse)
2276                                                 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2277                                         dy = -dy;
2278                                 }
2279                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2280
2281                                 /*const float keyspeed = 500;
2282                                 if(input->isKeyDown(irr::KEY_UP))
2283                                         dy -= dtime * keyspeed;
2284                                 if(input->isKeyDown(irr::KEY_DOWN))
2285                                         dy += dtime * keyspeed;
2286                                 if(input->isKeyDown(irr::KEY_LEFT))
2287                                         dx -= dtime * keyspeed;
2288                                 if(input->isKeyDown(irr::KEY_RIGHT))
2289                                         dx += dtime * keyspeed;*/
2290
2291                                 float d = g_settings->getFloat("mouse_sensitivity");
2292                                 d = rangelim(d, 0.01, 100.0);
2293                                 camera_yaw -= dx*d;
2294                                 camera_pitch += dy*d;
2295                                 turn_amount = v2f(dx, dy).getLength() * d;
2296
2297 #ifdef HAVE_TOUCHSCREENGUI
2298                                 }
2299 #endif
2300                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
2301                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
2302                         }
2303                         input->setMousePos((driver->getScreenSize().Width/2),
2304                                         (driver->getScreenSize().Height/2));
2305                 }
2306                 else{
2307 #ifndef ANDROID
2308                         // Mac OSX gets upset if this is set every frame
2309                         if(device->getCursorControl()->isVisible() == false)
2310                                 device->getCursorControl()->setVisible(true);
2311 #endif
2312
2313                         //infostream<<"window inactive"<<std::endl;
2314                         first_loop_after_window_activation = true;
2315                 }
2316                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2317                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2318
2319                 /*
2320                         Player speed control
2321                 */
2322                 {
2323                         /*bool a_up,
2324                         bool a_down,
2325                         bool a_left,
2326                         bool a_right,
2327                         bool a_jump,
2328                         bool a_superspeed,
2329                         bool a_sneak,
2330                         bool a_LMB,
2331                         bool a_RMB,
2332                         float a_pitch,
2333                         float a_yaw*/
2334                         PlayerControl control(
2335                                 input->isKeyDown(getKeySetting("keymap_forward")),
2336                                 input->isKeyDown(getKeySetting("keymap_backward")),
2337                                 input->isKeyDown(getKeySetting("keymap_left")),
2338                                 input->isKeyDown(getKeySetting("keymap_right")),
2339                                 input->isKeyDown(getKeySetting("keymap_jump")),
2340                                 input->isKeyDown(getKeySetting("keymap_special1")),
2341                                 input->isKeyDown(getKeySetting("keymap_sneak")),
2342                                 input->getLeftState(),
2343                                 input->getRightState(),
2344                                 camera_pitch,
2345                                 camera_yaw
2346                         );
2347                         client.setPlayerControl(control);
2348                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2349                         player->keyPressed=
2350                         (((int)input->isKeyDown(getKeySetting("keymap_forward"))  & 0x1) << 0) |
2351                         (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2352                         (((int)input->isKeyDown(getKeySetting("keymap_left"))     & 0x1) << 2) |
2353                         (((int)input->isKeyDown(getKeySetting("keymap_right"))    & 0x1) << 3) |
2354                         (((int)input->isKeyDown(getKeySetting("keymap_jump"))     & 0x1) << 4) |
2355                         (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2356                         (((int)input->isKeyDown(getKeySetting("keymap_sneak"))    & 0x1) << 6) |
2357                         (((int)input->getLeftState()  & 0x1) << 7) |
2358                         (((int)input->getRightState() & 0x1) << 8);
2359                 }
2360
2361                 /*
2362                         Run server, client (and process environments)
2363                 */
2364                 bool can_be_and_is_paused =
2365                                 (simple_singleplayer_mode && g_menumgr.pausesGame());
2366                 if(can_be_and_is_paused)
2367                 {
2368                         // No time passes
2369                         dtime = 0;
2370                 }
2371                 else
2372                 {
2373                         if(server != NULL)
2374                         {
2375                                 //TimeTaker timer("server->step(dtime)");
2376                                 server->step(dtime);
2377                         }
2378                         {
2379                                 //TimeTaker timer("client.step(dtime)");
2380                                 client.step(dtime);
2381                         }
2382                 }
2383
2384                 {
2385                         // Read client events
2386                         for(;;) {
2387                                 ClientEvent event = client.getClientEvent();
2388                                 if(event.type == CE_NONE) {
2389                                         break;
2390                                 }
2391                                 else if(event.type == CE_PLAYER_DAMAGE &&
2392                                                 client.getHP() != 0) {
2393                                         //u16 damage = event.player_damage.amount;
2394                                         //infostream<<"Player damage: "<<damage<<std::endl;
2395
2396                                         damage_flash += 100.0;
2397                                         damage_flash += 8.0 * event.player_damage.amount;
2398
2399                                         player->hurt_tilt_timer = 1.5;
2400                                         player->hurt_tilt_strength = event.player_damage.amount/4;
2401                                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2402
2403                                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2404                                         gamedef->event()->put(e);
2405                                 }
2406                                 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2407                                         camera_yaw = event.player_force_move.yaw;
2408                                         camera_pitch = event.player_force_move.pitch;
2409                                 }
2410                                 else if(event.type == CE_DEATHSCREEN) {
2411                                         show_deathscreen(&current_formspec, &client, gamedef, tsrc,
2412                                                         device, &client);
2413
2414                                         chat_backend.addMessage(L"", L"You died.");
2415
2416                                         /* Handle visualization */
2417                                         damage_flash = 0;
2418
2419                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2420                                         player->hurt_tilt_timer = 0;
2421                                         player->hurt_tilt_strength = 0;
2422
2423                                 }
2424                                 else if (event.type == CE_SHOW_FORMSPEC) {
2425                                         FormspecFormSource* fs_src =
2426                                                         new FormspecFormSource(*(event.show_formspec.formspec));
2427                                         TextDestPlayerInventory* txt_dst =
2428                                                         new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2429
2430                                         create_formspec_menu(&current_formspec, &client, gamedef,
2431                                                         tsrc, device, fs_src, txt_dst);
2432
2433                                         delete(event.show_formspec.formspec);
2434                                         delete(event.show_formspec.formname);
2435                                 }
2436                                 else if(event.type == CE_SPAWN_PARTICLE) {
2437                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2438                                         video::ITexture *texture =
2439                                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2440
2441                                         new Particle(gamedef, smgr, player, client.getEnv(),
2442                                                 *event.spawn_particle.pos,
2443                                                 *event.spawn_particle.vel,
2444                                                 *event.spawn_particle.acc,
2445                                                  event.spawn_particle.expirationtime,
2446                                                  event.spawn_particle.size,
2447                                                  event.spawn_particle.collisiondetection,
2448                                                  event.spawn_particle.vertical,
2449                                                  texture,
2450                                                  v2f(0.0, 0.0),
2451                                                  v2f(1.0, 1.0));
2452                                 }
2453                                 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2454                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2455                                         video::ITexture *texture =
2456                                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2457
2458                                         new ParticleSpawner(gamedef, smgr, player,
2459                                                  event.add_particlespawner.amount,
2460                                                  event.add_particlespawner.spawntime,
2461                                                 *event.add_particlespawner.minpos,
2462                                                 *event.add_particlespawner.maxpos,
2463                                                 *event.add_particlespawner.minvel,
2464                                                 *event.add_particlespawner.maxvel,
2465                                                 *event.add_particlespawner.minacc,
2466                                                 *event.add_particlespawner.maxacc,
2467                                                  event.add_particlespawner.minexptime,
2468                                                  event.add_particlespawner.maxexptime,
2469                                                  event.add_particlespawner.minsize,
2470                                                  event.add_particlespawner.maxsize,
2471                                                  event.add_particlespawner.collisiondetection,
2472                                                  event.add_particlespawner.vertical,
2473                                                  texture,
2474                                                  event.add_particlespawner.id);
2475                                 }
2476                                 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2477                                         delete_particlespawner (event.delete_particlespawner.id);
2478                                 }
2479                                 else if (event.type == CE_HUDADD) {
2480                                         u32 id = event.hudadd.id;
2481
2482                                         HudElement *e = player->getHud(id);
2483
2484                                         if (e != NULL) {
2485                                                 delete event.hudadd.pos;
2486                                                 delete event.hudadd.name;
2487                                                 delete event.hudadd.scale;
2488                                                 delete event.hudadd.text;
2489                                                 delete event.hudadd.align;
2490                                                 delete event.hudadd.offset;
2491                                                 delete event.hudadd.world_pos;
2492                                                 delete event.hudadd.size;
2493                                                 continue;
2494                                         }
2495
2496                                         e = new HudElement;
2497                                         e->type   = (HudElementType)event.hudadd.type;
2498                                         e->pos    = *event.hudadd.pos;
2499                                         e->name   = *event.hudadd.name;
2500                                         e->scale  = *event.hudadd.scale;
2501                                         e->text   = *event.hudadd.text;
2502                                         e->number = event.hudadd.number;
2503                                         e->item   = event.hudadd.item;
2504                                         e->dir    = event.hudadd.dir;
2505                                         e->align  = *event.hudadd.align;
2506                                         e->offset = *event.hudadd.offset;
2507                                         e->world_pos = *event.hudadd.world_pos;
2508                                         e->size = *event.hudadd.size;
2509
2510                                         u32 new_id = player->addHud(e);
2511                                         //if this isn't true our huds aren't consistent
2512                                         assert(new_id == id);
2513
2514                                         delete event.hudadd.pos;
2515                                         delete event.hudadd.name;
2516                                         delete event.hudadd.scale;
2517                                         delete event.hudadd.text;
2518                                         delete event.hudadd.align;
2519                                         delete event.hudadd.offset;
2520                                         delete event.hudadd.world_pos;
2521                                         delete event.hudadd.size;
2522                                 }
2523                                 else if (event.type == CE_HUDRM) {
2524                                         HudElement* e = player->removeHud(event.hudrm.id);
2525
2526                                         if (e != NULL)
2527                                                 delete (e);
2528                                 }
2529                                 else if (event.type == CE_HUDCHANGE) {
2530                                         u32 id = event.hudchange.id;
2531                                         HudElement* e = player->getHud(id);
2532                                         if (e == NULL)
2533                                         {
2534                                                 delete event.hudchange.v3fdata;
2535                                                 delete event.hudchange.v2fdata;
2536                                                 delete event.hudchange.sdata;
2537                                                 delete event.hudchange.v2s32data;
2538                                                 continue;
2539                                         }
2540
2541                                         switch (event.hudchange.stat) {
2542                                                 case HUD_STAT_POS:
2543                                                         e->pos = *event.hudchange.v2fdata;
2544                                                         break;
2545                                                 case HUD_STAT_NAME:
2546                                                         e->name = *event.hudchange.sdata;
2547                                                         break;
2548                                                 case HUD_STAT_SCALE:
2549                                                         e->scale = *event.hudchange.v2fdata;
2550                                                         break;
2551                                                 case HUD_STAT_TEXT:
2552                                                         e->text = *event.hudchange.sdata;
2553                                                         break;
2554                                                 case HUD_STAT_NUMBER:
2555                                                         e->number = event.hudchange.data;
2556                                                         break;
2557                                                 case HUD_STAT_ITEM:
2558                                                         e->item = event.hudchange.data;
2559                                                         break;
2560                                                 case HUD_STAT_DIR:
2561                                                         e->dir = event.hudchange.data;
2562                                                         break;
2563                                                 case HUD_STAT_ALIGN:
2564                                                         e->align = *event.hudchange.v2fdata;
2565                                                         break;
2566                                                 case HUD_STAT_OFFSET:
2567                                                         e->offset = *event.hudchange.v2fdata;
2568                                                         break;
2569                                                 case HUD_STAT_WORLD_POS:
2570                                                         e->world_pos = *event.hudchange.v3fdata;
2571                                                         break;
2572                                                 case HUD_STAT_SIZE:
2573                                                         e->size = *event.hudchange.v2s32data;
2574                                                         break;
2575                                         }
2576
2577                                         delete event.hudchange.v3fdata;
2578                                         delete event.hudchange.v2fdata;
2579                                         delete event.hudchange.sdata;
2580                                         delete event.hudchange.v2s32data;
2581                                 }
2582                                 else if (event.type == CE_SET_SKY) {
2583                                         sky->setVisible(false);
2584                                         if(skybox){
2585                                                 skybox->remove();
2586                                                 skybox = NULL;
2587                                         }
2588                                         // Handle according to type
2589                                         if(*event.set_sky.type == "regular") {
2590                                                 sky->setVisible(true);
2591                                         }
2592                                         else if(*event.set_sky.type == "skybox" &&
2593                                                         event.set_sky.params->size() == 6) {
2594                                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2595                                                 skybox = smgr->addSkyBoxSceneNode(
2596                                                                 tsrc->getTexture((*event.set_sky.params)[0]),
2597                                                                 tsrc->getTexture((*event.set_sky.params)[1]),
2598                                                                 tsrc->getTexture((*event.set_sky.params)[2]),
2599                                                                 tsrc->getTexture((*event.set_sky.params)[3]),
2600                                                                 tsrc->getTexture((*event.set_sky.params)[4]),
2601                                                                 tsrc->getTexture((*event.set_sky.params)[5]));
2602                                         }
2603                                         // Handle everything else as plain color
2604                                         else {
2605                                                 if(*event.set_sky.type != "plain")
2606                                                         infostream<<"Unknown sky type: "
2607                                                                         <<(*event.set_sky.type)<<std::endl;
2608                                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2609                                         }
2610
2611                                         delete event.set_sky.bgcolor;
2612                                         delete event.set_sky.type;
2613                                         delete event.set_sky.params;
2614                                 }
2615                                 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2616                                         bool enable = event.override_day_night_ratio.do_override;
2617                                         u32 value = event.override_day_night_ratio.ratio_f * 1000;
2618                                         client.getEnv().setDayNightRatioOverride(enable, value);
2619                                 }
2620                         }
2621                 }
2622
2623                 //TimeTaker //timer2("//timer2");
2624
2625                 /*
2626                         For interaction purposes, get info about the held item
2627                         - What item is it?
2628                         - Is it a usable item?
2629                         - Can it point to liquids?
2630                 */
2631                 ItemStack playeritem;
2632                 {
2633                         InventoryList *mlist = local_inventory.getList("main");
2634                         if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2635                                 playeritem = mlist->getItem(client.getPlayerItem());
2636                 }
2637                 const ItemDefinition &playeritem_def =
2638                                 playeritem.getDefinition(itemdef);
2639                 ToolCapabilities playeritem_toolcap =
2640                                 playeritem.getToolCapabilities(itemdef);
2641
2642                 /*
2643                         Update camera
2644                 */
2645
2646                 v3s16 old_camera_offset = camera.getOffset();
2647
2648                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2649                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2650                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2651
2652                 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2653                         camera.toggleCameraMode();
2654                         GenericCAO* playercao = player->getCAO();
2655
2656                         assert( playercao != NULL );
2657                         if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2658                                 playercao->setVisible(true);
2659                         }
2660                         else {
2661                                 playercao->setVisible(false);
2662                         }
2663                 }
2664                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2665                 camera.update(player, dtime, busytime, tool_reload_ratio,
2666                                 client.getEnv());
2667                 camera.step(dtime);
2668
2669                 v3f player_position = player->getPosition();
2670                 v3f camera_position = camera.getPosition();
2671                 v3f camera_direction = camera.getDirection();
2672                 f32 camera_fov = camera.getFovMax();
2673                 v3s16 camera_offset = camera.getOffset();
2674
2675                 bool camera_offset_changed = (camera_offset != old_camera_offset);
2676
2677                 if(!disable_camera_update){
2678                         client.getEnv().getClientMap().updateCamera(camera_position,
2679                                 camera_direction, camera_fov, camera_offset);
2680                         if (camera_offset_changed){
2681                                 client.updateCameraOffset(camera_offset);
2682                                 client.getEnv().updateCameraOffset(camera_offset);
2683                                 if (clouds)
2684                                         clouds->updateCameraOffset(camera_offset);
2685                         }
2686                 }
2687
2688                 // Update sound listener
2689                 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2690                                 v3f(0,0,0), // velocity
2691                                 camera.getDirection(),
2692                                 camera.getCameraNode()->getUpVector());
2693                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2694
2695                 /*
2696                         Update sound maker
2697                 */
2698                 {
2699                         soundmaker.step(dtime);
2700
2701                         ClientMap &map = client.getEnv().getClientMap();
2702                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2703                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2704                 }
2705
2706                 /*
2707                         Calculate what block is the crosshair pointing to
2708                 */
2709
2710                 //u32 t1 = device->getTimer()->getRealTime();
2711
2712                 f32 d = playeritem_def.range; // max. distance
2713                 f32 d_hand = itemdef->get("").range;
2714                 if(d < 0 && d_hand >= 0)
2715                         d = d_hand;
2716                 else if(d < 0)
2717                         d = 4.0;
2718                 core::line3d<f32> shootline(camera_position,
2719                                 camera_position + camera_direction * BS * (d+1));
2720
2721
2722                 // prevent player pointing anything in front-view
2723                 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2724                         shootline = core::line3d<f32>(0,0,0,0,0,0);
2725
2726 #ifdef HAVE_TOUCHSCREENGUI
2727                 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2728                         shootline = g_touchscreengui->getShootline();
2729                         shootline.start += intToFloat(camera_offset,BS);
2730                         shootline.end += intToFloat(camera_offset,BS);
2731                 }
2732 #endif
2733
2734                 ClientActiveObject *selected_object = NULL;
2735
2736                 PointedThing pointed = getPointedThing(
2737                                 // input
2738                                 &client, player_position, camera_direction,
2739                                 camera_position, shootline, d,
2740                                 playeritem_def.liquids_pointable, !ldown_for_dig,
2741                                 camera_offset,
2742                                 // output
2743                                 hilightboxes,
2744                                 selected_object);
2745
2746                 if(pointed != pointed_old)
2747                 {
2748                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2749                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2750                 }
2751
2752                 /*
2753                         Stop digging when
2754                         - releasing left mouse button
2755                         - pointing away from node
2756                 */
2757                 if(digging)
2758                 {
2759                         if(input->getLeftReleased())
2760                         {
2761                                 infostream<<"Left button released"
2762                                         <<" (stopped digging)"<<std::endl;
2763                                 digging = false;
2764                         }
2765                         else if(pointed != pointed_old)
2766                         {
2767                                 if (pointed.type == POINTEDTHING_NODE
2768                                         && pointed_old.type == POINTEDTHING_NODE
2769                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2770                                 {
2771                                         // Still pointing to the same node,
2772                                         // but a different face. Don't reset.
2773                                 }
2774                                 else
2775                                 {
2776                                         infostream<<"Pointing away from node"
2777                                                 <<" (stopped digging)"<<std::endl;
2778                                         digging = false;
2779                                 }
2780                         }
2781                         if(!digging)
2782                         {
2783                                 client.interact(1, pointed_old);
2784                                 client.setCrack(-1, v3s16(0,0,0));
2785                                 dig_time = 0.0;
2786                         }
2787                 }
2788                 if(!digging && ldown_for_dig && !input->getLeftState())
2789                 {
2790                         ldown_for_dig = false;
2791                 }
2792
2793                 bool left_punch = false;
2794                 soundmaker.m_player_leftpunch_sound.name = "";
2795
2796                 if(input->getRightState())
2797                         repeat_rightclick_timer += dtime;
2798                 else
2799                         repeat_rightclick_timer = 0;
2800
2801                 if(playeritem_def.usable && input->getLeftState())
2802                 {
2803                         if(input->getLeftClicked())
2804                                 client.interact(4, pointed);
2805                 }
2806                 else if(pointed.type == POINTEDTHING_NODE)
2807                 {
2808                         v3s16 nodepos = pointed.node_undersurface;
2809                         v3s16 neighbourpos = pointed.node_abovesurface;
2810
2811                         /*
2812                                 Check information text of node
2813                         */
2814
2815                         ClientMap &map = client.getEnv().getClientMap();
2816                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2817                         if(meta){
2818                                 infotext = narrow_to_wide(meta->getString("infotext"));
2819                         } else {
2820                                 MapNode n = map.getNode(nodepos);
2821                                 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2822                                         infotext = L"Unknown node: ";
2823                                         infotext += narrow_to_wide(nodedef->get(n).name);
2824                                 }
2825                         }
2826
2827                         /*
2828                                 Handle digging
2829                         */
2830
2831                         if(nodig_delay_timer <= 0.0 && input->getLeftState()
2832                                         && client.checkPrivilege("interact"))
2833                         {
2834                                 if(!digging)
2835                                 {
2836                                         infostream<<"Started digging"<<std::endl;
2837                                         client.interact(0, pointed);
2838                                         digging = true;
2839                                         ldown_for_dig = true;
2840                                 }
2841                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2842
2843                                 // NOTE: Similar piece of code exists on the server side for
2844                                 // cheat detection.
2845                                 // Get digging parameters
2846                                 DigParams params = getDigParams(nodedef->get(n).groups,
2847                                                 &playeritem_toolcap);
2848                                 // If can't dig, try hand
2849                                 if(!params.diggable){
2850                                         const ItemDefinition &hand = itemdef->get("");
2851                                         const ToolCapabilities *tp = hand.tool_capabilities;
2852                                         if(tp)
2853                                                 params = getDigParams(nodedef->get(n).groups, tp);
2854                                 }
2855
2856                                 float dig_time_complete = 0.0;
2857
2858                                 if(params.diggable == false)
2859                                 {
2860                                         // I guess nobody will wait for this long
2861                                         dig_time_complete = 10000000.0;
2862                                 }
2863                                 else
2864                                 {
2865                                         dig_time_complete = params.time;
2866                                         if (g_settings->getBool("enable_particles"))
2867                                         {
2868                                                 const ContentFeatures &features =
2869                                                         client.getNodeDefManager()->get(n);
2870                                                 addPunchingParticles
2871                                                         (gamedef, smgr, player, client.getEnv(),
2872                                                          nodepos, features.tiles);
2873                                         }
2874                                 }
2875
2876                                 if(dig_time_complete >= 0.001)
2877                                 {
2878                                         dig_index = (u16)((float)crack_animation_length
2879                                                         * dig_time/dig_time_complete);
2880                                 }
2881                                 // This is for torches
2882                                 else
2883                                 {
2884                                         dig_index = crack_animation_length;
2885                                 }
2886
2887                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2888                                 if(sound_dig.exists() && params.diggable){
2889                                         if(sound_dig.name == "__group"){
2890                                                 if(params.main_group != ""){
2891                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2892                                                         soundmaker.m_player_leftpunch_sound.name =
2893                                                                         std::string("default_dig_") +
2894                                                                                         params.main_group;
2895                                                 }
2896                                         } else{
2897                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2898                                         }
2899                                 }
2900
2901                                 // Don't show cracks if not diggable
2902                                 if(dig_time_complete >= 100000.0)
2903                                 {
2904                                 }
2905                                 else if(dig_index < crack_animation_length)
2906                                 {
2907                                         //TimeTaker timer("client.setTempMod");
2908                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2909                                         client.setCrack(dig_index, nodepos);
2910                                 }
2911                                 else
2912                                 {
2913                                         infostream<<"Digging completed"<<std::endl;
2914                                         client.interact(2, pointed);
2915                                         client.setCrack(-1, v3s16(0,0,0));
2916                                         MapNode wasnode = map.getNode(nodepos);
2917                                         client.removeNode(nodepos);
2918
2919                                         if (g_settings->getBool("enable_particles"))
2920                                         {
2921                                                 const ContentFeatures &features =
2922                                                         client.getNodeDefManager()->get(wasnode);
2923                                                 addDiggingParticles
2924                                                         (gamedef, smgr, player, client.getEnv(),
2925                                                          nodepos, features.tiles);
2926                                         }
2927
2928                                         dig_time = 0;
2929                                         digging = false;
2930
2931                                         nodig_delay_timer = dig_time_complete
2932                                                         / (float)crack_animation_length;
2933
2934                                         // We don't want a corresponding delay to
2935                                         // very time consuming nodes
2936                                         if(nodig_delay_timer > 0.3)
2937                                                 nodig_delay_timer = 0.3;
2938                                         // We want a slight delay to very little
2939                                         // time consuming nodes
2940                                         float mindelay = 0.15;
2941                                         if(nodig_delay_timer < mindelay)
2942                                                 nodig_delay_timer = mindelay;
2943
2944                                         // Send event to trigger sound
2945                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2946                                         gamedef->event()->put(e);
2947                                 }
2948
2949                                 if(dig_time_complete < 100000.0)
2950                                         dig_time += dtime;
2951                                 else {
2952                                         dig_time = 0;
2953                                         client.setCrack(-1, nodepos);
2954                                 }
2955
2956                                 camera.setDigging(0);  // left click animation
2957                         }
2958
2959                         if((input->getRightClicked() ||
2960                                         repeat_rightclick_timer >=
2961                                                 g_settings->getFloat("repeat_rightclick_time")) &&
2962                                         client.checkPrivilege("interact"))
2963                         {
2964                                 repeat_rightclick_timer = 0;
2965                                 infostream<<"Ground right-clicked"<<std::endl;
2966
2967                                 if(meta && meta->getString("formspec") != "" && !random_input
2968                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2969                                 {
2970                                         infostream<<"Launching custom inventory view"<<std::endl;
2971
2972                                         InventoryLocation inventoryloc;
2973                                         inventoryloc.setNodeMeta(nodepos);
2974
2975                                         NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
2976                                                         &client.getEnv().getClientMap(), nodepos);
2977                                         TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
2978
2979                                         create_formspec_menu(&current_formspec, &client, gamedef,
2980                                                         tsrc, device, fs_src, txt_dst);
2981
2982                                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
2983                                 }
2984                                 // Otherwise report right click to server
2985                                 else
2986                                 {
2987                                         camera.setDigging(1);  // right click animation (always shown for feedback)
2988
2989                                         // If the wielded item has node placement prediction,
2990                                         // make that happen
2991                                         bool placed = nodePlacementPrediction(client,
2992                                                 playeritem_def,
2993                                                 nodepos, neighbourpos);
2994
2995                                         if(placed) {
2996                                                 // Report to server
2997                                                 client.interact(3, pointed);
2998                                                 // Read the sound
2999                                                 soundmaker.m_player_rightpunch_sound =
3000                                                         playeritem_def.sound_place;
3001                                         } else {
3002                                                 soundmaker.m_player_rightpunch_sound =
3003                                                         SimpleSoundSpec();
3004                                         }
3005
3006                                         if (playeritem_def.node_placement_prediction == "" ||
3007                                                 nodedef->get(map.getNode(nodepos)).rightclickable)
3008                                                 client.interact(3, pointed); // Report to server
3009                                 }
3010                         }
3011                 }
3012                 else if(pointed.type == POINTEDTHING_OBJECT)
3013                 {
3014                         infotext = narrow_to_wide(selected_object->infoText());
3015
3016                         if(infotext == L"" && show_debug){
3017                                 infotext = narrow_to_wide(selected_object->debugInfoText());
3018                         }
3019
3020                         //if(input->getLeftClicked())
3021                         if(input->getLeftState())
3022                         {
3023                                 bool do_punch = false;
3024                                 bool do_punch_damage = false;
3025                                 if(object_hit_delay_timer <= 0.0){
3026                                         do_punch = true;
3027                                         do_punch_damage = true;
3028                                         object_hit_delay_timer = object_hit_delay;
3029                                 }
3030                                 if(input->getLeftClicked()){
3031                                         do_punch = true;
3032                                 }
3033                                 if(do_punch){
3034                                         infostream<<"Left-clicked object"<<std::endl;
3035                                         left_punch = true;
3036                                 }
3037                                 if(do_punch_damage){
3038                                         // Report direct punch
3039                                         v3f objpos = selected_object->getPosition();
3040                                         v3f dir = (objpos - player_position).normalize();
3041
3042                                         bool disable_send = selected_object->directReportPunch(
3043                                                         dir, &playeritem, time_from_last_punch);
3044                                         time_from_last_punch = 0;
3045                                         if(!disable_send)
3046                                                 client.interact(0, pointed);
3047                                 }
3048                         }
3049                         else if(input->getRightClicked())
3050                         {
3051                                 infostream<<"Right-clicked object"<<std::endl;
3052                                 client.interact(3, pointed);  // place
3053                         }
3054                 }
3055                 else if(input->getLeftState())
3056                 {
3057                         // When button is held down in air, show continuous animation
3058                         left_punch = true;
3059                 }
3060
3061                 pointed_old = pointed;
3062
3063                 if(left_punch || input->getLeftClicked())
3064                 {
3065                         camera.setDigging(0); // left click animation
3066                 }
3067
3068                 input->resetLeftClicked();
3069                 input->resetRightClicked();
3070
3071                 input->resetLeftReleased();
3072                 input->resetRightReleased();
3073
3074                 /*
3075                         Calculate stuff for drawing
3076                 */
3077
3078                 /*
3079                         Fog range
3080                 */
3081
3082                 if(draw_control.range_all)
3083                         fog_range = 100000*BS;
3084                 else {
3085                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3086                         fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3087                         fog_range *= 0.9;
3088                 }
3089
3090                 /*
3091                         Calculate general brightness
3092                 */
3093                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3094                 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3095                 float direct_brightness = 0;
3096                 bool sunlight_seen = false;
3097                 if(g_settings->getBool("free_move")){
3098                         direct_brightness = time_brightness;
3099                         sunlight_seen = true;
3100                 } else {
3101                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3102                         float old_brightness = sky->getBrightness();
3103                         direct_brightness = (float)client.getEnv().getClientMap()
3104                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3105                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3106                                         / 255.0;
3107                 }
3108
3109                 time_of_day = client.getEnv().getTimeOfDayF();
3110                 float maxsm = 0.05;
3111                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3112                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3113                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3114                         time_of_day_smooth = time_of_day;
3115                 float todsm = 0.05;
3116                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3117                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3118                                         + (time_of_day+1.0) * todsm;
3119                 else
3120                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3121                                         + time_of_day * todsm;
3122
3123                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3124                                 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3125                                 player->getPitch());
3126
3127                 video::SColor bgcolor = sky->getBgColor();
3128                 video::SColor skycolor = sky->getSkyColor();
3129
3130                 /*
3131                         Update clouds
3132                 */
3133                 if(clouds){
3134                         if(sky->getCloudsVisible()){
3135                                 clouds->setVisible(true);
3136                                 clouds->step(dtime);
3137                                 clouds->update(v2f(player_position.X, player_position.Z),
3138                                                 sky->getCloudColor());
3139                         } else{
3140                                 clouds->setVisible(false);
3141                         }
3142                 }
3143
3144                 /*
3145                         Update particles
3146                 */
3147
3148                 allparticles_step(dtime);
3149                 allparticlespawners_step(dtime, client.getEnv());
3150
3151                 /*
3152                         Fog
3153                 */
3154
3155                 if(g_settings->getBool("enable_fog") && !force_fog_off)
3156                 {
3157                         driver->setFog(
3158                                 bgcolor,
3159                                 video::EFT_FOG_LINEAR,
3160                                 fog_range*0.4,
3161                                 fog_range*1.0,
3162                                 0.01,
3163                                 false, // pixel fog
3164                                 false // range fog
3165                         );
3166                 }
3167                 else
3168                 {
3169                         driver->setFog(
3170                                 bgcolor,
3171                                 video::EFT_FOG_LINEAR,
3172                                 100000*BS,
3173                                 110000*BS,
3174                                 0.01,
3175                                 false, // pixel fog
3176                                 false // range fog
3177                         );
3178                 }
3179
3180                 /*
3181                         Update gui stuff (0ms)
3182                 */
3183
3184                 //TimeTaker guiupdatetimer("Gui updating");
3185
3186                 if(show_debug)
3187                 {
3188                         static float drawtime_avg = 0;
3189                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3190                         /*static float beginscenetime_avg = 0;
3191                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3192                         static float scenetime_avg = 0;
3193                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3194                         static float endscenetime_avg = 0;
3195                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3196
3197                         u16 fps = (1.0/dtime_avg1);
3198
3199                         std::ostringstream os(std::ios_base::binary);
3200                         os<<std::fixed
3201                                 <<"Minetest "<<minetest_version_hash
3202                                 <<" FPS = "<<fps
3203                                 <<" (R: range_all="<<draw_control.range_all<<")"
3204                                 <<std::setprecision(0)
3205                                 <<" drawtime = "<<drawtime_avg
3206                                 <<std::setprecision(1)
3207                                 <<", dtime_jitter = "
3208                                 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3209                                 <<std::setprecision(1)
3210                                 <<", v_range = "<<draw_control.wanted_range
3211                                 <<std::setprecision(3)
3212                                 <<", RTT = "<<client.getRTT();
3213                         guitext->setText(narrow_to_wide(os.str()).c_str());
3214                         guitext->setVisible(true);
3215                 }
3216                 else if(show_hud || show_chat)
3217                 {
3218                         std::ostringstream os(std::ios_base::binary);
3219                         os<<"Minetest "<<minetest_version_hash;
3220                         guitext->setText(narrow_to_wide(os.str()).c_str());
3221                         guitext->setVisible(true);
3222                 }
3223                 else
3224                 {
3225                         guitext->setVisible(false);
3226                 }
3227
3228                 if (guitext->isVisible())
3229                 {
3230                         core::rect<s32> rect(
3231                                 5,
3232                                 5,
3233                                 screensize.X,
3234                                 5 + text_height
3235                         );
3236                         guitext->setRelativePosition(rect);
3237                 }
3238
3239                 if(show_debug)
3240                 {
3241                         std::ostringstream os(std::ios_base::binary);
3242                         os<<std::setprecision(1)<<std::fixed
3243                                 <<"(" <<(player_position.X/BS)
3244                                 <<", "<<(player_position.Y/BS)
3245                                 <<", "<<(player_position.Z/BS)
3246                                 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3247                                 <<") (seed = "<<((u64)client.getMapSeed())
3248                                 <<")";
3249                         guitext2->setText(narrow_to_wide(os.str()).c_str());
3250                         guitext2->setVisible(true);
3251
3252                         core::rect<s32> rect(
3253                                 5,
3254                                 5 + text_height,
3255                                 screensize.X,
3256                                 5 + (text_height * 2)
3257                         );
3258                         guitext2->setRelativePosition(rect);
3259                 }
3260                 else
3261                 {
3262                         guitext2->setVisible(false);
3263                 }
3264
3265                 {
3266                         guitext_info->setText(infotext.c_str());
3267                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3268                 }
3269
3270                 {
3271                         float statustext_time_max = 1.5;
3272                         if(!statustext.empty())
3273                         {
3274                                 statustext_time += dtime;
3275                                 if(statustext_time >= statustext_time_max)
3276                                 {
3277                                         statustext = L"";
3278                                         statustext_time = 0;
3279                                 }
3280                         }
3281                         guitext_status->setText(statustext.c_str());
3282                         guitext_status->setVisible(!statustext.empty());
3283
3284                         if(!statustext.empty())
3285                         {
3286                                 s32 status_y = screensize.Y - 130;
3287                                 core::rect<s32> rect(
3288                                                 10,
3289                                                 status_y - guitext_status->getTextHeight(),
3290                                                 10 + guitext_status->getTextWidth(),
3291                                                 status_y
3292                                 );
3293                                 guitext_status->setRelativePosition(rect);
3294
3295                                 // Fade out
3296                                 video::SColor initial_color(255,0,0,0);
3297                                 if(guienv->getSkin())
3298                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3299                                 video::SColor final_color = initial_color;
3300                                 final_color.setAlpha(0);
3301                                 video::SColor fade_color =
3302                                         initial_color.getInterpolated_quadratic(
3303                                                 initial_color,
3304                                                 final_color,
3305                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
3306                                 guitext_status->setOverrideColor(fade_color);
3307                                 guitext_status->enableOverrideColor(true);
3308                         }
3309                 }
3310
3311                 /*
3312                         Get chat messages from client
3313                 */
3314                 {
3315                         // Get new messages from error log buffer
3316                         while(!chat_log_error_buf.empty())
3317                         {
3318                                 chat_backend.addMessage(L"", narrow_to_wide(
3319                                                 chat_log_error_buf.get()));
3320                         }
3321                         // Get new messages from client
3322                         std::wstring message;
3323                         while(client.getChatMessage(message))
3324                         {
3325                                 chat_backend.addUnparsedMessage(message);
3326                         }
3327                         // Remove old messages
3328                         chat_backend.step(dtime);
3329
3330                         // Display all messages in a static text element
3331                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3332                         std::wstring recent_chat = chat_backend.getRecentChat();
3333                         guitext_chat->setText(recent_chat.c_str());
3334
3335                         // Update gui element size and position
3336                         s32 chat_y = 5+(text_height+5);
3337                         if(show_debug)
3338                                 chat_y += (text_height+5);
3339                         core::rect<s32> rect(
3340                                 10,
3341                                 chat_y,
3342                                 screensize.X - 10,
3343                                 chat_y + guitext_chat->getTextHeight()
3344                         );
3345                         guitext_chat->setRelativePosition(rect);
3346
3347                         // Don't show chat if disabled or empty or profiler is enabled
3348                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
3349                                         && !show_profiler);
3350                 }
3351
3352                 /*
3353                         Inventory
3354                 */
3355
3356                 if(client.getPlayerItem() != new_playeritem)
3357                 {
3358                         client.selectPlayerItem(new_playeritem);
3359                 }
3360                 if(client.getLocalInventoryUpdated())
3361                 {
3362                         //infostream<<"Updating local inventory"<<std::endl;
3363                         client.getLocalInventory(local_inventory);
3364
3365                         update_wielded_item_trigger = true;
3366                 }
3367                 if(update_wielded_item_trigger)
3368                 {
3369                         update_wielded_item_trigger = false;
3370                         // Update wielded tool
3371                         InventoryList *mlist = local_inventory.getList("main");
3372                         ItemStack item;
3373                         if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3374                                 item = mlist->getItem(client.getPlayerItem());
3375                         camera.wield(item, client.getPlayerItem());
3376                 }
3377
3378                 /*
3379                         Update block draw list every 200ms or when camera direction has
3380                         changed much
3381                 */
3382                 update_draw_list_timer += dtime;
3383                 if(update_draw_list_timer >= 0.2 ||
3384                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3385                                 camera_offset_changed){
3386                         update_draw_list_timer = 0;
3387                         client.getEnv().getClientMap().updateDrawList(driver);
3388                         update_draw_list_last_cam_dir = camera_direction;
3389                 }
3390
3391                 /*
3392                         Drawing begins
3393                 */
3394                 TimeTaker tt_draw("mainloop: draw");
3395                 {
3396                         TimeTaker timer("beginScene");
3397                         driver->beginScene(true, true, skycolor);
3398                         beginscenetime = timer.stop(true);
3399                 }
3400
3401
3402                 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3403                                 hilightboxes, screensize, skycolor, show_hud);
3404
3405                 /*
3406                         Profiler graph
3407                 */
3408                 if(show_profiler_graph)
3409                 {
3410                         graph.draw(10, screensize.Y - 10, driver, font);
3411                 }
3412
3413                 /*
3414                         Damage flash
3415                 */
3416                 if(damage_flash > 0.0)
3417                 {
3418                         video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3419                         driver->draw2DRectangle(color,
3420                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
3421                                         NULL);
3422
3423                         damage_flash -= 100.0*dtime;
3424                 }
3425
3426                 /*
3427                         Damage camera tilt
3428                 */
3429                 if(player->hurt_tilt_timer > 0.0)
3430                 {
3431                         player->hurt_tilt_timer -= dtime*5;
3432                         if(player->hurt_tilt_timer < 0)
3433                                 player->hurt_tilt_strength = 0;
3434                 }
3435
3436                 /*
3437                         End scene
3438                 */
3439                 {
3440                         TimeTaker timer("endScene");
3441                         driver->endScene();
3442                         endscenetime = timer.stop(true);
3443                 }
3444
3445                 drawtime = tt_draw.stop(true);
3446                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3447
3448                 /*
3449                         End of drawing
3450                 */
3451
3452                 /*
3453                         Log times and stuff for visualization
3454                 */
3455                 Profiler::GraphValues values;
3456                 g_profiler->graphGet(values);
3457                 graph.put(values);
3458         }
3459
3460         /*
3461                 Drop stuff
3462         */
3463         if (clouds)
3464                 clouds->drop();
3465         if (gui_chat_console)
3466                 gui_chat_console->drop();
3467         if (sky)
3468                 sky->drop();
3469         clear_particles();
3470
3471         /* cleanup menus */
3472         while (g_menumgr.menuCount() > 0)
3473         {
3474                 g_menumgr.m_stack.front()->setVisible(false);
3475                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3476         }
3477         /*
3478                 Draw a "shutting down" screen, which will be shown while the map
3479                 generator and other stuff quits
3480         */
3481         {
3482                 wchar_t* text = wgettext("Shutting down stuff...");
3483                 draw_load_screen(text, device, guienv, font, 0, -1, false);
3484                 delete[] text;
3485         }
3486
3487         chat_backend.addMessage(L"", L"# Disconnected.");
3488         chat_backend.addMessage(L"", L"");
3489
3490         client.Stop();
3491
3492         //force answer all texture and shader jobs (TODO return empty values)
3493
3494         while(!client.isShutdown()) {
3495                 tsrc->processQueue();
3496                 shsrc->processQueue();
3497                 sleep_ms(100);
3498         }
3499
3500         // Client scope (client is destructed before destructing *def and tsrc)
3501         }while(0);
3502         } // try-catch
3503         catch(SerializationError &e)
3504         {
3505                 error_message = L"A serialization error occurred:\n"
3506                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3507                                 L" running a different version of Minetest.";
3508                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3509         }
3510         catch(ServerError &e) {
3511                 error_message = narrow_to_wide(e.what());
3512                 errorstream << "ServerError: " << e.what() << std::endl;
3513         }
3514         catch(ModError &e) {
3515                 errorstream << "ModError: " << e.what() << std::endl;
3516                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3517         }
3518
3519
3520
3521         if(!sound_is_dummy)
3522                 delete sound;
3523
3524         //has to be deleted first to stop all server threads
3525         delete server;
3526
3527         delete tsrc;
3528         delete shsrc;
3529         delete nodedef;
3530         delete itemdef;
3531
3532         //extended resource accounting
3533         infostream << "Irrlicht resources after cleanup:" << std::endl;
3534         infostream << "\tRemaining meshes   : "
3535                 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3536         infostream << "\tRemaining textures : "
3537                 << driver->getTextureCount() << std::endl;
3538         for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3539                 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3540                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3541                                 << std::endl;
3542         }
3543         clearTextureNameCache();
3544         infostream << "\tRemaining materials: "
3545                 << driver-> getMaterialRendererCount ()
3546                 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;
3547 }