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