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