Allow full circle rotation with 2degs step for plantlike drawtype.
[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         if (singleplayermode) {
1064                 (*cur_formspec)->doPause = true;
1065         }
1066 }
1067
1068 /******************************************************************************/
1069 void the_game(bool &kill, bool random_input, InputHandler *input,
1070         IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1071         std::string playername, std::string password,
1072         std::string address /* If "", local server is used */,
1073         u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1074         const SubgameSpec &gamespec /* Used for local game */,
1075         bool simple_singleplayer_mode)
1076 {
1077         GUIFormSpecMenu* current_formspec = 0;
1078         video::IVideoDriver* driver = device->getVideoDriver();
1079         scene::ISceneManager* smgr = device->getSceneManager();
1080
1081         // Calculate text height using the font
1082         u32 text_height = font->getDimension(L"Random test string").Height;
1083
1084         /*
1085                 Draw "Loading" screen
1086         */
1087
1088         {
1089                 wchar_t* text = wgettext("Loading...");
1090                 draw_load_screen(text, device, guienv, font, 0, 0);
1091                 delete[] text;
1092         }
1093
1094         // Create texture source
1095         IWritableTextureSource *tsrc = createTextureSource(device);
1096
1097         // Create shader source
1098         IWritableShaderSource *shsrc = createShaderSource(device);
1099
1100         // These will be filled by data received from the server
1101         // Create item definition manager
1102         IWritableItemDefManager *itemdef = createItemDefManager();
1103         // Create node definition manager
1104         IWritableNodeDefManager *nodedef = createNodeDefManager();
1105
1106         // Sound fetcher (useful when testing)
1107         GameOnDemandSoundFetcher soundfetcher;
1108
1109         // Sound manager
1110         ISoundManager *sound = NULL;
1111         bool sound_is_dummy = false;
1112 #if USE_SOUND
1113         if(g_settings->getBool("enable_sound")){
1114                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1115                 sound = createOpenALSoundManager(&soundfetcher);
1116                 if(!sound)
1117                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1118         } else {
1119                 infostream<<"Sound disabled."<<std::endl;
1120         }
1121 #endif
1122         if(!sound){
1123                 infostream<<"Using dummy audio."<<std::endl;
1124                 sound = &dummySoundManager;
1125                 sound_is_dummy = true;
1126         }
1127
1128         Server *server = NULL;
1129
1130         try{
1131         // Event manager
1132         EventManager eventmgr;
1133
1134         // Sound maker
1135         SoundMaker soundmaker(sound, nodedef);
1136         soundmaker.registerReceiver(&eventmgr);
1137
1138         // Add chat log output for errors to be shown in chat
1139         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1140
1141         // Create UI for modifying quicktune values
1142         QuicktuneShortcutter quicktune;
1143
1144         /*
1145                 Create server.
1146         */
1147
1148         if(address == ""){
1149                 wchar_t* text = wgettext("Creating server....");
1150                 draw_load_screen(text, device, guienv, font, 0, 25);
1151                 delete[] text;
1152                 infostream<<"Creating server"<<std::endl;
1153
1154                 std::string bind_str = g_settings->get("bind_address");
1155                 Address bind_addr(0,0,0,0, port);
1156
1157                 if (g_settings->getBool("ipv6_server")) {
1158                         bind_addr.setAddress((IPv6AddressBytes*) NULL);
1159                 }
1160                 try {
1161                         bind_addr.Resolve(bind_str.c_str());
1162                         address = bind_str;
1163                 } catch (ResolveError &e) {
1164                         infostream << "Resolving bind address \"" << bind_str
1165                                            << "\" failed: " << e.what()
1166                                            << " -- Listening on all addresses." << std::endl;
1167                 }
1168
1169                 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1170                         error_message = L"Unable to listen on " +
1171                                 narrow_to_wide(bind_addr.serializeString()) +
1172                                 L" because IPv6 is disabled";
1173                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1174                         // Break out of client scope
1175                         return;
1176                 }
1177
1178                 server = new Server(map_dir, gamespec,
1179                                 simple_singleplayer_mode,
1180                                 bind_addr.isIPv6());
1181
1182                 server->start(bind_addr);
1183         }
1184
1185         do{ // Client scope (breakable do-while(0))
1186
1187         /*
1188                 Create client
1189         */
1190
1191         {
1192                 wchar_t* text = wgettext("Creating client...");
1193                 draw_load_screen(text, device, guienv, font, 0, 50);
1194                 delete[] text;
1195         }
1196         infostream<<"Creating client"<<std::endl;
1197
1198         MapDrawControl draw_control;
1199
1200         {
1201                 wchar_t* text = wgettext("Resolving address...");
1202                 draw_load_screen(text, device, guienv, font, 0, 75);
1203                 delete[] text;
1204         }
1205         Address connect_address(0,0,0,0, port);
1206         try {
1207                 connect_address.Resolve(address.c_str());
1208                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1209                         //connect_address.Resolve("localhost");
1210                         if (connect_address.isIPv6()) {
1211                                 IPv6AddressBytes addr_bytes;
1212                                 addr_bytes.bytes[15] = 1;
1213                                 connect_address.setAddress(&addr_bytes);
1214                         } else {
1215                                 connect_address.setAddress(127,0,0,1);
1216                         }
1217                 }
1218         }
1219         catch(ResolveError &e) {
1220                 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1221                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1222                 // Break out of client scope
1223                 break;
1224         }
1225         if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1226                 error_message = L"Unable to connect to " +
1227                         narrow_to_wide(connect_address.serializeString()) +
1228                         L" because IPv6 is disabled";
1229                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1230                 // Break out of client scope
1231                 break;
1232         }
1233
1234         /*
1235                 Create client
1236         */
1237         Client client(device, playername.c_str(), password, draw_control,
1238                 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1239                 connect_address.isIPv6());
1240
1241         // Client acts as our GameDef
1242         IGameDef *gamedef = &client;
1243
1244         /*
1245                 Attempt to connect to the server
1246         */
1247
1248         infostream<<"Connecting to server at ";
1249         connect_address.print(&infostream);
1250         infostream<<std::endl;
1251         client.connect(connect_address);
1252
1253         /*
1254                 Wait for server to accept connection
1255         */
1256         bool could_connect = false;
1257         bool connect_aborted = false;
1258         try{
1259                 float time_counter = 0.0;
1260                 input->clear();
1261                 float fps_max = g_settings->getFloat("fps_max");
1262                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1263                 u32 lasttime = device->getTimer()->getTime();
1264                 while(device->run())
1265                 {
1266                         f32 dtime = 0.033; // in seconds
1267                         if (cloud_menu_background) {
1268                                 u32 time = device->getTimer()->getTime();
1269                                 if(time > lasttime)
1270                                         dtime = (time - lasttime) / 1000.0;
1271                                 else
1272                                         dtime = 0;
1273                                 lasttime = time;
1274                         }
1275                         // Update client and server
1276                         client.step(dtime);
1277                         if(server != NULL)
1278                                 server->step(dtime);
1279
1280                         // End condition
1281                         if(client.getState() == LC_Init) {
1282                                 could_connect = true;
1283                                 break;
1284                         }
1285                         // Break conditions
1286                         if(client.accessDenied()) {
1287                                 error_message = L"Access denied. Reason: "
1288                                                 +client.accessDeniedReason();
1289                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1290                                 break;
1291                         }
1292                         if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1293                                 connect_aborted = true;
1294                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1295                                 break;
1296                         }
1297
1298                         // Display status
1299                         {
1300                                 wchar_t* text = wgettext("Connecting to server...");
1301                                 draw_load_screen(text, device, guienv, font, dtime, 100);
1302                                 delete[] text;
1303                         }
1304
1305                         // On some computers framerate doesn't seem to be
1306                         // automatically limited
1307                         if (cloud_menu_background) {
1308                                 // Time of frame without fps limit
1309                                 float busytime;
1310                                 u32 busytime_u32;
1311                                 // not using getRealTime is necessary for wine
1312                                 u32 time = device->getTimer()->getTime();
1313                                 if(time > lasttime)
1314                                         busytime_u32 = time - lasttime;
1315                                 else
1316                                         busytime_u32 = 0;
1317                                 busytime = busytime_u32 / 1000.0;
1318
1319                                 // FPS limiter
1320                                 u32 frametime_min = 1000./fps_max;
1321
1322                                 if(busytime_u32 < frametime_min) {
1323                                         u32 sleeptime = frametime_min - busytime_u32;
1324                                         device->sleep(sleeptime);
1325                                 }
1326                         } else {
1327                                 sleep_ms(25);
1328                         }
1329                         time_counter += dtime;
1330                 }
1331         }
1332         catch(con::PeerNotFoundException &e)
1333         {}
1334
1335         /*
1336                 Handle failure to connect
1337         */
1338         if(!could_connect) {
1339                 if(error_message == L"" && !connect_aborted) {
1340                         error_message = L"Connection failed";
1341                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1342                 }
1343                 // Break out of client scope
1344                 break;
1345         }
1346
1347         /*
1348                 Wait until content has been received
1349         */
1350         bool got_content = false;
1351         bool content_aborted = false;
1352         {
1353                 float time_counter = 0.0;
1354                 input->clear();
1355                 float fps_max = g_settings->getFloat("fps_max");
1356                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1357                 u32 lasttime = device->getTimer()->getTime();
1358                 while (device->run()) {
1359                         f32 dtime = 0.033; // in seconds
1360                         if (cloud_menu_background) {
1361                                 u32 time = device->getTimer()->getTime();
1362                                 if(time > lasttime)
1363                                         dtime = (time - lasttime) / 1000.0;
1364                                 else
1365                                         dtime = 0;
1366                                 lasttime = time;
1367                         }
1368                         // Update client and server
1369                         client.step(dtime);
1370                         if (server != NULL)
1371                                 server->step(dtime);
1372
1373                         // End condition
1374                         if (client.mediaReceived() &&
1375                                         client.itemdefReceived() &&
1376                                         client.nodedefReceived()) {
1377                                 got_content = true;
1378                                 break;
1379                         }
1380                         // Break conditions
1381                         if (client.accessDenied()) {
1382                                 error_message = L"Access denied. Reason: "
1383                                                 +client.accessDeniedReason();
1384                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1385                                 break;
1386                         }
1387                         if (client.getState() < LC_Init) {
1388                                 error_message = L"Client disconnected";
1389                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1390                                 break;
1391                         }
1392                         if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1393                                 content_aborted = true;
1394                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1395                                 break;
1396                         }
1397
1398                         // Display status
1399                         int progress=0;
1400                         if (!client.itemdefReceived())
1401                         {
1402                                 wchar_t* text = wgettext("Item definitions...");
1403                                 progress = 0;
1404                                 draw_load_screen(text, device, guienv, font, dtime, progress);
1405                                 delete[] text;
1406                         }
1407                         else if (!client.nodedefReceived())
1408                         {
1409                                 wchar_t* text = wgettext("Node definitions...");
1410                                 progress = 25;
1411                                 draw_load_screen(text, device, guienv, font, dtime, progress);
1412                                 delete[] text;
1413                         }
1414                         else
1415                         {
1416
1417                                 std::stringstream message;
1418                                 message.precision(3);
1419                                 message << gettext("Media...");
1420
1421                                 if ( ( USE_CURL == 0) ||
1422                                                 (!g_settings->getBool("enable_remote_media_server"))) {
1423                                         float cur = client.getCurRate();
1424                                         std::string cur_unit = gettext(" KB/s");
1425
1426                                         if (cur > 900) {
1427                                                 cur /= 1024.0;
1428                                                 cur_unit = gettext(" MB/s");
1429                                         }
1430                                         message << " ( " << cur << cur_unit << " )";
1431                                 }
1432                                 progress = 50+client.mediaReceiveProgress()*50+0.5;
1433                                 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1434                                                 guienv, font, dtime, progress);
1435                         }
1436
1437                         // On some computers framerate doesn't seem to be
1438                         // automatically limited
1439                         if (cloud_menu_background) {
1440                                 // Time of frame without fps limit
1441                                 float busytime;
1442                                 u32 busytime_u32;
1443                                 // not using getRealTime is necessary for wine
1444                                 u32 time = device->getTimer()->getTime();
1445                                 if(time > lasttime)
1446                                         busytime_u32 = time - lasttime;
1447                                 else
1448                                         busytime_u32 = 0;
1449                                 busytime = busytime_u32 / 1000.0;
1450
1451                                 // FPS limiter
1452                                 u32 frametime_min = 1000./fps_max;
1453
1454                                 if(busytime_u32 < frametime_min) {
1455                                         u32 sleeptime = frametime_min - busytime_u32;
1456                                         device->sleep(sleeptime);
1457                                 }
1458                         } else {
1459                                 sleep_ms(25);
1460                         }
1461                         time_counter += dtime;
1462                 }
1463         }
1464
1465         if(!got_content){
1466                 if(error_message == L"" && !content_aborted){
1467                         error_message = L"Something failed";
1468                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1469                 }
1470                 // Break out of client scope
1471                 break;
1472         }
1473
1474         /*
1475                 After all content has been received:
1476                 Update cached textures, meshes and materials
1477         */
1478         client.afterContentReceived(device,font);
1479
1480         /*
1481                 Create the camera node
1482         */
1483         Camera camera(smgr, draw_control, gamedef);
1484         if (!camera.successfullyCreated(error_message))
1485                 return;
1486
1487         f32 camera_yaw = 0; // "right/left"
1488         f32 camera_pitch = 0; // "up/down"
1489
1490         /*
1491                 Clouds
1492         */
1493
1494         Clouds *clouds = NULL;
1495         if(g_settings->getBool("enable_clouds"))
1496         {
1497                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1498         }
1499
1500         /*
1501                 Skybox thingy
1502         */
1503
1504         Sky *sky = NULL;
1505         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1506
1507         scene::ISceneNode* skybox = NULL;
1508
1509         /*
1510                 A copy of the local inventory
1511         */
1512         Inventory local_inventory(itemdef);
1513
1514         /*
1515                 Find out size of crack animation
1516         */
1517         int crack_animation_length = 5;
1518         {
1519                 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1520                 v2u32 size = t->getOriginalSize();
1521                 crack_animation_length = size.Y / size.X;
1522         }
1523
1524         /*
1525                 Add some gui stuff
1526         */
1527
1528         // First line of debug text
1529         gui::IGUIStaticText *guitext = guienv->addStaticText(
1530                         L"Minetest",
1531                         core::rect<s32>(0, 0, 0, 0),
1532                         false, false);
1533         // Second line of debug text
1534         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1535                         L"",
1536                         core::rect<s32>(0, 0, 0, 0),
1537                         false, false);
1538         // At the middle of the screen
1539         // Object infos are shown in this
1540         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1541                         L"",
1542                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1543                         false, true);
1544
1545         // Status text (displays info when showing and hiding GUI stuff, etc.)
1546         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1547                         L"<Status>",
1548                         core::rect<s32>(0,0,0,0),
1549                         false, false);
1550         guitext_status->setVisible(false);
1551
1552         std::wstring statustext;
1553         float statustext_time = 0;
1554
1555         // Chat text
1556         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1557                         L"",
1558                         core::rect<s32>(0,0,0,0),
1559                         //false, false); // Disable word wrap as of now
1560                         false, true);
1561         // Remove stale "recent" chat messages from previous connections
1562         chat_backend.clearRecentChat();
1563         // Chat backend and console
1564         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1565
1566         // Profiler text (size is updated when text is updated)
1567         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1568                         L"<Profiler>",
1569                         core::rect<s32>(0,0,0,0),
1570                         false, false);
1571         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1572         guitext_profiler->setVisible(false);
1573         guitext_profiler->setWordWrap(true);
1574
1575 #ifdef HAVE_TOUCHSCREENGUI
1576         if (g_touchscreengui)
1577                 g_touchscreengui->init(tsrc,porting::getDisplayDensity());
1578 #endif
1579
1580         /*
1581                 Some statistics are collected in these
1582         */
1583         u32 drawtime = 0;
1584         u32 beginscenetime = 0;
1585         u32 endscenetime = 0;
1586
1587         float recent_turn_speed = 0.0;
1588
1589         ProfilerGraph graph;
1590         // Initially clear the profiler
1591         Profiler::GraphValues dummyvalues;
1592         g_profiler->graphGet(dummyvalues);
1593
1594         float nodig_delay_timer = 0.0;
1595         float dig_time = 0.0;
1596         u16 dig_index = 0;
1597         PointedThing pointed_old;
1598         bool digging = false;
1599         bool ldown_for_dig = false;
1600
1601         float damage_flash = 0;
1602
1603         float jump_timer = 0;
1604         bool reset_jump_timer = false;
1605
1606         const float object_hit_delay = 0.2;
1607         float object_hit_delay_timer = 0.0;
1608         float time_from_last_punch = 10;
1609
1610         float update_draw_list_timer = 0.0;
1611         v3f update_draw_list_last_cam_dir;
1612
1613         bool invert_mouse = g_settings->getBool("invert_mouse");
1614
1615         bool update_wielded_item_trigger = true;
1616
1617         bool show_hud = true;
1618         bool show_chat = true;
1619         bool force_fog_off = false;
1620         f32 fog_range = 100*BS;
1621         bool disable_camera_update = false;
1622         bool show_debug = g_settings->getBool("show_debug");
1623         bool show_profiler_graph = false;
1624         u32 show_profiler = 0;
1625         u32 show_profiler_max = 3;  // Number of pages
1626
1627         float time_of_day = 0;
1628         float time_of_day_smooth = 0;
1629
1630         float repeat_rightclick_timer = 0;
1631
1632         /*
1633                 Shader constants
1634         */
1635         shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1636                         sky, &force_fog_off, &fog_range, &client));
1637
1638         /*
1639                 Main loop
1640         */
1641
1642         bool first_loop_after_window_activation = true;
1643
1644         // TODO: Convert the static interval timers to these
1645         // Interval limiter for profiler
1646         IntervalLimiter m_profiler_interval;
1647
1648         // Time is in milliseconds
1649         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1650         // NOTE: So we have to use getTime() and call run()s between them
1651         u32 lasttime = device->getTimer()->getTime();
1652
1653         LocalPlayer* player = client.getEnv().getLocalPlayer();
1654         player->hurt_tilt_timer = 0;
1655         player->hurt_tilt_strength = 0;
1656
1657         /*
1658                 HUD object
1659         */
1660         Hud hud(driver, smgr, guienv, font, text_height,
1661                         gamedef, player, &local_inventory);
1662
1663         core::stringw str = L"Minetest [";
1664         str += driver->getName();
1665         str += "]";
1666         device->setWindowCaption(str.c_str());
1667
1668         // Info text
1669         std::wstring infotext;
1670
1671         for(;;)
1672         {
1673                 if(device->run() == false || kill == true ||
1674                                 g_gamecallback->shutdown_requested)
1675                         break;
1676
1677                 v2u32 screensize = driver->getScreenSize();
1678
1679                 // Time of frame without fps limit
1680                 float busytime;
1681                 u32 busytime_u32;
1682                 {
1683                         // not using getRealTime is necessary for wine
1684                         u32 time = device->getTimer()->getTime();
1685                         if(time > lasttime)
1686                                 busytime_u32 = time - lasttime;
1687                         else
1688                                 busytime_u32 = 0;
1689                         busytime = busytime_u32 / 1000.0;
1690                 }
1691
1692                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1693
1694                 // Necessary for device->getTimer()->getTime()
1695                 device->run();
1696
1697                 /*
1698                         FPS limiter
1699                 */
1700
1701                 {
1702                         float fps_max = g_menumgr.pausesGame() ?
1703                                         g_settings->getFloat("pause_fps_max") :
1704                                         g_settings->getFloat("fps_max");
1705                         u32 frametime_min = 1000./fps_max;
1706
1707                         if(busytime_u32 < frametime_min)
1708                         {
1709                                 u32 sleeptime = frametime_min - busytime_u32;
1710                                 device->sleep(sleeptime);
1711                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1712                         }
1713                 }
1714
1715                 // Necessary for device->getTimer()->getTime()
1716                 device->run();
1717
1718                 /*
1719                         Time difference calculation
1720                 */
1721                 f32 dtime; // in seconds
1722
1723                 u32 time = device->getTimer()->getTime();
1724                 if(time > lasttime)
1725                         dtime = (time - lasttime) / 1000.0;
1726                 else
1727                         dtime = 0;
1728                 lasttime = time;
1729
1730                 g_profiler->graphAdd("mainloop_dtime", dtime);
1731
1732                 /* Run timers */
1733
1734                 if(nodig_delay_timer >= 0)
1735                         nodig_delay_timer -= dtime;
1736                 if(object_hit_delay_timer >= 0)
1737                         object_hit_delay_timer -= dtime;
1738                 time_from_last_punch += dtime;
1739
1740                 g_profiler->add("Elapsed time", dtime);
1741                 g_profiler->avg("FPS", 1./dtime);
1742
1743                 /*
1744                         Time average and jitter calculation
1745                 */
1746
1747                 static f32 dtime_avg1 = 0.0;
1748                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1749                 f32 dtime_jitter1 = dtime - dtime_avg1;
1750
1751                 static f32 dtime_jitter1_max_sample = 0.0;
1752                 static f32 dtime_jitter1_max_fraction = 0.0;
1753                 {
1754                         static f32 jitter1_max = 0.0;
1755                         static f32 counter = 0.0;
1756                         if(dtime_jitter1 > jitter1_max)
1757                                 jitter1_max = dtime_jitter1;
1758                         counter += dtime;
1759                         if(counter > 0.0)
1760                         {
1761                                 counter -= 3.0;
1762                                 dtime_jitter1_max_sample = jitter1_max;
1763                                 dtime_jitter1_max_fraction
1764                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1765                                 jitter1_max = 0.0;
1766                         }
1767                 }
1768
1769                 /*
1770                         Busytime average and jitter calculation
1771                 */
1772
1773                 static f32 busytime_avg1 = 0.0;
1774                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1775                 f32 busytime_jitter1 = busytime - busytime_avg1;
1776
1777                 static f32 busytime_jitter1_max_sample = 0.0;
1778                 static f32 busytime_jitter1_min_sample = 0.0;
1779                 {
1780                         static f32 jitter1_max = 0.0;
1781                         static f32 jitter1_min = 0.0;
1782                         static f32 counter = 0.0;
1783                         if(busytime_jitter1 > jitter1_max)
1784                                 jitter1_max = busytime_jitter1;
1785                         if(busytime_jitter1 < jitter1_min)
1786                                 jitter1_min = busytime_jitter1;
1787                         counter += dtime;
1788                         if(counter > 0.0){
1789                                 counter -= 3.0;
1790                                 busytime_jitter1_max_sample = jitter1_max;
1791                                 busytime_jitter1_min_sample = jitter1_min;
1792                                 jitter1_max = 0.0;
1793                                 jitter1_min = 0.0;
1794                         }
1795                 }
1796
1797                 /*
1798                         Handle miscellaneous stuff
1799                 */
1800
1801                 if(client.accessDenied())
1802                 {
1803                         error_message = L"Access denied. Reason: "
1804                                         +client.accessDeniedReason();
1805                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1806                         break;
1807                 }
1808
1809                 if(g_gamecallback->disconnect_requested)
1810                 {
1811                         g_gamecallback->disconnect_requested = false;
1812                         break;
1813                 }
1814
1815                 if(g_gamecallback->changepassword_requested)
1816                 {
1817                         (new GUIPasswordChange(guienv, guiroot, -1,
1818                                 &g_menumgr, &client))->drop();
1819                         g_gamecallback->changepassword_requested = false;
1820                 }
1821
1822                 if(g_gamecallback->changevolume_requested)
1823                 {
1824                         (new GUIVolumeChange(guienv, guiroot, -1,
1825                                 &g_menumgr, &client))->drop();
1826                         g_gamecallback->changevolume_requested = false;
1827                 }
1828
1829                 /* Process TextureSource's queue */
1830                 tsrc->processQueue();
1831
1832                 /* Process ItemDefManager's queue */
1833                 itemdef->processQueue(gamedef);
1834
1835                 /*
1836                         Process ShaderSource's queue
1837                 */
1838                 shsrc->processQueue();
1839
1840                 /*
1841                         Random calculations
1842                 */
1843                 hud.resizeHotbar();
1844
1845                 // Hilight boxes collected during the loop and displayed
1846                 std::vector<aabb3f> hilightboxes;
1847
1848                 /* reset infotext */
1849                 infotext = L"";
1850                 /*
1851                         Profiler
1852                 */
1853                 float profiler_print_interval =
1854                                 g_settings->getFloat("profiler_print_interval");
1855                 bool print_to_log = true;
1856                 if(profiler_print_interval == 0){
1857                         print_to_log = false;
1858                         profiler_print_interval = 5;
1859                 }
1860                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1861                 {
1862                         if(print_to_log){
1863                                 infostream<<"Profiler:"<<std::endl;
1864                                 g_profiler->print(infostream);
1865                         }
1866
1867                         update_profiler_gui(guitext_profiler, font, text_height,
1868                                         show_profiler, show_profiler_max);
1869
1870                         g_profiler->clear();
1871                 }
1872
1873                 /*
1874                         Direct handling of user input
1875                 */
1876
1877                 // Reset input if window not active or some menu is active
1878                 if(device->isWindowActive() == false
1879                                 || noMenuActive() == false
1880                                 || guienv->hasFocus(gui_chat_console))
1881                 {
1882                         input->clear();
1883                 }
1884                 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1885                 {
1886                         gui_chat_console->closeConsoleAtOnce();
1887                 }
1888
1889                 // Input handler step() (used by the random input generator)
1890                 input->step(dtime);
1891 #ifdef HAVE_TOUCHSCREENGUI
1892                 if (g_touchscreengui) {
1893                         g_touchscreengui->step(dtime);
1894                 }
1895 #endif
1896 #ifdef __ANDROID__
1897                 if (current_formspec != 0)
1898                         current_formspec->getAndroidUIInput();
1899 #endif
1900
1901                 // Increase timer for doubleclick of "jump"
1902                 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1903                         jump_timer += dtime;
1904
1905                 /*
1906                         Launch menus and trigger stuff according to keys
1907                 */
1908                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1909                 {
1910                         // drop selected item
1911                         IDropAction *a = new IDropAction();
1912                         a->count = 0;
1913                         a->from_inv.setCurrentPlayer();
1914                         a->from_list = "main";
1915                         a->from_i = client.getPlayerItem();
1916                         client.inventoryAction(a);
1917                 }
1918                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1919                 {
1920                         infostream<<"the_game: "
1921                                         <<"Launching inventory"<<std::endl;
1922
1923                         PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1924                         TextDest* txt_dst = new TextDestPlayerInventory(&client);
1925
1926                         create_formspec_menu(&current_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst);
1927
1928                         InventoryLocation inventoryloc;
1929                         inventoryloc.setCurrentPlayer();
1930                         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1931                 }
1932                 else if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey))
1933                 {
1934                         show_pause_menu(&current_formspec, &client, gamedef, tsrc, device,
1935                                         simple_singleplayer_mode);
1936                 }
1937                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1938                 {
1939                         show_chat_menu(&current_formspec, &client, gamedef, tsrc, device,
1940                                         &client,"");
1941                 }
1942                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1943                 {
1944                         show_chat_menu(&current_formspec, &client, gamedef, tsrc, device,
1945                                         &client,"/");
1946                 }
1947                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1948                 {
1949                         if (!gui_chat_console->isOpenInhibited())
1950                         {
1951                                 // Open up to over half of the screen
1952                                 gui_chat_console->openConsole(0.6);
1953                                 guienv->setFocus(gui_chat_console);
1954                         }
1955                 }
1956                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1957                 {
1958                         if(g_settings->getBool("free_move"))
1959                         {
1960                                 g_settings->set("free_move","false");
1961                                 statustext = L"free_move disabled";
1962                                 statustext_time = 0;
1963                         }
1964                         else
1965                         {
1966                                 g_settings->set("free_move","true");
1967                                 statustext = L"free_move enabled";
1968                                 statustext_time = 0;
1969                                 if(!client.checkPrivilege("fly"))
1970                                         statustext += L" (note: no 'fly' privilege)";
1971                         }
1972                 }
1973                 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1974                 {
1975                         if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1976                         {
1977                                 if(g_settings->getBool("free_move"))
1978                                 {
1979                                         g_settings->set("free_move","false");
1980                                         statustext = L"free_move disabled";
1981                                         statustext_time = 0;
1982                                 }
1983                                 else
1984                                 {
1985                                         g_settings->set("free_move","true");
1986                                         statustext = L"free_move enabled";
1987                                         statustext_time = 0;
1988                                         if(!client.checkPrivilege("fly"))
1989                                                 statustext += L" (note: no 'fly' privilege)";
1990                                 }
1991                         }
1992                         reset_jump_timer = true;
1993                 }
1994                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1995                 {
1996                         if(g_settings->getBool("fast_move"))
1997                         {
1998                                 g_settings->set("fast_move","false");
1999                                 statustext = L"fast_move disabled";
2000                                 statustext_time = 0;
2001                         }
2002                         else
2003                         {
2004                                 g_settings->set("fast_move","true");
2005                                 statustext = L"fast_move enabled";
2006                                 statustext_time = 0;
2007                                 if(!client.checkPrivilege("fast"))
2008                                         statustext += L" (note: no 'fast' privilege)";
2009                         }
2010                 }
2011                 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2012                 {
2013                         if(g_settings->getBool("noclip"))
2014                         {
2015                                 g_settings->set("noclip","false");
2016                                 statustext = L"noclip disabled";
2017                                 statustext_time = 0;
2018                         }
2019                         else
2020                         {
2021                                 g_settings->set("noclip","true");
2022                                 statustext = L"noclip enabled";
2023                                 statustext_time = 0;
2024                                 if(!client.checkPrivilege("noclip"))
2025                                         statustext += L" (note: no 'noclip' privilege)";
2026                         }
2027                 }
2028                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2029                 {
2030                         irr::video::IImage* const image = driver->createScreenShot();
2031                         if (image) {
2032                                 irr::c8 filename[256];
2033                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
2034                                                  g_settings->get("screenshot_path").c_str(),
2035                                                  device->getTimer()->getRealTime());
2036                                 if (driver->writeImageToFile(image, filename)) {
2037                                         std::wstringstream sstr;
2038                                         sstr<<"Saved screenshot to '"<<filename<<"'";
2039                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2040                                         statustext = sstr.str();
2041                                         statustext_time = 0;
2042                                 } else{
2043                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2044                                 }
2045                                 image->drop();
2046                         }
2047                 }
2048                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2049                 {
2050                         show_hud = !show_hud;
2051                         if(show_hud)
2052                                 statustext = L"HUD shown";
2053                         else
2054                                 statustext = L"HUD hidden";
2055                         statustext_time = 0;
2056                 }
2057                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2058                 {
2059                         show_chat = !show_chat;
2060                         if(show_chat)
2061                                 statustext = L"Chat shown";
2062                         else
2063                                 statustext = L"Chat hidden";
2064                         statustext_time = 0;
2065                 }
2066                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2067                 {
2068                         force_fog_off = !force_fog_off;
2069                         if(force_fog_off)
2070                                 statustext = L"Fog disabled";
2071                         else
2072                                 statustext = L"Fog enabled";
2073                         statustext_time = 0;
2074                 }
2075                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2076                 {
2077                         disable_camera_update = !disable_camera_update;
2078                         if(disable_camera_update)
2079                                 statustext = L"Camera update disabled";
2080                         else
2081                                 statustext = L"Camera update enabled";
2082                         statustext_time = 0;
2083                 }
2084                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2085                 {
2086                         // Initial / 3x toggle: Chat only
2087                         // 1x toggle: Debug text with chat
2088                         // 2x toggle: Debug text with profiler graph
2089                         if(!show_debug)
2090                         {
2091                                 show_debug = true;
2092                                 show_profiler_graph = false;
2093                                 statustext = L"Debug info shown";
2094                                 statustext_time = 0;
2095                         }
2096                         else if(show_profiler_graph)
2097                         {
2098                                 show_debug = false;
2099                                 show_profiler_graph = false;
2100                                 statustext = L"Debug info and profiler graph hidden";
2101                                 statustext_time = 0;
2102                         }
2103                         else
2104                         {
2105                                 show_profiler_graph = true;
2106                                 statustext = L"Profiler graph shown";
2107                                 statustext_time = 0;
2108                         }
2109                 }
2110                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2111                 {
2112                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2113
2114                         // FIXME: This updates the profiler with incomplete values
2115                         update_profiler_gui(guitext_profiler, font, text_height,
2116                                         show_profiler, show_profiler_max);
2117
2118                         if(show_profiler != 0)
2119                         {
2120                                 std::wstringstream sstr;
2121                                 sstr<<"Profiler shown (page "<<show_profiler
2122                                         <<" of "<<show_profiler_max<<")";
2123                                 statustext = sstr.str();
2124                                 statustext_time = 0;
2125                         }
2126                         else
2127                         {
2128                                 statustext = L"Profiler hidden";
2129                                 statustext_time = 0;
2130                         }
2131                 }
2132                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2133                 {
2134                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2135                         s16 range_new = range + 10;
2136                         g_settings->set("viewing_range_nodes_min", itos(range_new));
2137                         statustext = narrow_to_wide(
2138                                         "Minimum viewing range changed to "
2139                                         + itos(range_new));
2140                         statustext_time = 0;
2141                 }
2142                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2143                 {
2144                         s16 range = g_settings->getS16("viewing_range_nodes_min");
2145                         s16 range_new = range - 10;
2146                         if(range_new < 0)
2147                                 range_new = range;
2148                         g_settings->set("viewing_range_nodes_min",
2149                                         itos(range_new));
2150                         statustext = narrow_to_wide(
2151                                         "Minimum viewing range changed to "
2152                                         + itos(range_new));
2153                         statustext_time = 0;
2154                 }
2155
2156                 // Reset jump_timer
2157                 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2158                 {
2159                         reset_jump_timer = false;
2160                         jump_timer = 0.0;
2161                 }
2162
2163                 // Handle QuicktuneShortcutter
2164                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2165                         quicktune.next();
2166                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2167                         quicktune.prev();
2168                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2169                         quicktune.inc();
2170                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2171                         quicktune.dec();
2172                 {
2173                         std::string msg = quicktune.getMessage();
2174                         if(msg != ""){
2175                                 statustext = narrow_to_wide(msg);
2176                                 statustext_time = 0;
2177                         }
2178                 }
2179
2180                 // Item selection with mouse wheel
2181                 u16 new_playeritem = client.getPlayerItem();
2182                 {
2183                         s32 wheel = input->getMouseWheel();
2184                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2185                                         player->hud_hotbar_itemcount-1);
2186
2187                         if(wheel < 0)
2188                         {
2189                                 if(new_playeritem < max_item)
2190                                         new_playeritem++;
2191                                 else
2192                                         new_playeritem = 0;
2193                         }
2194                         else if(wheel > 0)
2195                         {
2196                                 if(new_playeritem > 0)
2197                                         new_playeritem--;
2198                                 else
2199                                         new_playeritem = max_item;
2200                         }
2201                 }
2202
2203                 // Item selection
2204                 for(u16 i=0; i<10; i++)
2205                 {
2206                         const KeyPress *kp = NumberKey + (i + 1) % 10;
2207                         if(input->wasKeyDown(*kp))
2208                         {
2209                                 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2210                                 {
2211                                         new_playeritem = i;
2212
2213                                         infostream<<"Selected item: "
2214                                                         <<new_playeritem<<std::endl;
2215                                 }
2216                         }
2217                 }
2218
2219                 // Viewing range selection
2220                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2221                 {
2222                         draw_control.range_all = !draw_control.range_all;
2223                         if(draw_control.range_all)
2224                         {
2225                                 infostream<<"Enabled full viewing range"<<std::endl;
2226                                 statustext = L"Enabled full viewing range";
2227                                 statustext_time = 0;
2228                         }
2229                         else
2230                         {
2231                                 infostream<<"Disabled full viewing range"<<std::endl;
2232                                 statustext = L"Disabled full viewing range";
2233                                 statustext_time = 0;
2234                         }
2235                 }
2236
2237                 // Print debug stacks
2238                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2239                 {
2240                         dstream<<"-----------------------------------------"
2241                                         <<std::endl;
2242                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2243                         dstream<<"-----------------------------------------"
2244                                         <<std::endl;
2245                         debug_stacks_print();
2246                 }
2247
2248                 /*
2249                         Mouse and camera control
2250                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2251                 */
2252
2253                 float turn_amount = 0;
2254                 if((device->isWindowActive() && noMenuActive()) || random_input)
2255                 {
2256 #ifndef __ANDROID__
2257                         if(!random_input)
2258                         {
2259                                 // Mac OSX gets upset if this is set every frame
2260                                 if(device->getCursorControl()->isVisible())
2261                                         device->getCursorControl()->setVisible(false);
2262                         }
2263 #endif
2264
2265                         if(first_loop_after_window_activation){
2266                                 //infostream<<"window active, first loop"<<std::endl;
2267                                 first_loop_after_window_activation = false;
2268                         } else {
2269 #ifdef HAVE_TOUCHSCREENGUI
2270                                 if (g_touchscreengui) {
2271                                         camera_yaw   = g_touchscreengui->getYaw();
2272                                         camera_pitch = g_touchscreengui->getPitch();
2273                                 } else {
2274 #endif
2275                                         s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2276                                         s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2277                                 if ((invert_mouse)
2278                                                 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2279                                         dy = -dy;
2280                                 }
2281                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2282
2283                                 /*const float keyspeed = 500;
2284                                 if(input->isKeyDown(irr::KEY_UP))
2285                                         dy -= dtime * keyspeed;
2286                                 if(input->isKeyDown(irr::KEY_DOWN))
2287                                         dy += dtime * keyspeed;
2288                                 if(input->isKeyDown(irr::KEY_LEFT))
2289                                         dx -= dtime * keyspeed;
2290                                 if(input->isKeyDown(irr::KEY_RIGHT))
2291                                         dx += dtime * keyspeed;*/
2292
2293                                 float d = g_settings->getFloat("mouse_sensitivity");
2294                                 d = rangelim(d, 0.01, 100.0);
2295                                 camera_yaw -= dx*d;
2296                                 camera_pitch += dy*d;
2297                                 turn_amount = v2f(dx, dy).getLength() * d;
2298
2299 #ifdef HAVE_TOUCHSCREENGUI
2300                                 }
2301 #endif
2302                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
2303                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
2304                         }
2305                         input->setMousePos((driver->getScreenSize().Width/2),
2306                                         (driver->getScreenSize().Height/2));
2307                 }
2308                 else{
2309 #ifndef ANDROID
2310                         // Mac OSX gets upset if this is set every frame
2311                         if(device->getCursorControl()->isVisible() == false)
2312                                 device->getCursorControl()->setVisible(true);
2313 #endif
2314
2315                         //infostream<<"window inactive"<<std::endl;
2316                         first_loop_after_window_activation = true;
2317                 }
2318                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2319                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2320
2321                 /*
2322                         Player speed control
2323                 */
2324                 {
2325                         /*bool a_up,
2326                         bool a_down,
2327                         bool a_left,
2328                         bool a_right,
2329                         bool a_jump,
2330                         bool a_superspeed,
2331                         bool a_sneak,
2332                         bool a_LMB,
2333                         bool a_RMB,
2334                         float a_pitch,
2335                         float a_yaw*/
2336                         PlayerControl control(
2337                                 input->isKeyDown(getKeySetting("keymap_forward")),
2338                                 input->isKeyDown(getKeySetting("keymap_backward")),
2339                                 input->isKeyDown(getKeySetting("keymap_left")),
2340                                 input->isKeyDown(getKeySetting("keymap_right")),
2341                                 input->isKeyDown(getKeySetting("keymap_jump")),
2342                                 input->isKeyDown(getKeySetting("keymap_special1")),
2343                                 input->isKeyDown(getKeySetting("keymap_sneak")),
2344                                 input->getLeftState(),
2345                                 input->getRightState(),
2346                                 camera_pitch,
2347                                 camera_yaw
2348                         );
2349                         client.setPlayerControl(control);
2350                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2351                         player->keyPressed=
2352                         (((int)input->isKeyDown(getKeySetting("keymap_forward"))  & 0x1) << 0) |
2353                         (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2354                         (((int)input->isKeyDown(getKeySetting("keymap_left"))     & 0x1) << 2) |
2355                         (((int)input->isKeyDown(getKeySetting("keymap_right"))    & 0x1) << 3) |
2356                         (((int)input->isKeyDown(getKeySetting("keymap_jump"))     & 0x1) << 4) |
2357                         (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2358                         (((int)input->isKeyDown(getKeySetting("keymap_sneak"))    & 0x1) << 6) |
2359                         (((int)input->getLeftState()  & 0x1) << 7) |
2360                         (((int)input->getRightState() & 0x1) << 8);
2361                 }
2362
2363                 /*
2364                         Run server, client (and process environments)
2365                 */
2366                 bool can_be_and_is_paused =
2367                                 (simple_singleplayer_mode && g_menumgr.pausesGame());
2368                 if(can_be_and_is_paused)
2369                 {
2370                         // No time passes
2371                         dtime = 0;
2372                 }
2373                 else
2374                 {
2375                         if(server != NULL)
2376                         {
2377                                 //TimeTaker timer("server->step(dtime)");
2378                                 server->step(dtime);
2379                         }
2380                         {
2381                                 //TimeTaker timer("client.step(dtime)");
2382                                 client.step(dtime);
2383                         }
2384                 }
2385
2386                 {
2387                         // Read client events
2388                         for(;;) {
2389                                 ClientEvent event = client.getClientEvent();
2390                                 if(event.type == CE_NONE) {
2391                                         break;
2392                                 }
2393                                 else if(event.type == CE_PLAYER_DAMAGE &&
2394                                                 client.getHP() != 0) {
2395                                         //u16 damage = event.player_damage.amount;
2396                                         //infostream<<"Player damage: "<<damage<<std::endl;
2397
2398                                         damage_flash += 100.0;
2399                                         damage_flash += 8.0 * event.player_damage.amount;
2400
2401                                         player->hurt_tilt_timer = 1.5;
2402                                         player->hurt_tilt_strength = event.player_damage.amount/2;
2403                                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2404
2405                                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2406                                         gamedef->event()->put(e);
2407                                 }
2408                                 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2409                                         camera_yaw = event.player_force_move.yaw;
2410                                         camera_pitch = event.player_force_move.pitch;
2411                                 }
2412                                 else if(event.type == CE_DEATHSCREEN) {
2413                                         show_deathscreen(&current_formspec, &client, gamedef, tsrc,
2414                                                         device, &client);
2415
2416                                         chat_backend.addMessage(L"", L"You died.");
2417
2418                                         /* Handle visualization */
2419                                         damage_flash = 0;
2420
2421                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2422                                         player->hurt_tilt_timer = 0;
2423                                         player->hurt_tilt_strength = 0;
2424
2425                                 }
2426                                 else if (event.type == CE_SHOW_FORMSPEC) {
2427                                         FormspecFormSource* fs_src =
2428                                                         new FormspecFormSource(*(event.show_formspec.formspec));
2429                                         TextDestPlayerInventory* txt_dst =
2430                                                         new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2431
2432                                         create_formspec_menu(&current_formspec, &client, gamedef,
2433                                                         tsrc, device, fs_src, txt_dst);
2434
2435                                         delete(event.show_formspec.formspec);
2436                                         delete(event.show_formspec.formname);
2437                                 }
2438                                 else if(event.type == CE_SPAWN_PARTICLE) {
2439                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2440                                         video::ITexture *texture =
2441                                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2442
2443                                         new Particle(gamedef, smgr, player, client.getEnv(),
2444                                                 *event.spawn_particle.pos,
2445                                                 *event.spawn_particle.vel,
2446                                                 *event.spawn_particle.acc,
2447                                                  event.spawn_particle.expirationtime,
2448                                                  event.spawn_particle.size,
2449                                                  event.spawn_particle.collisiondetection,
2450                                                  event.spawn_particle.vertical,
2451                                                  texture,
2452                                                  v2f(0.0, 0.0),
2453                                                  v2f(1.0, 1.0));
2454                                 }
2455                                 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2456                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2457                                         video::ITexture *texture =
2458                                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2459
2460                                         new ParticleSpawner(gamedef, smgr, player,
2461                                                  event.add_particlespawner.amount,
2462                                                  event.add_particlespawner.spawntime,
2463                                                 *event.add_particlespawner.minpos,
2464                                                 *event.add_particlespawner.maxpos,
2465                                                 *event.add_particlespawner.minvel,
2466                                                 *event.add_particlespawner.maxvel,
2467                                                 *event.add_particlespawner.minacc,
2468                                                 *event.add_particlespawner.maxacc,
2469                                                  event.add_particlespawner.minexptime,
2470                                                  event.add_particlespawner.maxexptime,
2471                                                  event.add_particlespawner.minsize,
2472                                                  event.add_particlespawner.maxsize,
2473                                                  event.add_particlespawner.collisiondetection,
2474                                                  event.add_particlespawner.vertical,
2475                                                  texture,
2476                                                  event.add_particlespawner.id);
2477                                 }
2478                                 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2479                                         delete_particlespawner (event.delete_particlespawner.id);
2480                                 }
2481                                 else if (event.type == CE_HUDADD) {
2482                                         u32 id = event.hudadd.id;
2483
2484                                         HudElement *e = player->getHud(id);
2485
2486                                         if (e != NULL) {
2487                                                 delete event.hudadd.pos;
2488                                                 delete event.hudadd.name;
2489                                                 delete event.hudadd.scale;
2490                                                 delete event.hudadd.text;
2491                                                 delete event.hudadd.align;
2492                                                 delete event.hudadd.offset;
2493                                                 delete event.hudadd.world_pos;
2494                                                 delete event.hudadd.size;
2495                                                 continue;
2496                                         }
2497
2498                                         e = new HudElement;
2499                                         e->type   = (HudElementType)event.hudadd.type;
2500                                         e->pos    = *event.hudadd.pos;
2501                                         e->name   = *event.hudadd.name;
2502                                         e->scale  = *event.hudadd.scale;
2503                                         e->text   = *event.hudadd.text;
2504                                         e->number = event.hudadd.number;
2505                                         e->item   = event.hudadd.item;
2506                                         e->dir    = event.hudadd.dir;
2507                                         e->align  = *event.hudadd.align;
2508                                         e->offset = *event.hudadd.offset;
2509                                         e->world_pos = *event.hudadd.world_pos;
2510                                         e->size = *event.hudadd.size;
2511
2512                                         u32 new_id = player->addHud(e);
2513                                         //if this isn't true our huds aren't consistent
2514                                         assert(new_id == id);
2515
2516                                         delete event.hudadd.pos;
2517                                         delete event.hudadd.name;
2518                                         delete event.hudadd.scale;
2519                                         delete event.hudadd.text;
2520                                         delete event.hudadd.align;
2521                                         delete event.hudadd.offset;
2522                                         delete event.hudadd.world_pos;
2523                                         delete event.hudadd.size;
2524                                 }
2525                                 else if (event.type == CE_HUDRM) {
2526                                         HudElement* e = player->removeHud(event.hudrm.id);
2527
2528                                         if (e != NULL)
2529                                                 delete (e);
2530                                 }
2531                                 else if (event.type == CE_HUDCHANGE) {
2532                                         u32 id = event.hudchange.id;
2533                                         HudElement* e = player->getHud(id);
2534                                         if (e == NULL)
2535                                         {
2536                                                 delete event.hudchange.v3fdata;
2537                                                 delete event.hudchange.v2fdata;
2538                                                 delete event.hudchange.sdata;
2539                                                 delete event.hudchange.v2s32data;
2540                                                 continue;
2541                                         }
2542
2543                                         switch (event.hudchange.stat) {
2544                                                 case HUD_STAT_POS:
2545                                                         e->pos = *event.hudchange.v2fdata;
2546                                                         break;
2547                                                 case HUD_STAT_NAME:
2548                                                         e->name = *event.hudchange.sdata;
2549                                                         break;
2550                                                 case HUD_STAT_SCALE:
2551                                                         e->scale = *event.hudchange.v2fdata;
2552                                                         break;
2553                                                 case HUD_STAT_TEXT:
2554                                                         e->text = *event.hudchange.sdata;
2555                                                         break;
2556                                                 case HUD_STAT_NUMBER:
2557                                                         e->number = event.hudchange.data;
2558                                                         break;
2559                                                 case HUD_STAT_ITEM:
2560                                                         e->item = event.hudchange.data;
2561                                                         break;
2562                                                 case HUD_STAT_DIR:
2563                                                         e->dir = event.hudchange.data;
2564                                                         break;
2565                                                 case HUD_STAT_ALIGN:
2566                                                         e->align = *event.hudchange.v2fdata;
2567                                                         break;
2568                                                 case HUD_STAT_OFFSET:
2569                                                         e->offset = *event.hudchange.v2fdata;
2570                                                         break;
2571                                                 case HUD_STAT_WORLD_POS:
2572                                                         e->world_pos = *event.hudchange.v3fdata;
2573                                                         break;
2574                                                 case HUD_STAT_SIZE:
2575                                                         e->size = *event.hudchange.v2s32data;
2576                                                         break;
2577                                         }
2578
2579                                         delete event.hudchange.v3fdata;
2580                                         delete event.hudchange.v2fdata;
2581                                         delete event.hudchange.sdata;
2582                                         delete event.hudchange.v2s32data;
2583                                 }
2584                                 else if (event.type == CE_SET_SKY) {
2585                                         sky->setVisible(false);
2586                                         if(skybox){
2587                                                 skybox->remove();
2588                                                 skybox = NULL;
2589                                         }
2590                                         // Handle according to type
2591                                         if(*event.set_sky.type == "regular") {
2592                                                 sky->setVisible(true);
2593                                         }
2594                                         else if(*event.set_sky.type == "skybox" &&
2595                                                         event.set_sky.params->size() == 6) {
2596                                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2597                                                 skybox = smgr->addSkyBoxSceneNode(
2598                                                                 tsrc->getTexture((*event.set_sky.params)[0]),
2599                                                                 tsrc->getTexture((*event.set_sky.params)[1]),
2600                                                                 tsrc->getTexture((*event.set_sky.params)[2]),
2601                                                                 tsrc->getTexture((*event.set_sky.params)[3]),
2602                                                                 tsrc->getTexture((*event.set_sky.params)[4]),
2603                                                                 tsrc->getTexture((*event.set_sky.params)[5]));
2604                                         }
2605                                         // Handle everything else as plain color
2606                                         else {
2607                                                 if(*event.set_sky.type != "plain")
2608                                                         infostream<<"Unknown sky type: "
2609                                                                         <<(*event.set_sky.type)<<std::endl;
2610                                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2611                                         }
2612
2613                                         delete event.set_sky.bgcolor;
2614                                         delete event.set_sky.type;
2615                                         delete event.set_sky.params;
2616                                 }
2617                                 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2618                                         bool enable = event.override_day_night_ratio.do_override;
2619                                         u32 value = event.override_day_night_ratio.ratio_f * 1000;
2620                                         client.getEnv().setDayNightRatioOverride(enable, value);
2621                                 }
2622                         }
2623                 }
2624
2625                 //TimeTaker //timer2("//timer2");
2626
2627                 /*
2628                         For interaction purposes, get info about the held item
2629                         - What item is it?
2630                         - Is it a usable item?
2631                         - Can it point to liquids?
2632                 */
2633                 ItemStack playeritem;
2634                 {
2635                         InventoryList *mlist = local_inventory.getList("main");
2636                         if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2637                                 playeritem = mlist->getItem(client.getPlayerItem());
2638                 }
2639                 const ItemDefinition &playeritem_def =
2640                                 playeritem.getDefinition(itemdef);
2641                 ToolCapabilities playeritem_toolcap =
2642                                 playeritem.getToolCapabilities(itemdef);
2643
2644                 /*
2645                         Update camera
2646                 */
2647
2648                 v3s16 old_camera_offset = camera.getOffset();
2649
2650                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2651                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2652                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2653
2654                 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2655                         camera.toggleCameraMode();
2656                         GenericCAO* playercao = player->getCAO();
2657
2658                         assert( playercao != NULL );
2659                         if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2660                                 playercao->setVisible(true);
2661                         }
2662                         else {
2663                                 playercao->setVisible(false);
2664                         }
2665                 }
2666                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2667                 camera.update(player, dtime, busytime, tool_reload_ratio,
2668                                 client.getEnv());
2669                 camera.step(dtime);
2670
2671                 v3f player_position = player->getPosition();
2672                 v3f camera_position = camera.getPosition();
2673                 v3f camera_direction = camera.getDirection();
2674                 f32 camera_fov = camera.getFovMax();
2675                 v3s16 camera_offset = camera.getOffset();
2676
2677                 bool camera_offset_changed = (camera_offset != old_camera_offset);
2678
2679                 if(!disable_camera_update){
2680                         client.getEnv().getClientMap().updateCamera(camera_position,
2681                                 camera_direction, camera_fov, camera_offset);
2682                         if (camera_offset_changed){
2683                                 client.updateCameraOffset(camera_offset);
2684                                 client.getEnv().updateCameraOffset(camera_offset);
2685                                 if (clouds)
2686                                         clouds->updateCameraOffset(camera_offset);
2687                         }
2688                 }
2689
2690                 // Update sound listener
2691                 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2692                                 v3f(0,0,0), // velocity
2693                                 camera.getDirection(),
2694                                 camera.getCameraNode()->getUpVector());
2695                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2696
2697                 /*
2698                         Update sound maker
2699                 */
2700                 {
2701                         soundmaker.step(dtime);
2702
2703                         ClientMap &map = client.getEnv().getClientMap();
2704                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2705                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2706                 }
2707
2708                 /*
2709                         Calculate what block is the crosshair pointing to
2710                 */
2711
2712                 //u32 t1 = device->getTimer()->getRealTime();
2713
2714                 f32 d = playeritem_def.range; // max. distance
2715                 f32 d_hand = itemdef->get("").range;
2716                 if(d < 0 && d_hand >= 0)
2717                         d = d_hand;
2718                 else if(d < 0)
2719                         d = 4.0;
2720                 core::line3d<f32> shootline(camera_position,
2721                                 camera_position + camera_direction * BS * (d+1));
2722
2723
2724                 // prevent player pointing anything in front-view
2725                 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2726                         shootline = core::line3d<f32>(0,0,0,0,0,0);
2727
2728 #ifdef HAVE_TOUCHSCREENGUI
2729                 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2730                         shootline = g_touchscreengui->getShootline();
2731                         shootline.start += intToFloat(camera_offset,BS);
2732                         shootline.end += intToFloat(camera_offset,BS);
2733                 }
2734 #endif
2735
2736                 ClientActiveObject *selected_object = NULL;
2737
2738                 PointedThing pointed = getPointedThing(
2739                                 // input
2740                                 &client, player_position, camera_direction,
2741                                 camera_position, shootline, d,
2742                                 playeritem_def.liquids_pointable, !ldown_for_dig,
2743                                 camera_offset,
2744                                 // output
2745                                 hilightboxes,
2746                                 selected_object);
2747
2748                 if(pointed != pointed_old)
2749                 {
2750                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2751                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2752                 }
2753
2754                 /*
2755                         Stop digging when
2756                         - releasing left mouse button
2757                         - pointing away from node
2758                 */
2759                 if(digging)
2760                 {
2761                         if(input->getLeftReleased())
2762                         {
2763                                 infostream<<"Left button released"
2764                                         <<" (stopped digging)"<<std::endl;
2765                                 digging = false;
2766                         }
2767                         else if(pointed != pointed_old)
2768                         {
2769                                 if (pointed.type == POINTEDTHING_NODE
2770                                         && pointed_old.type == POINTEDTHING_NODE
2771                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2772                                 {
2773                                         // Still pointing to the same node,
2774                                         // but a different face. Don't reset.
2775                                 }
2776                                 else
2777                                 {
2778                                         infostream<<"Pointing away from node"
2779                                                 <<" (stopped digging)"<<std::endl;
2780                                         digging = false;
2781                                 }
2782                         }
2783                         if(!digging)
2784                         {
2785                                 client.interact(1, pointed_old);
2786                                 client.setCrack(-1, v3s16(0,0,0));
2787                                 dig_time = 0.0;
2788                         }
2789                 }
2790                 if(!digging && ldown_for_dig && !input->getLeftState())
2791                 {
2792                         ldown_for_dig = false;
2793                 }
2794
2795                 bool left_punch = false;
2796                 soundmaker.m_player_leftpunch_sound.name = "";
2797
2798                 if(input->getRightState())
2799                         repeat_rightclick_timer += dtime;
2800                 else
2801                         repeat_rightclick_timer = 0;
2802
2803                 if(playeritem_def.usable && input->getLeftState())
2804                 {
2805                         if(input->getLeftClicked())
2806                                 client.interact(4, pointed);
2807                 }
2808                 else if(pointed.type == POINTEDTHING_NODE)
2809                 {
2810                         v3s16 nodepos = pointed.node_undersurface;
2811                         v3s16 neighbourpos = pointed.node_abovesurface;
2812
2813                         /*
2814                                 Check information text of node
2815                         */
2816
2817                         ClientMap &map = client.getEnv().getClientMap();
2818                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2819                         if(meta){
2820                                 infotext = narrow_to_wide(meta->getString("infotext"));
2821                         } else {
2822                                 MapNode n = map.getNode(nodepos);
2823                                 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2824                                         infotext = L"Unknown node: ";
2825                                         infotext += narrow_to_wide(nodedef->get(n).name);
2826                                 }
2827                         }
2828
2829                         /*
2830                                 Handle digging
2831                         */
2832
2833                         if(nodig_delay_timer <= 0.0 && input->getLeftState()
2834                                         && client.checkPrivilege("interact"))
2835                         {
2836                                 if(!digging)
2837                                 {
2838                                         infostream<<"Started digging"<<std::endl;
2839                                         client.interact(0, pointed);
2840                                         digging = true;
2841                                         ldown_for_dig = true;
2842                                 }
2843                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2844
2845                                 // NOTE: Similar piece of code exists on the server side for
2846                                 // cheat detection.
2847                                 // Get digging parameters
2848                                 DigParams params = getDigParams(nodedef->get(n).groups,
2849                                                 &playeritem_toolcap);
2850                                 // If can't dig, try hand
2851                                 if(!params.diggable){
2852                                         const ItemDefinition &hand = itemdef->get("");
2853                                         const ToolCapabilities *tp = hand.tool_capabilities;
2854                                         if(tp)
2855                                                 params = getDigParams(nodedef->get(n).groups, tp);
2856                                 }
2857
2858                                 float dig_time_complete = 0.0;
2859
2860                                 if(params.diggable == false)
2861                                 {
2862                                         // I guess nobody will wait for this long
2863                                         dig_time_complete = 10000000.0;
2864                                 }
2865                                 else
2866                                 {
2867                                         dig_time_complete = params.time;
2868                                         if (g_settings->getBool("enable_particles"))
2869                                         {
2870                                                 const ContentFeatures &features =
2871                                                         client.getNodeDefManager()->get(n);
2872                                                 addPunchingParticles
2873                                                         (gamedef, smgr, player, client.getEnv(),
2874                                                          nodepos, features.tiles);
2875                                         }
2876                                 }
2877
2878                                 if(dig_time_complete >= 0.001)
2879                                 {
2880                                         dig_index = (u16)((float)crack_animation_length
2881                                                         * dig_time/dig_time_complete);
2882                                 }
2883                                 // This is for torches
2884                                 else
2885                                 {
2886                                         dig_index = crack_animation_length;
2887                                 }
2888
2889                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2890                                 if(sound_dig.exists() && params.diggable){
2891                                         if(sound_dig.name == "__group"){
2892                                                 if(params.main_group != ""){
2893                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2894                                                         soundmaker.m_player_leftpunch_sound.name =
2895                                                                         std::string("default_dig_") +
2896                                                                                         params.main_group;
2897                                                 }
2898                                         } else{
2899                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2900                                         }
2901                                 }
2902
2903                                 // Don't show cracks if not diggable
2904                                 if(dig_time_complete >= 100000.0)
2905                                 {
2906                                 }
2907                                 else if(dig_index < crack_animation_length)
2908                                 {
2909                                         //TimeTaker timer("client.setTempMod");
2910                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2911                                         client.setCrack(dig_index, nodepos);
2912                                 }
2913                                 else
2914                                 {
2915                                         infostream<<"Digging completed"<<std::endl;
2916                                         client.interact(2, pointed);
2917                                         client.setCrack(-1, v3s16(0,0,0));
2918                                         MapNode wasnode = map.getNode(nodepos);
2919                                         client.removeNode(nodepos);
2920
2921                                         if (g_settings->getBool("enable_particles"))
2922                                         {
2923                                                 const ContentFeatures &features =
2924                                                         client.getNodeDefManager()->get(wasnode);
2925                                                 addDiggingParticles
2926                                                         (gamedef, smgr, player, client.getEnv(),
2927                                                          nodepos, features.tiles);
2928                                         }
2929
2930                                         dig_time = 0;
2931                                         digging = false;
2932
2933                                         nodig_delay_timer = dig_time_complete
2934                                                         / (float)crack_animation_length;
2935
2936                                         // We don't want a corresponding delay to
2937                                         // very time consuming nodes
2938                                         if(nodig_delay_timer > 0.3)
2939                                                 nodig_delay_timer = 0.3;
2940                                         // We want a slight delay to very little
2941                                         // time consuming nodes
2942                                         float mindelay = 0.15;
2943                                         if(nodig_delay_timer < mindelay)
2944                                                 nodig_delay_timer = mindelay;
2945
2946                                         // Send event to trigger sound
2947                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2948                                         gamedef->event()->put(e);
2949                                 }
2950
2951                                 if(dig_time_complete < 100000.0)
2952                                         dig_time += dtime;
2953                                 else {
2954                                         dig_time = 0;
2955                                         client.setCrack(-1, nodepos);
2956                                 }
2957
2958                                 camera.setDigging(0);  // left click animation
2959                         }
2960
2961                         if((input->getRightClicked() ||
2962                                         repeat_rightclick_timer >=
2963                                                 g_settings->getFloat("repeat_rightclick_time")) &&
2964                                         client.checkPrivilege("interact"))
2965                         {
2966                                 repeat_rightclick_timer = 0;
2967                                 infostream<<"Ground right-clicked"<<std::endl;
2968
2969                                 if(meta && meta->getString("formspec") != "" && !random_input
2970                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2971                                 {
2972                                         infostream<<"Launching custom inventory view"<<std::endl;
2973
2974                                         InventoryLocation inventoryloc;
2975                                         inventoryloc.setNodeMeta(nodepos);
2976
2977                                         NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
2978                                                         &client.getEnv().getClientMap(), nodepos);
2979                                         TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
2980
2981                                         create_formspec_menu(&current_formspec, &client, gamedef,
2982                                                         tsrc, device, fs_src, txt_dst);
2983
2984                                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
2985                                 }
2986                                 // Otherwise report right click to server
2987                                 else
2988                                 {
2989                                         camera.setDigging(1);  // right click animation (always shown for feedback)
2990
2991                                         // If the wielded item has node placement prediction,
2992                                         // make that happen
2993                                         bool placed = nodePlacementPrediction(client,
2994                                                 playeritem_def,
2995                                                 nodepos, neighbourpos);
2996
2997                                         if(placed) {
2998                                                 // Report to server
2999                                                 client.interact(3, pointed);
3000                                                 // Read the sound
3001                                                 soundmaker.m_player_rightpunch_sound =
3002                                                         playeritem_def.sound_place;
3003                                         } else {
3004                                                 soundmaker.m_player_rightpunch_sound =
3005                                                         SimpleSoundSpec();
3006                                         }
3007
3008                                         if (playeritem_def.node_placement_prediction == "" ||
3009                                                 nodedef->get(map.getNode(nodepos)).rightclickable)
3010                                                 client.interact(3, pointed); // Report to server
3011                                 }
3012                         }
3013                 }
3014                 else if(pointed.type == POINTEDTHING_OBJECT)
3015                 {
3016                         infotext = narrow_to_wide(selected_object->infoText());
3017
3018                         if(infotext == L"" && show_debug){
3019                                 infotext = narrow_to_wide(selected_object->debugInfoText());
3020                         }
3021
3022                         //if(input->getLeftClicked())
3023                         if(input->getLeftState())
3024                         {
3025                                 bool do_punch = false;
3026                                 bool do_punch_damage = false;
3027                                 if(object_hit_delay_timer <= 0.0){
3028                                         do_punch = true;
3029                                         do_punch_damage = true;
3030                                         object_hit_delay_timer = object_hit_delay;
3031                                 }
3032                                 if(input->getLeftClicked()){
3033                                         do_punch = true;
3034                                 }
3035                                 if(do_punch){
3036                                         infostream<<"Left-clicked object"<<std::endl;
3037                                         left_punch = true;
3038                                 }
3039                                 if(do_punch_damage){
3040                                         // Report direct punch
3041                                         v3f objpos = selected_object->getPosition();
3042                                         v3f dir = (objpos - player_position).normalize();
3043
3044                                         bool disable_send = selected_object->directReportPunch(
3045                                                         dir, &playeritem, time_from_last_punch);
3046                                         time_from_last_punch = 0;
3047                                         if(!disable_send)
3048                                                 client.interact(0, pointed);
3049                                 }
3050                         }
3051                         else if(input->getRightClicked())
3052                         {
3053                                 infostream<<"Right-clicked object"<<std::endl;
3054                                 client.interact(3, pointed);  // place
3055                         }
3056                 }
3057                 else if(input->getLeftState())
3058                 {
3059                         // When button is held down in air, show continuous animation
3060                         left_punch = true;
3061                 }
3062
3063                 pointed_old = pointed;
3064
3065                 if(left_punch || input->getLeftClicked())
3066                 {
3067                         camera.setDigging(0); // left click animation
3068                 }
3069
3070                 input->resetLeftClicked();
3071                 input->resetRightClicked();
3072
3073                 input->resetLeftReleased();
3074                 input->resetRightReleased();
3075
3076                 /*
3077                         Calculate stuff for drawing
3078                 */
3079
3080                 /*
3081                         Fog range
3082                 */
3083
3084                 if(draw_control.range_all)
3085                         fog_range = 100000*BS;
3086                 else {
3087                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3088                         fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3089                         fog_range *= 0.9;
3090                 }
3091
3092                 /*
3093                         Calculate general brightness
3094                 */
3095                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3096                 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3097                 float direct_brightness = 0;
3098                 bool sunlight_seen = false;
3099                 if(g_settings->getBool("free_move")){
3100                         direct_brightness = time_brightness;
3101                         sunlight_seen = true;
3102                 } else {
3103                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3104                         float old_brightness = sky->getBrightness();
3105                         direct_brightness = (float)client.getEnv().getClientMap()
3106                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3107                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3108                                         / 255.0;
3109                 }
3110
3111                 time_of_day = client.getEnv().getTimeOfDayF();
3112                 float maxsm = 0.05;
3113                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3114                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3115                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3116                         time_of_day_smooth = time_of_day;
3117                 float todsm = 0.05;
3118                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3119                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3120                                         + (time_of_day+1.0) * todsm;
3121                 else
3122                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3123                                         + time_of_day * todsm;
3124
3125                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3126                                 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3127                                 player->getPitch());
3128
3129                 video::SColor bgcolor = sky->getBgColor();
3130                 video::SColor skycolor = sky->getSkyColor();
3131
3132                 /*
3133                         Update clouds
3134                 */
3135                 if(clouds){
3136                         if(sky->getCloudsVisible()){
3137                                 clouds->setVisible(true);
3138                                 clouds->step(dtime);
3139                                 clouds->update(v2f(player_position.X, player_position.Z),
3140                                                 sky->getCloudColor());
3141                         } else{
3142                                 clouds->setVisible(false);
3143                         }
3144                 }
3145
3146                 /*
3147                         Update particles
3148                 */
3149
3150                 allparticles_step(dtime);
3151                 allparticlespawners_step(dtime, client.getEnv());
3152
3153                 /*
3154                         Fog
3155                 */
3156
3157                 if(g_settings->getBool("enable_fog") && !force_fog_off)
3158                 {
3159                         driver->setFog(
3160                                 bgcolor,
3161                                 video::EFT_FOG_LINEAR,
3162                                 fog_range*0.4,
3163                                 fog_range*1.0,
3164                                 0.01,
3165                                 false, // pixel fog
3166                                 false // range fog
3167                         );
3168                 }
3169                 else
3170                 {
3171                         driver->setFog(
3172                                 bgcolor,
3173                                 video::EFT_FOG_LINEAR,
3174                                 100000*BS,
3175                                 110000*BS,
3176                                 0.01,
3177                                 false, // pixel fog
3178                                 false // range fog
3179                         );
3180                 }
3181
3182                 /*
3183                         Update gui stuff (0ms)
3184                 */
3185
3186                 //TimeTaker guiupdatetimer("Gui updating");
3187
3188                 if(show_debug)
3189                 {
3190                         static float drawtime_avg = 0;
3191                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3192                         /*static float beginscenetime_avg = 0;
3193                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3194                         static float scenetime_avg = 0;
3195                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3196                         static float endscenetime_avg = 0;
3197                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3198
3199                         u16 fps = (1.0/dtime_avg1);
3200
3201                         std::ostringstream os(std::ios_base::binary);
3202                         os<<std::fixed
3203                                 <<"Minetest "<<minetest_version_hash
3204                                 <<" FPS = "<<fps
3205                                 <<" (R: range_all="<<draw_control.range_all<<")"
3206                                 <<std::setprecision(0)
3207                                 <<" drawtime = "<<drawtime_avg
3208                                 <<std::setprecision(1)
3209                                 <<", dtime_jitter = "
3210                                 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3211                                 <<std::setprecision(1)
3212                                 <<", v_range = "<<draw_control.wanted_range
3213                                 <<std::setprecision(3)
3214                                 <<", RTT = "<<client.getRTT();
3215                         guitext->setText(narrow_to_wide(os.str()).c_str());
3216                         guitext->setVisible(true);
3217                 }
3218                 else if(show_hud || show_chat)
3219                 {
3220                         std::ostringstream os(std::ios_base::binary);
3221                         os<<"Minetest "<<minetest_version_hash;
3222                         guitext->setText(narrow_to_wide(os.str()).c_str());
3223                         guitext->setVisible(true);
3224                 }
3225                 else
3226                 {
3227                         guitext->setVisible(false);
3228                 }
3229
3230                 if (guitext->isVisible())
3231                 {
3232                         core::rect<s32> rect(
3233                                 5,
3234                                 5,
3235                                 screensize.X,
3236                                 5 + text_height
3237                         );
3238                         guitext->setRelativePosition(rect);
3239                 }
3240
3241                 if(show_debug)
3242                 {
3243                         std::ostringstream os(std::ios_base::binary);
3244                         os<<std::setprecision(1)<<std::fixed
3245                                 <<"(" <<(player_position.X/BS)
3246                                 <<", "<<(player_position.Y/BS)
3247                                 <<", "<<(player_position.Z/BS)
3248                                 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3249                                 <<") (seed = "<<((u64)client.getMapSeed())
3250                                 <<")";
3251                         guitext2->setText(narrow_to_wide(os.str()).c_str());
3252                         guitext2->setVisible(true);
3253
3254                         core::rect<s32> rect(
3255                                 5,
3256                                 5 + text_height,
3257                                 screensize.X,
3258                                 5 + (text_height * 2)
3259                         );
3260                         guitext2->setRelativePosition(rect);
3261                 }
3262                 else
3263                 {
3264                         guitext2->setVisible(false);
3265                 }
3266
3267                 {
3268                         guitext_info->setText(infotext.c_str());
3269                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3270                 }
3271
3272                 {
3273                         float statustext_time_max = 1.5;
3274                         if(!statustext.empty())
3275                         {
3276                                 statustext_time += dtime;
3277                                 if(statustext_time >= statustext_time_max)
3278                                 {
3279                                         statustext = L"";
3280                                         statustext_time = 0;
3281                                 }
3282                         }
3283                         guitext_status->setText(statustext.c_str());
3284                         guitext_status->setVisible(!statustext.empty());
3285
3286                         if(!statustext.empty())
3287                         {
3288                                 s32 status_y = screensize.Y - 130;
3289                                 core::rect<s32> rect(
3290                                                 10,
3291                                                 status_y - guitext_status->getTextHeight(),
3292                                                 10 + guitext_status->getTextWidth(),
3293                                                 status_y
3294                                 );
3295                                 guitext_status->setRelativePosition(rect);
3296
3297                                 // Fade out
3298                                 video::SColor initial_color(255,0,0,0);
3299                                 if(guienv->getSkin())
3300                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3301                                 video::SColor final_color = initial_color;
3302                                 final_color.setAlpha(0);
3303                                 video::SColor fade_color =
3304                                         initial_color.getInterpolated_quadratic(
3305                                                 initial_color,
3306                                                 final_color,
3307                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
3308                                 guitext_status->setOverrideColor(fade_color);
3309                                 guitext_status->enableOverrideColor(true);
3310                         }
3311                 }
3312
3313                 /*
3314                         Get chat messages from client
3315                 */
3316                 {
3317                         // Get new messages from error log buffer
3318                         while(!chat_log_error_buf.empty())
3319                         {
3320                                 chat_backend.addMessage(L"", narrow_to_wide(
3321                                                 chat_log_error_buf.get()));
3322                         }
3323                         // Get new messages from client
3324                         std::wstring message;
3325                         while(client.getChatMessage(message))
3326                         {
3327                                 chat_backend.addUnparsedMessage(message);
3328                         }
3329                         // Remove old messages
3330                         chat_backend.step(dtime);
3331
3332                         // Display all messages in a static text element
3333                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3334                         std::wstring recent_chat = chat_backend.getRecentChat();
3335                         guitext_chat->setText(recent_chat.c_str());
3336
3337                         // Update gui element size and position
3338                         s32 chat_y = 5+(text_height+5);
3339                         if(show_debug)
3340                                 chat_y += (text_height+5);
3341                         core::rect<s32> rect(
3342                                 10,
3343                                 chat_y,
3344                                 screensize.X - 10,
3345                                 chat_y + guitext_chat->getTextHeight()
3346                         );
3347                         guitext_chat->setRelativePosition(rect);
3348
3349                         // Don't show chat if disabled or empty or profiler is enabled
3350                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
3351                                         && !show_profiler);
3352                 }
3353
3354                 /*
3355                         Inventory
3356                 */
3357
3358                 if(client.getPlayerItem() != new_playeritem)
3359                 {
3360                         client.selectPlayerItem(new_playeritem);
3361                 }
3362                 if(client.getLocalInventoryUpdated())
3363                 {
3364                         //infostream<<"Updating local inventory"<<std::endl;
3365                         client.getLocalInventory(local_inventory);
3366
3367                         update_wielded_item_trigger = true;
3368                 }
3369                 if(update_wielded_item_trigger)
3370                 {
3371                         update_wielded_item_trigger = false;
3372                         // Update wielded tool
3373                         InventoryList *mlist = local_inventory.getList("main");
3374                         ItemStack item;
3375                         if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3376                                 item = mlist->getItem(client.getPlayerItem());
3377                         camera.wield(item, client.getPlayerItem());
3378                 }
3379
3380                 /*
3381                         Update block draw list every 200ms or when camera direction has
3382                         changed much
3383                 */
3384                 update_draw_list_timer += dtime;
3385                 if(update_draw_list_timer >= 0.2 ||
3386                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3387                                 camera_offset_changed){
3388                         update_draw_list_timer = 0;
3389                         client.getEnv().getClientMap().updateDrawList(driver);
3390                         update_draw_list_last_cam_dir = camera_direction;
3391                 }
3392
3393                 /*
3394                         Drawing begins
3395                 */
3396                 TimeTaker tt_draw("mainloop: draw");
3397                 {
3398                         TimeTaker timer("beginScene");
3399                         driver->beginScene(true, true, skycolor);
3400                         beginscenetime = timer.stop(true);
3401                 }
3402
3403
3404                 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3405                                 hilightboxes, screensize, skycolor, show_hud);
3406
3407                 /*
3408                         Profiler graph
3409                 */
3410                 if(show_profiler_graph)
3411                 {
3412                         graph.draw(10, screensize.Y - 10, driver, font);
3413                 }
3414
3415                 /*
3416                         Damage flash
3417                 */
3418                 if(damage_flash > 0.0)
3419                 {
3420                         video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3421                         driver->draw2DRectangle(color,
3422                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
3423                                         NULL);
3424
3425                         damage_flash -= 100.0*dtime;
3426                 }
3427
3428                 /*
3429                         Damage camera tilt
3430                 */
3431                 if(player->hurt_tilt_timer > 0.0)
3432                 {
3433                         player->hurt_tilt_timer -= dtime*5;
3434                         if(player->hurt_tilt_timer < 0)
3435                                 player->hurt_tilt_strength = 0;
3436                 }
3437
3438                 /*
3439                         End scene
3440                 */
3441                 {
3442                         TimeTaker timer("endScene");
3443                         driver->endScene();
3444                         endscenetime = timer.stop(true);
3445                 }
3446
3447                 drawtime = tt_draw.stop(true);
3448                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3449
3450                 /*
3451                         End of drawing
3452                 */
3453
3454                 /*
3455                         Log times and stuff for visualization
3456                 */
3457                 Profiler::GraphValues values;
3458                 g_profiler->graphGet(values);
3459                 graph.put(values);
3460         }
3461
3462         /*
3463                 Drop stuff
3464         */
3465         if (clouds)
3466                 clouds->drop();
3467         if (gui_chat_console)
3468                 gui_chat_console->drop();
3469         if (sky)
3470                 sky->drop();
3471         clear_particles();
3472
3473         /* cleanup menus */
3474         while (g_menumgr.menuCount() > 0)
3475         {
3476                 g_menumgr.m_stack.front()->setVisible(false);
3477                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3478         }
3479         /*
3480                 Draw a "shutting down" screen, which will be shown while the map
3481                 generator and other stuff quits
3482         */
3483         {
3484                 wchar_t* text = wgettext("Shutting down stuff...");
3485                 draw_load_screen(text, device, guienv, font, 0, -1, false);
3486                 delete[] text;
3487         }
3488
3489         chat_backend.addMessage(L"", L"# Disconnected.");
3490         chat_backend.addMessage(L"", L"");
3491
3492         client.Stop();
3493
3494         //force answer all texture and shader jobs (TODO return empty values)
3495
3496         while(!client.isShutdown()) {
3497                 tsrc->processQueue();
3498                 shsrc->processQueue();
3499                 sleep_ms(100);
3500         }
3501
3502         // Client scope (client is destructed before destructing *def and tsrc)
3503         }while(0);
3504         } // try-catch
3505         catch(SerializationError &e)
3506         {
3507                 error_message = L"A serialization error occurred:\n"
3508                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3509                                 L" running a different version of Minetest.";
3510                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3511         }
3512         catch(ServerError &e) {
3513                 error_message = narrow_to_wide(e.what());
3514                 errorstream << "ServerError: " << e.what() << std::endl;
3515         }
3516         catch(ModError &e) {
3517                 errorstream << "ModError: " << e.what() << std::endl;
3518                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3519         }
3520
3521
3522
3523         if(!sound_is_dummy)
3524                 delete sound;
3525
3526         //has to be deleted first to stop all server threads
3527         delete server;
3528
3529         delete tsrc;
3530         delete shsrc;
3531         delete nodedef;
3532         delete itemdef;
3533
3534         //extended resource accounting
3535         infostream << "Irrlicht resources after cleanup:" << std::endl;
3536         infostream << "\tRemaining meshes   : "
3537                 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3538         infostream << "\tRemaining textures : "
3539                 << driver->getTextureCount() << std::endl;
3540         for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3541                 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3542                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3543                                 << std::endl;
3544         }
3545         clearTextureNameCache();
3546         infostream << "\tRemaining materials: "
3547                 << driver-> getMaterialRendererCount ()
3548                 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;
3549 }