Make attached objects visible in 3rd person view
[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
22 #include <iomanip>
23 #include "camera.h"
24 #include "client.h"
25 #include "client/tile.h"     // For TextureSource
26 #include "clientmap.h"
27 #include "clouds.h"
28 #include "config.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
33 #include "itemdef.h"
34 #include "log.h"
35 #include "filesys.h"
36 #include "gettext.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
42 #include "hud.h"
43 #include "logoutputbuffer.h"
44 #include "mainmenumanager.h"
45 #include "mapblock.h"
46 #include "nodedef.h"         // Needed for determining pointing to nodes
47 #include "nodemetadata.h"
48 #include "particles.h"
49 #include "profiler.h"
50 #include "quicktune_shortcutter.h"
51 #include "server.h"
52 #include "settings.h"
53 #include "shader.h"          // For ShaderSource
54 #include "sky.h"
55 #include "subgame.h"
56 #include "tool.h"
57 #include "util/directiontables.h"
58 #include "util/pointedthing.h"
59 #include "version.h"
60
61 #include "sound.h"
62
63 #if USE_SOUND
64         #include "sound_openal.h"
65 #endif
66
67 #ifdef HAVE_TOUCHSCREENGUI
68         #include "touchscreengui.h"
69 #endif
70
71 extern Settings *g_settings;
72 extern Profiler *g_profiler;
73
74 /*
75         Text input system
76 */
77
78 struct TextDestNodeMetadata : public TextDest {
79         TextDestNodeMetadata(v3s16 p, Client *client)
80         {
81                 m_p = p;
82                 m_client = client;
83         }
84         // This is deprecated I guess? -celeron55
85         void gotText(std::wstring text)
86         {
87                 std::string ntext = wide_to_narrow(text);
88                 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
89                            << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
90                 StringMap fields;
91                 fields["text"] = ntext;
92                 m_client->sendNodemetaFields(m_p, "", fields);
93         }
94         void gotText(const StringMap &fields)
95         {
96                 m_client->sendNodemetaFields(m_p, "", fields);
97         }
98
99         v3s16 m_p;
100         Client *m_client;
101 };
102
103 struct TextDestPlayerInventory : public TextDest {
104         TextDestPlayerInventory(Client *client)
105         {
106                 m_client = client;
107                 m_formname = "";
108         }
109         TextDestPlayerInventory(Client *client, std::string formname)
110         {
111                 m_client = client;
112                 m_formname = formname;
113         }
114         void gotText(const StringMap &fields)
115         {
116                 m_client->sendInventoryFields(m_formname, fields);
117         }
118
119         Client *m_client;
120 };
121
122 struct LocalFormspecHandler : public TextDest {
123         LocalFormspecHandler();
124         LocalFormspecHandler(std::string formname) :
125                 m_client(0)
126         {
127                 m_formname = formname;
128         }
129
130         LocalFormspecHandler(std::string formname, Client *client) :
131                 m_client(client)
132         {
133                 m_formname = formname;
134         }
135
136         void gotText(std::wstring message)
137         {
138                 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
139         }
140
141         void gotText(const StringMap &fields)
142         {
143                 if (m_formname == "MT_PAUSE_MENU") {
144                         if (fields.find("btn_sound") != fields.end()) {
145                                 g_gamecallback->changeVolume();
146                                 return;
147                         }
148
149                         if (fields.find("btn_key_config") != fields.end()) {
150                                 g_gamecallback->keyConfig();
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
178                 if (m_formname == "MT_CHAT_MENU") {
179                         assert(m_client != 0);
180
181                         if ((fields.find("btn_send") != fields.end()) ||
182                                         (fields.find("quit") != fields.end())) {
183                                 StringMap::const_iterator it = fields.find("f_text");
184                                 if (it != fields.end())
185                                         m_client->typeChatMessage(narrow_to_wide(it->second));
186
187                                 return;
188                         }
189                 }
190
191                 if (m_formname == "MT_DEATH_SCREEN") {
192                         assert(m_client != 0);
193
194                         if ((fields.find("btn_respawn") != fields.end())) {
195                                 m_client->sendRespawn();
196                                 return;
197                         }
198
199                         if (fields.find("quit") != fields.end()) {
200                                 m_client->sendRespawn();
201                                 return;
202                         }
203                 }
204
205                 // don't show error message for unhandled cursor keys
206                 if ((fields.find("key_up") != fields.end()) ||
207                                 (fields.find("key_down") != fields.end()) ||
208                                 (fields.find("key_left") != fields.end()) ||
209                                 (fields.find("key_right") != fields.end())) {
210                         return;
211                 }
212
213                 errorstream << "LocalFormspecHandler::gotText unhandled >"
214                         << m_formname << "< event" << std::endl;
215
216                 int i = 0;
217                 StringMap::const_iterator it;
218                 for (it = fields.begin(); it != fields.end(); ++it) {
219                         errorstream << "\t" << i << ": " << it->first
220                                 << "=" << it->second << std::endl;
221                         i++;
222                 }
223         }
224
225         Client *m_client;
226 };
227
228 /* Form update callback */
229
230 class NodeMetadataFormSource: public IFormSource
231 {
232 public:
233         NodeMetadataFormSource(ClientMap *map, v3s16 p):
234                 m_map(map),
235                 m_p(p)
236         {
237         }
238         std::string getForm()
239         {
240                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
241
242                 if (!meta)
243                         return "";
244
245                 return meta->getString("formspec");
246         }
247         std::string resolveText(std::string str)
248         {
249                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
250
251                 if (!meta)
252                         return str;
253
254                 return meta->resolveString(str);
255         }
256
257         ClientMap *m_map;
258         v3s16 m_p;
259 };
260
261 class PlayerInventoryFormSource: public IFormSource
262 {
263 public:
264         PlayerInventoryFormSource(Client *client):
265                 m_client(client)
266         {
267         }
268         std::string getForm()
269         {
270                 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
271                 return player->inventory_formspec;
272         }
273
274         Client *m_client;
275 };
276
277 /*
278         Check if a node is pointable
279 */
280 inline bool isPointableNode(const MapNode &n,
281                             Client *client, bool liquids_pointable)
282 {
283         const ContentFeatures &features = client->getNodeDefManager()->get(n);
284         return features.pointable ||
285                (liquids_pointable && features.isLiquid());
286 }
287
288 /*
289         Find what the player is pointing at
290 */
291 PointedThing getPointedThing(Client *client, v3f player_position,
292                 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
293                 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
294                 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
295 {
296         PointedThing result;
297
298         hilightboxes.clear();
299         selected_object = NULL;
300
301         INodeDefManager *nodedef = client->getNodeDefManager();
302         ClientMap &map = client->getEnv().getClientMap();
303
304         f32 mindistance = BS * 1001;
305
306         // First try to find a pointed at active object
307         if (look_for_object) {
308                 selected_object = client->getSelectedActiveObject(d * BS,
309                                   camera_position, shootline);
310
311                 if (selected_object != NULL) {
312                         if (selected_object->doShowSelectionBox()) {
313                                 aabb3f *selection_box = selected_object->getSelectionBox();
314                                 // Box should exist because object was
315                                 // returned in the first place
316                                 assert(selection_box);
317
318                                 v3f pos = selected_object->getPosition();
319                                 hilightboxes.push_back(aabb3f(
320                                                                selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
321                                                                selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
322                         }
323
324                         mindistance = (selected_object->getPosition() - camera_position).getLength();
325
326                         result.type = POINTEDTHING_OBJECT;
327                         result.object_id = selected_object->getId();
328                 }
329         }
330
331         // That didn't work, try to find a pointed at node
332
333
334         v3s16 pos_i = floatToInt(player_position, BS);
335
336         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
337                         <<std::endl;*/
338
339         s16 a = d;
340         s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
341         s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
342         s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
343         s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
344         s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
345         s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
346
347         // Prevent signed number overflow
348         if (yend == 32767)
349                 yend = 32766;
350
351         if (zend == 32767)
352                 zend = 32766;
353
354         if (xend == 32767)
355                 xend = 32766;
356
357         for (s16 y = ystart; y <= yend; y++)
358                 for (s16 z = zstart; z <= zend; z++)
359                         for (s16 x = xstart; x <= xend; x++) {
360                                 MapNode n;
361                                 bool is_valid_position;
362
363                                 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
364                                 if (!is_valid_position)
365                                         continue;
366
367                                 if (!isPointableNode(n, client, liquids_pointable))
368                                         continue;
369
370                                 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
371
372                                 v3s16 np(x, y, z);
373                                 v3f npf = intToFloat(np, BS);
374
375                                 for (std::vector<aabb3f>::const_iterator
376                                                 i = boxes.begin();
377                                                 i != boxes.end(); i++) {
378                                         aabb3f box = *i;
379                                         box.MinEdge += npf;
380                                         box.MaxEdge += npf;
381
382                                         for (u16 j = 0; j < 6; j++) {
383                                                 v3s16 facedir = g_6dirs[j];
384                                                 aabb3f facebox = box;
385
386                                                 f32 d = 0.001 * BS;
387
388                                                 if (facedir.X > 0)
389                                                         facebox.MinEdge.X = facebox.MaxEdge.X - d;
390                                                 else if (facedir.X < 0)
391                                                         facebox.MaxEdge.X = facebox.MinEdge.X + d;
392                                                 else if (facedir.Y > 0)
393                                                         facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
394                                                 else if (facedir.Y < 0)
395                                                         facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
396                                                 else if (facedir.Z > 0)
397                                                         facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
398                                                 else if (facedir.Z < 0)
399                                                         facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
400
401                                                 v3f centerpoint = facebox.getCenter();
402                                                 f32 distance = (centerpoint - camera_position).getLength();
403
404                                                 if (distance >= mindistance)
405                                                         continue;
406
407                                                 if (!facebox.intersectsWithLine(shootline))
408                                                         continue;
409
410                                                 v3s16 np_above = np + facedir;
411
412                                                 result.type = POINTEDTHING_NODE;
413                                                 result.node_undersurface = np;
414                                                 result.node_abovesurface = np_above;
415                                                 mindistance = distance;
416
417                                                 hilightboxes.clear();
418
419                                                 if (!g_settings->getBool("enable_node_highlighting")) {
420                                                         for (std::vector<aabb3f>::const_iterator
421                                                                         i2 = boxes.begin();
422                                                                         i2 != boxes.end(); i2++) {
423                                                                 aabb3f box = *i2;
424                                                                 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
425                                                                 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
426                                                                 hilightboxes.push_back(box);
427                                                         }
428                                                 }
429                                         }
430                                 }
431                         } // for coords
432
433         return result;
434 }
435
436 /* Profiler display */
437
438 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
439                 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
440 {
441         if (show_profiler == 0) {
442                 guitext_profiler->setVisible(false);
443         } else {
444
445                 std::ostringstream os(std::ios_base::binary);
446                 g_profiler->printPage(os, show_profiler, show_profiler_max);
447                 std::wstring text = narrow_to_wide(os.str());
448                 guitext_profiler->setText(text.c_str());
449                 guitext_profiler->setVisible(true);
450
451                 s32 w = fe->getTextWidth(text.c_str());
452
453                 if (w < 400)
454                         w = 400;
455
456                 unsigned text_height = fe->getTextHeight();
457
458                 core::position2di upper_left, lower_right;
459
460                 upper_left.X  = 6;
461                 upper_left.Y  = (text_height + 5) * 2;
462                 lower_right.X = 12 + w;
463                 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
464
465                 if (lower_right.Y > screen_height * 2 / 3)
466                         lower_right.Y = screen_height * 2 / 3;
467
468                 core::rect<s32> rect(upper_left, lower_right);
469
470                 guitext_profiler->setRelativePosition(rect);
471                 guitext_profiler->setVisible(true);
472         }
473 }
474
475 class ProfilerGraph
476 {
477 private:
478         struct Piece {
479                 Profiler::GraphValues values;
480         };
481         struct Meta {
482                 float min;
483                 float max;
484                 video::SColor color;
485                 Meta(float initial = 0,
486                         video::SColor color = video::SColor(255, 255, 255, 255)):
487                         min(initial),
488                         max(initial),
489                         color(color)
490                 {}
491         };
492         std::vector<Piece> m_log;
493 public:
494         u32 m_log_max_size;
495
496         ProfilerGraph():
497                 m_log_max_size(200)
498         {}
499
500         void put(const Profiler::GraphValues &values)
501         {
502                 Piece piece;
503                 piece.values = values;
504                 m_log.push_back(piece);
505
506                 while (m_log.size() > m_log_max_size)
507                         m_log.erase(m_log.begin());
508         }
509
510         void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
511                   gui::IGUIFont *font) const
512         {
513                 std::map<std::string, Meta> m_meta;
514
515                 for (std::vector<Piece>::const_iterator k = m_log.begin();
516                                 k != m_log.end(); k++) {
517                         const Piece &piece = *k;
518
519                         for (Profiler::GraphValues::const_iterator i = piece.values.begin();
520                                         i != piece.values.end(); i++) {
521                                 const std::string &id = i->first;
522                                 const float &value = i->second;
523                                 std::map<std::string, Meta>::iterator j =
524                                         m_meta.find(id);
525
526                                 if (j == m_meta.end()) {
527                                         m_meta[id] = Meta(value);
528                                         continue;
529                                 }
530
531                                 if (value < j->second.min)
532                                         j->second.min = value;
533
534                                 if (value > j->second.max)
535                                         j->second.max = value;
536                         }
537                 }
538
539                 // Assign colors
540                 static const video::SColor usable_colors[] = {
541                         video::SColor(255, 255, 100, 100),
542                         video::SColor(255, 90, 225, 90),
543                         video::SColor(255, 100, 100, 255),
544                         video::SColor(255, 255, 150, 50),
545                         video::SColor(255, 220, 220, 100)
546                 };
547                 static const u32 usable_colors_count =
548                         sizeof(usable_colors) / sizeof(*usable_colors);
549                 u32 next_color_i = 0;
550
551                 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
552                                 i != m_meta.end(); i++) {
553                         Meta &meta = i->second;
554                         video::SColor color(255, 200, 200, 200);
555
556                         if (next_color_i < usable_colors_count)
557                                 color = usable_colors[next_color_i++];
558
559                         meta.color = color;
560                 }
561
562                 s32 graphh = 50;
563                 s32 textx = x_left + m_log_max_size + 15;
564                 s32 textx2 = textx + 200 - 15;
565                 s32 meta_i = 0;
566
567                 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
568                                 i != m_meta.end(); i++) {
569                         const std::string &id = i->first;
570                         const Meta &meta = i->second;
571                         s32 x = x_left;
572                         s32 y = y_bottom - meta_i * 50;
573                         float show_min = meta.min;
574                         float show_max = meta.max;
575
576                         if (show_min >= -0.0001 && show_max >= -0.0001) {
577                                 if (show_min <= show_max * 0.5)
578                                         show_min = 0;
579                         }
580
581                         s32 texth = 15;
582                         char buf[10];
583                         snprintf(buf, 10, "%.3g", show_max);
584                         font->draw(narrow_to_wide(buf).c_str(),
585                                         core::rect<s32>(textx, y - graphh,
586                                                    textx2, y - graphh + texth),
587                                         meta.color);
588                         snprintf(buf, 10, "%.3g", show_min);
589                         font->draw(narrow_to_wide(buf).c_str(),
590                                         core::rect<s32>(textx, y - texth,
591                                                    textx2, y),
592                                         meta.color);
593                         font->draw(narrow_to_wide(id).c_str(),
594                                         core::rect<s32>(textx, y - graphh / 2 - texth / 2,
595                                                    textx2, y - graphh / 2 + texth / 2),
596                                         meta.color);
597                         s32 graph1y = y;
598                         s32 graph1h = graphh;
599                         bool relativegraph = (show_min != 0 && show_min != show_max);
600                         float lastscaledvalue = 0.0;
601                         bool lastscaledvalue_exists = false;
602
603                         for (std::vector<Piece>::const_iterator j = m_log.begin();
604                                         j != m_log.end(); j++) {
605                                 const Piece &piece = *j;
606                                 float value = 0;
607                                 bool value_exists = false;
608                                 Profiler::GraphValues::const_iterator k =
609                                         piece.values.find(id);
610
611                                 if (k != piece.values.end()) {
612                                         value = k->second;
613                                         value_exists = true;
614                                 }
615
616                                 if (!value_exists) {
617                                         x++;
618                                         lastscaledvalue_exists = false;
619                                         continue;
620                                 }
621
622                                 float scaledvalue = 1.0;
623
624                                 if (show_max != show_min)
625                                         scaledvalue = (value - show_min) / (show_max - show_min);
626
627                                 if (scaledvalue == 1.0 && value == 0) {
628                                         x++;
629                                         lastscaledvalue_exists = false;
630                                         continue;
631                                 }
632
633                                 if (relativegraph) {
634                                         if (lastscaledvalue_exists) {
635                                                 s32 ivalue1 = lastscaledvalue * graph1h;
636                                                 s32 ivalue2 = scaledvalue * graph1h;
637                                                 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
638                                                                    v2s32(x, graph1y - ivalue2), meta.color);
639                                         }
640
641                                         lastscaledvalue = scaledvalue;
642                                         lastscaledvalue_exists = true;
643                                 } else {
644                                         s32 ivalue = scaledvalue * graph1h;
645                                         driver->draw2DLine(v2s32(x, graph1y),
646                                                            v2s32(x, graph1y - ivalue), meta.color);
647                                 }
648
649                                 x++;
650                         }
651
652                         meta_i++;
653                 }
654         }
655 };
656
657 class NodeDugEvent: public MtEvent
658 {
659 public:
660         v3s16 p;
661         MapNode n;
662
663         NodeDugEvent(v3s16 p, MapNode n):
664                 p(p),
665                 n(n)
666         {}
667         const char *getType() const
668         {
669                 return "NodeDug";
670         }
671 };
672
673 class SoundMaker
674 {
675         ISoundManager *m_sound;
676         INodeDefManager *m_ndef;
677 public:
678         float m_player_step_timer;
679
680         SimpleSoundSpec m_player_step_sound;
681         SimpleSoundSpec m_player_leftpunch_sound;
682         SimpleSoundSpec m_player_rightpunch_sound;
683
684         SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
685                 m_sound(sound),
686                 m_ndef(ndef),
687                 m_player_step_timer(0)
688         {
689         }
690
691         void playPlayerStep()
692         {
693                 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
694                         m_player_step_timer = 0.03;
695                         m_sound->playSound(m_player_step_sound, false);
696                 }
697         }
698
699         static void viewBobbingStep(MtEvent *e, void *data)
700         {
701                 SoundMaker *sm = (SoundMaker *)data;
702                 sm->playPlayerStep();
703         }
704
705         static void playerRegainGround(MtEvent *e, void *data)
706         {
707                 SoundMaker *sm = (SoundMaker *)data;
708                 sm->playPlayerStep();
709         }
710
711         static void playerJump(MtEvent *e, void *data)
712         {
713                 //SoundMaker *sm = (SoundMaker*)data;
714         }
715
716         static void cameraPunchLeft(MtEvent *e, void *data)
717         {
718                 SoundMaker *sm = (SoundMaker *)data;
719                 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
720         }
721
722         static void cameraPunchRight(MtEvent *e, void *data)
723         {
724                 SoundMaker *sm = (SoundMaker *)data;
725                 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
726         }
727
728         static void nodeDug(MtEvent *e, void *data)
729         {
730                 SoundMaker *sm = (SoundMaker *)data;
731                 NodeDugEvent *nde = (NodeDugEvent *)e;
732                 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
733         }
734
735         static void playerDamage(MtEvent *e, void *data)
736         {
737                 SoundMaker *sm = (SoundMaker *)data;
738                 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
739         }
740
741         static void playerFallingDamage(MtEvent *e, void *data)
742         {
743                 SoundMaker *sm = (SoundMaker *)data;
744                 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
745         }
746
747         void registerReceiver(MtEventManager *mgr)
748         {
749                 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
750                 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
751                 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
752                 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
753                 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
754                 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
755                 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
756                 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
757         }
758
759         void step(float dtime)
760         {
761                 m_player_step_timer -= dtime;
762         }
763 };
764
765 // Locally stored sounds don't need to be preloaded because of this
766 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
767 {
768         std::set<std::string> m_fetched;
769 public:
770         void fetchSounds(const std::string &name,
771                         std::set<std::string> &dst_paths,
772                         std::set<std::string> &dst_datas)
773         {
774                 if (m_fetched.count(name))
775                         return;
776
777                 m_fetched.insert(name);
778                 std::string base = porting::path_share + DIR_DELIM + "testsounds";
779                 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
780                 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
781                 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
782                 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
783                 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
784                 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
785                 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
786                 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
787                 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
788                 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
789                 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
790         }
791 };
792
793 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
794 {
795         Sky *m_sky;
796         bool *m_force_fog_off;
797         f32 *m_fog_range;
798         Client *m_client;
799         bool m_fogEnabled;
800
801 public:
802         void onSettingsChange(const std::string &name)
803         {
804                 if (name == "enable_fog")
805                         m_fogEnabled = g_settings->getBool("enable_fog");
806         }
807
808         static void SettingsCallback(const std::string name, void *userdata)
809         {
810                 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
811         }
812
813         GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
814                         f32 *fog_range, Client *client) :
815                 m_sky(sky),
816                 m_force_fog_off(force_fog_off),
817                 m_fog_range(fog_range),
818                 m_client(client)
819         {
820                 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
821                 m_fogEnabled = g_settings->getBool("enable_fog");
822         }
823
824         ~GameGlobalShaderConstantSetter()
825         {
826                 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
827         }
828
829         virtual void onSetConstants(video::IMaterialRendererServices *services,
830                         bool is_highlevel)
831         {
832                 if (!is_highlevel)
833                         return;
834
835                 // Background color
836                 video::SColor bgcolor = m_sky->getBgColor();
837                 video::SColorf bgcolorf(bgcolor);
838                 float bgcolorfa[4] = {
839                         bgcolorf.r,
840                         bgcolorf.g,
841                         bgcolorf.b,
842                         bgcolorf.a,
843                 };
844                 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
845
846                 // Fog distance
847                 float fog_distance = 10000 * BS;
848
849                 if (m_fogEnabled && !*m_force_fog_off)
850                         fog_distance = *m_fog_range;
851
852                 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
853
854                 // Day-night ratio
855                 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
856                 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
857                 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
858
859                 u32 animation_timer = porting::getTimeMs() % 100000;
860                 float animation_timer_f = (float)animation_timer / 100000.0;
861                 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
862                 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
863
864                 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
865                 v3f eye_position = player->getEyePosition();
866                 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
867                 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
868
869                 // Uniform sampler layers
870                 int layer0 = 0;
871                 int layer1 = 1;
872                 int layer2 = 2;
873                 // before 1.8 there isn't a "integer interface", only float
874 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
875                 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
876                 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
877                 services->setPixelShaderConstant("useNormalmap" , (irr::f32 *)&layer2, 1);
878 #else
879                 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
880                 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
881                 services->setPixelShaderConstant("useNormalmap" , (irr::s32 *)&layer2, 1);
882 #endif
883         }
884 };
885
886 bool nodePlacementPrediction(Client &client,
887                 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
888 {
889         std::string prediction = playeritem_def.node_placement_prediction;
890         INodeDefManager *nodedef = client.ndef();
891         ClientMap &map = client.getEnv().getClientMap();
892         MapNode node;
893         bool is_valid_position;
894
895         node = map.getNodeNoEx(nodepos, &is_valid_position);
896         if (!is_valid_position)
897                 return false;
898
899         if (prediction != "" && !nodedef->get(node).rightclickable) {
900                 verbosestream << "Node placement prediction for "
901                               << playeritem_def.name << " is "
902                               << prediction << std::endl;
903                 v3s16 p = neighbourpos;
904
905                 // Place inside node itself if buildable_to
906                 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
907                 if (is_valid_position)
908                 {
909                         if (nodedef->get(n_under).buildable_to)
910                                 p = nodepos;
911                         else {
912                                 node = map.getNodeNoEx(p, &is_valid_position);
913                                 if (is_valid_position &&!nodedef->get(node).buildable_to)
914                                         return false;
915                         }
916                 }
917
918                 // Find id of predicted node
919                 content_t id;
920                 bool found = nodedef->getId(prediction, id);
921
922                 if (!found) {
923                         errorstream << "Node placement prediction failed for "
924                                     << playeritem_def.name << " (places "
925                                     << prediction
926                                     << ") - Name not known" << std::endl;
927                         return false;
928                 }
929
930                 // Predict param2 for facedir and wallmounted nodes
931                 u8 param2 = 0;
932
933                 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
934                         v3s16 dir = nodepos - neighbourpos;
935
936                         if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
937                                 param2 = dir.Y < 0 ? 1 : 0;
938                         } else if (abs(dir.X) > abs(dir.Z)) {
939                                 param2 = dir.X < 0 ? 3 : 2;
940                         } else {
941                                 param2 = dir.Z < 0 ? 5 : 4;
942                         }
943                 }
944
945                 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
946                         v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
947
948                         if (abs(dir.X) > abs(dir.Z)) {
949                                 param2 = dir.X < 0 ? 3 : 1;
950                         } else {
951                                 param2 = dir.Z < 0 ? 2 : 0;
952                         }
953                 }
954
955                 assert(param2 <= 5);
956
957                 //Check attachment if node is in group attached_node
958                 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
959                         static v3s16 wallmounted_dirs[8] = {
960                                 v3s16(0, 1, 0),
961                                 v3s16(0, -1, 0),
962                                 v3s16(1, 0, 0),
963                                 v3s16(-1, 0, 0),
964                                 v3s16(0, 0, 1),
965                                 v3s16(0, 0, -1),
966                         };
967                         v3s16 pp;
968
969                         if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
970                                 pp = p + wallmounted_dirs[param2];
971                         else
972                                 pp = p + v3s16(0, -1, 0);
973
974                         if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
975                                 return false;
976                 }
977
978                 // Add node to client map
979                 MapNode n(id, 0, param2);
980
981                 try {
982                         LocalPlayer *player = client.getEnv().getLocalPlayer();
983
984                         // Dont place node when player would be inside new node
985                         // NOTE: This is to be eventually implemented by a mod as client-side Lua
986                         if (!nodedef->get(n).walkable ||
987                                         g_settings->getBool("enable_build_where_you_stand") ||
988                                         (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
989                                         (nodedef->get(n).walkable &&
990                                          neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
991                                          neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
992
993                                 // This triggers the required mesh update too
994                                 client.addNode(p, n);
995                                 return true;
996                         }
997                 } catch (InvalidPositionException &e) {
998                         errorstream << "Node placement prediction failed for "
999                                     << playeritem_def.name << " (places "
1000                                     << prediction
1001                                     << ") - Position not loaded" << std::endl;
1002                 }
1003         }
1004
1005         return false;
1006 }
1007
1008 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1009                 InventoryManager *invmgr, IGameDef *gamedef,
1010                 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1011                 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1012 {
1013
1014         if (*cur_formspec == 0) {
1015                 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1016                                                     invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1017                 (*cur_formspec)->doPause = false;
1018
1019                 /*
1020                         Caution: do not call (*cur_formspec)->drop() here --
1021                         the reference might outlive the menu, so we will
1022                         periodically check if *cur_formspec is the only
1023                         remaining reference (i.e. the menu was removed)
1024                         and delete it in that case.
1025                 */
1026
1027         } else {
1028                 (*cur_formspec)->setFormSource(fs_src);
1029                 (*cur_formspec)->setTextDest(txt_dest);
1030         }
1031 }
1032
1033 #ifdef __ANDROID__
1034 #define SIZE_TAG "size[11,5.5]"
1035 #else
1036 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1037 #endif
1038
1039 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1040                 InventoryManager *invmgr, IGameDef *gamedef,
1041                 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1042                 Client *client, std::string text)
1043 {
1044         std::string formspec =
1045                 FORMSPEC_VERSION_STRING
1046                 SIZE_TAG
1047                 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1048                 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
1049                 ;
1050
1051         /* Create menu */
1052         /* Note: FormspecFormSource and LocalFormspecHandler
1053          * are deleted by guiFormSpecMenu                     */
1054         FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1055         LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1056
1057         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1058 }
1059
1060 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1061                 InventoryManager *invmgr, IGameDef *gamedef,
1062                 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1063 {
1064         std::string formspec =
1065                 std::string(FORMSPEC_VERSION_STRING) +
1066                 SIZE_TAG
1067                 "bgcolor[#320000b4;true]"
1068                 "label[4.85,1.35;" + gettext("You died.") + "]"
1069                 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1070                 ;
1071
1072         /* Create menu */
1073         /* Note: FormspecFormSource and LocalFormspecHandler
1074          * are deleted by guiFormSpecMenu                     */
1075         FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1076         LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1077
1078         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst, NULL);
1079 }
1080
1081 /******************************************************************************/
1082 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1083                 InventoryManager *invmgr, IGameDef *gamedef,
1084                 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1085                 bool singleplayermode)
1086 {
1087 #ifdef __ANDROID__
1088         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1089                                    "No menu visible:\n"
1090                                    "- single tap: button activate\n"
1091                                    "- double tap: place/use\n"
1092                                    "- slide finger: look around\n"
1093                                    "Menu/Inventory visible:\n"
1094                                    "- double tap (outside):\n"
1095                                    " -->close\n"
1096                                    "- touch stack, touch slot:\n"
1097                                    " --> move stack\n"
1098                                    "- touch&drag, tap 2nd finger\n"
1099                                    " --> place single item to slot\n"
1100                                                              ));
1101 #else
1102         std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1103                                    "- WASD: move\n"
1104                                    "- Space: jump/climb\n"
1105                                    "- Shift: sneak/go down\n"
1106                                    "- Q: drop item\n"
1107                                    "- I: inventory\n"
1108                                    "- Mouse: turn/look\n"
1109                                    "- Mouse left: dig/punch\n"
1110                                    "- Mouse right: place/use\n"
1111                                    "- Mouse wheel: select item\n"
1112                                    "- T: chat\n"
1113                                                              ));
1114 #endif
1115
1116         float ypos = singleplayermode ? 0.5 : 0.1;
1117         std::ostringstream os;
1118
1119         os << FORMSPEC_VERSION_STRING  << SIZE_TAG
1120            << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1121            << wide_to_narrow(wstrgettext("Continue"))     << "]";
1122
1123         if (!singleplayermode) {
1124                 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1125                    << wide_to_narrow(wstrgettext("Change Password")) << "]";
1126         }
1127
1128 #ifndef __ANDROID__
1129         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1130                         << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1131         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1132                         << wide_to_narrow(wstrgettext("Change Keys"))  << "]";
1133 #endif
1134         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1135                         << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1136         os              << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1137                         << wide_to_narrow(wstrgettext("Exit to OS"))   << "]"
1138                         << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1139                         << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1140                         << g_build_info << "\n"
1141                         << "path_user = " << wrap_rows(porting::path_user, 20)
1142                         << "\n;]";
1143
1144         /* Create menu */
1145         /* Note: FormspecFormSource and LocalFormspecHandler  *
1146          * are deleted by guiFormSpecMenu                     */
1147         FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1148         LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1149
1150         create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,  fs_src, txt_dst, NULL);
1151         std::string con("btn_continue");
1152         (*cur_formspec)->setFocus(con);
1153         (*cur_formspec)->doPause = true;
1154 }
1155
1156 /******************************************************************************/
1157 static void updateChat(Client &client, f32 dtime, bool show_debug,
1158                 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1159                 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1160 {
1161         // Add chat log output for errors to be shown in chat
1162         static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1163
1164         // Get new messages from error log buffer
1165         while (!chat_log_error_buf.empty()) {
1166                 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1167         }
1168
1169         // Get new messages from client
1170         std::wstring message;
1171
1172         while (client.getChatMessage(message)) {
1173                 chat_backend.addUnparsedMessage(message);
1174         }
1175
1176         // Remove old messages
1177         chat_backend.step(dtime);
1178
1179         // Display all messages in a static text element
1180         unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1181         std::wstring recent_chat       = chat_backend.getRecentChat();
1182         unsigned int line_height       = g_fontengine->getLineHeight();
1183
1184         guitext_chat->setText(recent_chat.c_str());
1185
1186         // Update gui element size and position
1187         s32 chat_y = 5 + line_height;
1188
1189         if (show_debug)
1190                 chat_y += line_height;
1191
1192         // first pass to calculate height of text to be set
1193         s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1194                              porting::getWindowSize().X - 20);
1195         core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1196         guitext_chat->setRelativePosition(rect);
1197
1198         //now use real height of text and adjust rect according to this size
1199         rect = core::rect<s32>(10, chat_y, width,
1200                                chat_y + guitext_chat->getTextHeight());
1201
1202
1203         guitext_chat->setRelativePosition(rect);
1204         // Don't show chat if disabled or empty or profiler is enabled
1205         guitext_chat->setVisible(
1206                 show_chat && recent_chat_count != 0 && !show_profiler);
1207 }
1208
1209
1210 /****************************************************************************
1211  Fast key cache for main game loop
1212  ****************************************************************************/
1213
1214 /* This is faster than using getKeySetting with the tradeoff that functions
1215  * using it must make sure that it's initialised before using it and there is
1216  * no error handling (for example bounds checking). This is really intended for
1217  * use only in the main running loop of the client (the_game()) where the faster
1218  * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1219  * (e.g. formspecs) should continue using getKeySetting().
1220  */
1221 struct KeyCache {
1222
1223         KeyCache() { populate(); }
1224
1225         enum {
1226                 // Player movement
1227                 KEYMAP_ID_FORWARD,
1228                 KEYMAP_ID_BACKWARD,
1229                 KEYMAP_ID_LEFT,
1230                 KEYMAP_ID_RIGHT,
1231                 KEYMAP_ID_JUMP,
1232                 KEYMAP_ID_SPECIAL1,
1233                 KEYMAP_ID_SNEAK,
1234
1235                 // Other
1236                 KEYMAP_ID_DROP,
1237                 KEYMAP_ID_INVENTORY,
1238                 KEYMAP_ID_CHAT,
1239                 KEYMAP_ID_CMD,
1240                 KEYMAP_ID_CONSOLE,
1241                 KEYMAP_ID_FREEMOVE,
1242                 KEYMAP_ID_FASTMOVE,
1243                 KEYMAP_ID_NOCLIP,
1244                 KEYMAP_ID_CINEMATIC,
1245                 KEYMAP_ID_SCREENSHOT,
1246                 KEYMAP_ID_TOGGLE_HUD,
1247                 KEYMAP_ID_TOGGLE_CHAT,
1248                 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1249                 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1250                 KEYMAP_ID_TOGGLE_DEBUG,
1251                 KEYMAP_ID_TOGGLE_PROFILER,
1252                 KEYMAP_ID_CAMERA_MODE,
1253                 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1254                 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1255                 KEYMAP_ID_RANGESELECT,
1256
1257                 KEYMAP_ID_QUICKTUNE_NEXT,
1258                 KEYMAP_ID_QUICKTUNE_PREV,
1259                 KEYMAP_ID_QUICKTUNE_INC,
1260                 KEYMAP_ID_QUICKTUNE_DEC,
1261
1262                 KEYMAP_ID_DEBUG_STACKS,
1263
1264                 // Fake keycode for array size and internal checks
1265                 KEYMAP_INTERNAL_ENUM_COUNT
1266
1267
1268         };
1269
1270         void populate();
1271
1272         KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1273 };
1274
1275 void KeyCache::populate()
1276 {
1277         key[KEYMAP_ID_FORWARD]      = getKeySetting("keymap_forward");
1278         key[KEYMAP_ID_BACKWARD]     = getKeySetting("keymap_backward");
1279         key[KEYMAP_ID_LEFT]         = getKeySetting("keymap_left");
1280         key[KEYMAP_ID_RIGHT]        = getKeySetting("keymap_right");
1281         key[KEYMAP_ID_JUMP]         = getKeySetting("keymap_jump");
1282         key[KEYMAP_ID_SPECIAL1]     = getKeySetting("keymap_special1");
1283         key[KEYMAP_ID_SNEAK]        = getKeySetting("keymap_sneak");
1284
1285         key[KEYMAP_ID_DROP]         = getKeySetting("keymap_drop");
1286         key[KEYMAP_ID_INVENTORY]    = getKeySetting("keymap_inventory");
1287         key[KEYMAP_ID_CHAT]         = getKeySetting("keymap_chat");
1288         key[KEYMAP_ID_CMD]          = getKeySetting("keymap_cmd");
1289         key[KEYMAP_ID_CONSOLE]      = getKeySetting("keymap_console");
1290         key[KEYMAP_ID_FREEMOVE]     = getKeySetting("keymap_freemove");
1291         key[KEYMAP_ID_FASTMOVE]     = getKeySetting("keymap_fastmove");
1292         key[KEYMAP_ID_NOCLIP]       = getKeySetting("keymap_noclip");
1293         key[KEYMAP_ID_CINEMATIC]    = getKeySetting("keymap_cinematic");
1294         key[KEYMAP_ID_SCREENSHOT]   = getKeySetting("keymap_screenshot");
1295         key[KEYMAP_ID_TOGGLE_HUD]   = getKeySetting("keymap_toggle_hud");
1296         key[KEYMAP_ID_TOGGLE_CHAT]  = getKeySetting("keymap_toggle_chat");
1297         key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1298                         = getKeySetting("keymap_toggle_force_fog_off");
1299         key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1300                         = getKeySetting("keymap_toggle_update_camera");
1301         key[KEYMAP_ID_TOGGLE_DEBUG]
1302                         = getKeySetting("keymap_toggle_debug");
1303         key[KEYMAP_ID_TOGGLE_PROFILER]
1304                         = getKeySetting("keymap_toggle_profiler");
1305         key[KEYMAP_ID_CAMERA_MODE]
1306                         = getKeySetting("keymap_camera_mode");
1307         key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1308                         = getKeySetting("keymap_increase_viewing_range_min");
1309         key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1310                         = getKeySetting("keymap_decrease_viewing_range_min");
1311         key[KEYMAP_ID_RANGESELECT]
1312                         = getKeySetting("keymap_rangeselect");
1313
1314         key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1315         key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1316         key[KEYMAP_ID_QUICKTUNE_INC]  = getKeySetting("keymap_quicktune_inc");
1317         key[KEYMAP_ID_QUICKTUNE_DEC]  = getKeySetting("keymap_quicktune_dec");
1318
1319         key[KEYMAP_ID_DEBUG_STACKS]   = getKeySetting("keymap_print_debug_stacks");
1320 }
1321
1322
1323 /****************************************************************************
1324
1325  ****************************************************************************/
1326
1327 const float object_hit_delay = 0.2;
1328
1329 struct FpsControl {
1330         u32 last_time, busy_time, sleep_time;
1331 };
1332
1333
1334 /* The reason the following structs are not anonymous structs within the
1335  * class is that they are not used by the majority of member functions and
1336  * many functions that do require objects of thse types do not modify them
1337  * (so they can be passed as a const qualified parameter)
1338  */
1339 struct CameraOrientation {
1340         f32 camera_yaw;    // "right/left"
1341         f32 camera_pitch;  // "up/down"
1342 };
1343
1344 struct GameRunData {
1345         u16 dig_index;
1346         u16 new_playeritem;
1347         PointedThing pointed_old;
1348         bool digging;
1349         bool ldown_for_dig;
1350         bool left_punch;
1351         bool update_wielded_item_trigger;
1352         bool reset_jump_timer;
1353         float nodig_delay_timer;
1354         float dig_time;
1355         float dig_time_complete;
1356         float repeat_rightclick_timer;
1357         float object_hit_delay_timer;
1358         float time_from_last_punch;
1359         ClientActiveObject *selected_object;
1360
1361         float jump_timer;
1362         float damage_flash;
1363         float update_draw_list_timer;
1364         float statustext_time;
1365
1366         f32 fog_range;
1367
1368         v3f update_draw_list_last_cam_dir;
1369
1370         u32 profiler_current_page;
1371         u32 profiler_max_page;     // Number of pages
1372
1373         float time_of_day;
1374         float time_of_day_smooth;
1375 };
1376
1377 struct Jitter {
1378         f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1379 };
1380
1381 struct RunStats {
1382         u32 drawtime;
1383         u32 beginscenetime;
1384         u32 endscenetime;
1385
1386         Jitter dtime_jitter, busy_time_jitter;
1387 };
1388
1389 /* Flags that can, or may, change during main game loop
1390  */
1391 struct VolatileRunFlags {
1392         bool invert_mouse;
1393         bool show_chat;
1394         bool show_hud;
1395         bool force_fog_off;
1396         bool show_debug;
1397         bool show_profiler_graph;
1398         bool disable_camera_update;
1399         bool first_loop_after_window_activation;
1400         bool camera_offset_changed;
1401 };
1402
1403
1404 /****************************************************************************
1405  THE GAME
1406  ****************************************************************************/
1407
1408 /* This is not intended to be a public class. If a public class becomes
1409  * desirable then it may be better to create another 'wrapper' class that
1410  * hides most of the stuff in this class (nothing in this class is required
1411  * by any other file) but exposes the public methods/data only.
1412  */
1413 class Game
1414 {
1415 public:
1416         Game();
1417         ~Game();
1418
1419         bool startup(bool *kill,
1420                         bool random_input,
1421                         InputHandler *input,
1422                         IrrlichtDevice *device,
1423                         const std::string &map_dir,
1424                         const std::string &playername,
1425                         const std::string &password,
1426                         // If address is "", local server is used and address is updated
1427                         std::string *address,
1428                         u16 port,
1429                         std::string &error_message,
1430                         ChatBackend *chat_backend,
1431                         const SubgameSpec &gamespec,    // Used for local game
1432                         bool simple_singleplayer_mode);
1433
1434         void run();
1435         void shutdown();
1436
1437 protected:
1438
1439         void extendedResourceCleanup();
1440
1441         // Basic initialisation
1442         bool init(const std::string &map_dir, std::string *address,
1443                         u16 port,
1444                         const SubgameSpec &gamespec);
1445         bool initSound();
1446         bool createSingleplayerServer(const std::string map_dir,
1447                         const SubgameSpec &gamespec, u16 port, std::string *address);
1448
1449         // Client creation
1450         bool createClient(const std::string &playername,
1451                         const std::string &password, std::string *address, u16 port);
1452         bool initGui();
1453
1454         // Client connection
1455         bool connectToServer(const std::string &playername,
1456                         const std::string &password, std::string *address, u16 port,
1457                         bool *connect_ok, bool *aborted);
1458         bool getServerContent(bool *aborted);
1459
1460         // Main loop
1461
1462         void updateInteractTimers(GameRunData *runData, f32 dtime);
1463         bool checkConnection();
1464         bool handleCallbacks();
1465         void processQueues();
1466         void updateProfilers(const GameRunData &runData, const RunStats &stats,
1467                         const FpsControl &draw_times, f32 dtime);
1468         void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1469                         f32 dtime);
1470         void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1471
1472         void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1473                         f32 dtime);
1474         void processKeyboardInput(VolatileRunFlags *flags,
1475                         float *statustext_time,
1476                         float *jump_timer,
1477                         bool *reset_jump_timer,
1478                         u32 *profiler_current_page,
1479                         u32 profiler_max_page);
1480         void processItemSelection(u16 *new_playeritem);
1481
1482         void dropSelectedItem();
1483         void openInventory();
1484         void openConsole();
1485         void toggleFreeMove(float *statustext_time);
1486         void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1487         void toggleFast(float *statustext_time);
1488         void toggleNoClip(float *statustext_time);
1489         void toggleCinematic(float *statustext_time);
1490
1491         void toggleChat(float *statustext_time, bool *flag);
1492         void toggleHud(float *statustext_time, bool *flag);
1493         void toggleFog(float *statustext_time, bool *flag);
1494         void toggleDebug(float *statustext_time, bool *show_debug,
1495                         bool *show_profiler_graph);
1496         void toggleUpdateCamera(float *statustext_time, bool *flag);
1497         void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1498                         u32 profiler_max_page);
1499
1500         void increaseViewRange(float *statustext_time);
1501         void decreaseViewRange(float *statustext_time);
1502         void toggleFullViewRange(float *statustext_time);
1503
1504         void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1505         void updateCameraOrientation(CameraOrientation *cam,
1506                         const VolatileRunFlags &flags);
1507         void updatePlayerControl(const CameraOrientation &cam);
1508         void step(f32 *dtime);
1509         void processClientEvents(CameraOrientation *cam, float *damage_flash);
1510         void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1511                         float time_from_last_punch);
1512         void updateSound(f32 dtime);
1513         void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1514                         GameRunData *runData, f32 dtime, bool show_hud,
1515                         bool show_debug);
1516         void handlePointingAtNode(GameRunData *runData,
1517                         const PointedThing &pointed, const ItemDefinition &playeritem_def,
1518                         const ToolCapabilities &playeritem_toolcap, f32 dtime);
1519         void handlePointingAtObject(GameRunData *runData,
1520                         const PointedThing &pointed, const ItemStack &playeritem,
1521                         const v3f &player_position, bool show_debug);
1522         void handleDigging(GameRunData *runData, const PointedThing &pointed,
1523                         const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1524                         f32 dtime);
1525         void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1526                         RunStats *stats, GameRunData *runData,
1527                         f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1528         void updateGui(float *statustext_time, const RunStats &stats,
1529                         const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1530                         const CameraOrientation &cam);
1531         void updateProfilerGraphs(ProfilerGraph *graph);
1532
1533         // Misc
1534         void limitFps(FpsControl *fps_timings, f32 *dtime);
1535
1536         void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1537                         bool draw_clouds = true);
1538
1539 private:
1540         InputHandler *input;
1541
1542         Client *client;
1543         Server *server;
1544
1545         IWritableTextureSource *texture_src;
1546         IWritableShaderSource *shader_src;
1547
1548         // When created, these will be filled with data received from the server
1549         IWritableItemDefManager *itemdef_manager;
1550         IWritableNodeDefManager *nodedef_manager;
1551
1552         GameOnDemandSoundFetcher soundfetcher; // useful when testing
1553         ISoundManager *sound;
1554         bool sound_is_dummy;
1555         SoundMaker *soundmaker;
1556
1557         ChatBackend *chat_backend;
1558
1559         GUIFormSpecMenu *current_formspec;
1560
1561         EventManager *eventmgr;
1562         QuicktuneShortcutter *quicktune;
1563
1564         GUIChatConsole *gui_chat_console; // Free using ->Drop()
1565         MapDrawControl *draw_control;
1566         Camera *camera;
1567         Clouds *clouds;                   // Free using ->Drop()
1568         Sky *sky;                         // Free using ->Drop()
1569         Inventory *local_inventory;
1570         Hud *hud;
1571
1572         /* 'cache'
1573            This class does take ownership/responsibily for cleaning up etc of any of
1574            these items (e.g. device)
1575         */
1576         IrrlichtDevice *device;
1577         video::IVideoDriver *driver;
1578         scene::ISceneManager *smgr;
1579         bool *kill;
1580         std::string *error_message;
1581         IGameDef *gamedef;                     // Convenience (same as *client)
1582         scene::ISceneNode *skybox;
1583
1584         bool random_input;
1585         bool simple_singleplayer_mode;
1586         /* End 'cache' */
1587
1588         /* Pre-calculated values
1589          */
1590         int crack_animation_length;
1591
1592         /* GUI stuff
1593          */
1594         gui::IGUIStaticText *guitext;          // First line of debug text
1595         gui::IGUIStaticText *guitext2;         // Second line of debug text
1596         gui::IGUIStaticText *guitext_info;     // At the middle of the screen
1597         gui::IGUIStaticText *guitext_status;
1598         gui::IGUIStaticText *guitext_chat;         // Chat text
1599         gui::IGUIStaticText *guitext_profiler; // Profiler text
1600
1601         std::wstring infotext;
1602         std::wstring statustext;
1603
1604         KeyCache keycache;
1605
1606         IntervalLimiter profiler_interval;
1607
1608         /* TODO: Add a callback function so these can be updated when a setting
1609          *       changes.  At this point in time it doesn't matter (e.g. /set
1610          *       is documented to change server settings only)
1611          *
1612          * TODO: Local caching of settings is not optimal and should at some stage
1613          *       be updated to use a global settings object for getting thse values
1614          *       (as opposed to the this local caching). This can be addressed in
1615          *       a later release.
1616          */
1617         bool m_cache_doubletap_jump;
1618         bool m_cache_enable_node_highlighting;
1619         bool m_cache_enable_clouds;
1620         bool m_cache_enable_particles;
1621         bool m_cache_enable_fog;
1622         f32  m_cache_mouse_sensitivity;
1623         f32  m_repeat_right_click_time;
1624
1625 #ifdef __ANDROID__
1626         bool m_cache_hold_aux1;
1627 #endif
1628
1629 };
1630
1631 Game::Game() :
1632         client(NULL),
1633         server(NULL),
1634         texture_src(NULL),
1635         shader_src(NULL),
1636         itemdef_manager(NULL),
1637         nodedef_manager(NULL),
1638         sound(NULL),
1639         sound_is_dummy(false),
1640         soundmaker(NULL),
1641         chat_backend(NULL),
1642         current_formspec(NULL),
1643         eventmgr(NULL),
1644         quicktune(NULL),
1645         gui_chat_console(NULL),
1646         draw_control(NULL),
1647         camera(NULL),
1648         clouds(NULL),
1649         sky(NULL),
1650         local_inventory(NULL),
1651         hud(NULL)
1652 {
1653         m_cache_doubletap_jump            = g_settings->getBool("doubletap_jump");
1654         m_cache_enable_node_highlighting  = g_settings->getBool("enable_node_highlighting");
1655         m_cache_enable_clouds             = g_settings->getBool("enable_clouds");
1656         m_cache_enable_particles          = g_settings->getBool("enable_particles");
1657         m_cache_enable_fog                = g_settings->getBool("enable_fog");
1658         m_cache_mouse_sensitivity         = g_settings->getFloat("mouse_sensitivity");
1659         m_repeat_right_click_time         = g_settings->getFloat("repeat_rightclick_time");
1660
1661         m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
1662
1663 #ifdef __ANDROID__
1664         m_cache_hold_aux1 = false;      // This is initialised properly later
1665 #endif
1666
1667 }
1668
1669
1670
1671 /****************************************************************************
1672  MinetestApp Public
1673  ****************************************************************************/
1674
1675 Game::~Game()
1676 {
1677         delete client;
1678         delete soundmaker;
1679         if (!sound_is_dummy)
1680                 delete sound;
1681
1682         delete server; // deleted first to stop all server threads
1683
1684         delete hud;
1685         delete local_inventory;
1686         delete camera;
1687         delete quicktune;
1688         delete eventmgr;
1689         delete texture_src;
1690         delete shader_src;
1691         delete nodedef_manager;
1692         delete itemdef_manager;
1693         delete draw_control;
1694
1695         extendedResourceCleanup();
1696 }
1697
1698 bool Game::startup(bool *kill,
1699                 bool random_input,
1700                 InputHandler *input,
1701                 IrrlichtDevice *device,
1702                 const std::string &map_dir,
1703                 const std::string &playername,
1704                 const std::string &password,
1705                 std::string *address,     // can change if simple_singleplayer_mode
1706                 u16 port,
1707                 std::string &error_message,
1708                 ChatBackend *chat_backend,
1709                 const SubgameSpec &gamespec,
1710                 bool simple_singleplayer_mode)
1711 {
1712         // "cache"
1713         this->device        = device;
1714         this->kill          = kill;
1715         this->error_message = &error_message;
1716         this->random_input  = random_input;
1717         this->input         = input;
1718         this->chat_backend  = chat_backend;
1719         this->simple_singleplayer_mode = simple_singleplayer_mode;
1720
1721         driver              = device->getVideoDriver();
1722         smgr                = device->getSceneManager();
1723
1724         smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1725
1726         if (!init(map_dir, address, port, gamespec))
1727                 return false;
1728
1729         if (!createClient(playername, password, address, port))
1730                 return false;
1731
1732         return true;
1733 }
1734
1735
1736 void Game::run()
1737 {
1738         ProfilerGraph graph;
1739         RunStats stats              = { 0 };
1740         CameraOrientation cam_view_target  = { 0 };
1741         CameraOrientation cam_view  = { 0 };
1742         GameRunData runData         = { 0 };
1743         FpsControl draw_times       = { 0 };
1744         VolatileRunFlags flags      = { 0 };
1745         f32 dtime; // in seconds
1746
1747         runData.time_from_last_punch  = 10.0;
1748         runData.profiler_max_page = 3;
1749         runData.update_wielded_item_trigger = true;
1750
1751         flags.show_chat = true;
1752         flags.show_hud = true;
1753         flags.show_debug = g_settings->getBool("show_debug");
1754         flags.invert_mouse = g_settings->getBool("invert_mouse");
1755         flags.first_loop_after_window_activation = true;
1756
1757         /* Clear the profiler */
1758         Profiler::GraphValues dummyvalues;
1759         g_profiler->graphGet(dummyvalues);
1760
1761         draw_times.last_time = device->getTimer()->getTime();
1762
1763         shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1764                         sky,
1765                         &flags.force_fog_off,
1766                         &runData.fog_range,
1767                         client));
1768
1769         std::vector<aabb3f> highlight_boxes;
1770
1771         set_light_table(g_settings->getFloat("display_gamma"));
1772
1773 #ifdef __ANDROID__
1774         m_cache_hold_aux1 = g_settings->getBool("fast_move")
1775                         && client->checkPrivilege("fast");
1776 #endif
1777
1778         while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1779
1780                 /* Must be called immediately after a device->run() call because it
1781                  * uses device->getTimer()->getTime()
1782                  */
1783                 limitFps(&draw_times, &dtime);
1784
1785                 updateStats(&stats, draw_times, dtime);
1786                 updateInteractTimers(&runData, dtime);
1787
1788                 if (!checkConnection())
1789                         break;
1790                 if (!handleCallbacks())
1791                         break;
1792
1793                 processQueues();
1794
1795                 infotext = L"";
1796                 hud->resizeHotbar();
1797
1798                 updateProfilers(runData, stats, draw_times, dtime);
1799                 processUserInput(&flags, &runData, dtime);
1800                 // Update camera before player movement to avoid camera lag of one frame
1801                 updateCameraDirection(&cam_view_target, &flags);
1802                 float cam_smoothing = 0;
1803                 if (g_settings->getBool("cinematic"))
1804                         cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1805                 else
1806                         cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1807                 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1808                 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1809                                 cam_view.camera_yaw) * cam_smoothing;
1810                 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1811                                 cam_view.camera_pitch) * cam_smoothing;
1812                 updatePlayerControl(cam_view);
1813                 step(&dtime);
1814                 processClientEvents(&cam_view_target, &runData.damage_flash);
1815                 updateCamera(&flags, draw_times.busy_time, dtime,
1816                                 runData.time_from_last_punch);
1817                 updateSound(dtime);
1818                 processPlayerInteraction(highlight_boxes, &runData, dtime,
1819                                 flags.show_hud, flags.show_debug);
1820                 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1821                                 flags, cam_view);
1822                 updateProfilerGraphs(&graph);
1823         }
1824 }
1825
1826
1827 void Game::shutdown()
1828 {
1829         showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1830
1831         if (clouds)
1832                 clouds->drop();
1833
1834         if (gui_chat_console)
1835                 gui_chat_console->drop();
1836
1837         if (sky)
1838                 sky->drop();
1839
1840         /* cleanup menus */
1841         while (g_menumgr.menuCount() > 0) {
1842                 g_menumgr.m_stack.front()->setVisible(false);
1843                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1844         }
1845
1846         if (current_formspec) {
1847                 current_formspec->drop();
1848                 current_formspec = NULL;
1849         }
1850
1851         chat_backend->addMessage(L"", L"# Disconnected.");
1852         chat_backend->addMessage(L"", L"");
1853
1854         if (client) {
1855                 client->Stop();
1856                 while (!client->isShutdown()) {
1857                         assert(texture_src != NULL);
1858                         assert(shader_src != NULL);
1859                         texture_src->processQueue();
1860                         shader_src->processQueue();
1861                         sleep_ms(100);
1862                 }
1863         }
1864 }
1865
1866
1867 /****************************************************************************/
1868 /****************************************************************************
1869  Startup
1870  ****************************************************************************/
1871 /****************************************************************************/
1872
1873 bool Game::init(
1874                 const std::string &map_dir,
1875                 std::string *address,
1876                 u16 port,
1877                 const SubgameSpec &gamespec)
1878 {
1879         showOverlayMessage(wgettext("Loading..."), 0, 0);
1880
1881         texture_src = createTextureSource(device);
1882         shader_src = createShaderSource(device);
1883
1884         itemdef_manager = createItemDefManager();
1885         nodedef_manager = createNodeDefManager();
1886
1887         eventmgr = new EventManager();
1888         quicktune = new QuicktuneShortcutter();
1889
1890         if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1891                         && eventmgr && quicktune))
1892                 return false;
1893
1894         if (!initSound())
1895                 return false;
1896
1897         // Create a server if not connecting to an existing one
1898         if (*address == "") {
1899                 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1900                         return false;
1901         }
1902
1903         return true;
1904 }
1905
1906 bool Game::initSound()
1907 {
1908 #if USE_SOUND
1909         if (g_settings->getBool("enable_sound")) {
1910                 infostream << "Attempting to use OpenAL audio" << std::endl;
1911                 sound = createOpenALSoundManager(&soundfetcher);
1912                 if (!sound)
1913                         infostream << "Failed to initialize OpenAL audio" << std::endl;
1914         } else
1915                 infostream << "Sound disabled." << std::endl;
1916 #endif
1917
1918         if (!sound) {
1919                 infostream << "Using dummy audio." << std::endl;
1920                 sound = &dummySoundManager;
1921                 sound_is_dummy = true;
1922         }
1923
1924         soundmaker = new SoundMaker(sound, nodedef_manager);
1925         if (!soundmaker)
1926                 return false;
1927
1928         soundmaker->registerReceiver(eventmgr);
1929
1930         return true;
1931 }
1932
1933 bool Game::createSingleplayerServer(const std::string map_dir,
1934                 const SubgameSpec &gamespec, u16 port, std::string *address)
1935 {
1936         showOverlayMessage(wgettext("Creating server..."), 0, 5);
1937
1938         std::string bind_str = g_settings->get("bind_address");
1939         Address bind_addr(0, 0, 0, 0, port);
1940
1941         if (g_settings->getBool("ipv6_server")) {
1942                 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1943         }
1944
1945         try {
1946                 bind_addr.Resolve(bind_str.c_str());
1947         } catch (ResolveError &e) {
1948                 infostream << "Resolving bind address \"" << bind_str
1949                            << "\" failed: " << e.what()
1950                            << " -- Listening on all addresses." << std::endl;
1951         }
1952
1953         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1954                 *error_message = "Unable to listen on " +
1955                                 bind_addr.serializeString() +
1956                                 " because IPv6 is disabled";
1957                 errorstream << *error_message << std::endl;
1958                 return false;
1959         }
1960
1961         server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1962                             bind_addr.isIPv6());
1963
1964         server->start(bind_addr);
1965
1966         return true;
1967 }
1968
1969 bool Game::createClient(const std::string &playername,
1970                 const std::string &password, std::string *address, u16 port)
1971 {
1972         showOverlayMessage(wgettext("Creating client..."), 0, 10);
1973
1974         draw_control = new MapDrawControl;
1975         if (!draw_control)
1976                 return false;
1977
1978         bool could_connect, connect_aborted;
1979
1980         if (!connectToServer(playername, password, address, port,
1981                         &could_connect, &connect_aborted))
1982                 return false;
1983
1984         if (!could_connect) {
1985                 if (error_message->empty() && !connect_aborted) {
1986                         // Should not happen if error messages are set properly
1987                         *error_message = "Connection failed for unknown reason";
1988                         errorstream << *error_message << std::endl;
1989                 }
1990                 return false;
1991         }
1992
1993         if (!getServerContent(&connect_aborted)) {
1994                 if (error_message->empty() && !connect_aborted) {
1995                         // Should not happen if error messages are set properly
1996                         *error_message = "Connection failed for unknown reason";
1997                         errorstream << *error_message << std::endl;
1998                 }
1999                 return false;
2000         }
2001
2002         // Update cached textures, meshes and materials
2003         client->afterContentReceived(device);
2004
2005         /* Camera
2006          */
2007         camera = new Camera(smgr, *draw_control, gamedef);
2008         if (!camera || !camera->successfullyCreated(*error_message))
2009                 return false;
2010
2011         /* Clouds
2012          */
2013         if (m_cache_enable_clouds) {
2014                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2015                 if (!clouds) {
2016                         *error_message = "Memory allocation error (clouds)";
2017                         errorstream << *error_message << std::endl;
2018                         return false;
2019                 }
2020         }
2021
2022         /* Skybox
2023          */
2024         sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2025         skybox = NULL;  // This is used/set later on in the main run loop
2026
2027         local_inventory = new Inventory(itemdef_manager);
2028
2029         if (!(sky && local_inventory)) {
2030                 *error_message = "Memory allocation error (sky or local inventory)";
2031                 errorstream << *error_message << std::endl;
2032                 return false;
2033         }
2034
2035         /* Pre-calculated values
2036          */
2037         video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2038         if (t) {
2039                 v2u32 size = t->getOriginalSize();
2040                 crack_animation_length = size.Y / size.X;
2041         } else {
2042                 crack_animation_length = 5;
2043         }
2044
2045         if (!initGui())
2046                 return false;
2047
2048         /* Set window caption
2049          */
2050         std::wstring str = narrow_to_wide(PROJECT_NAME_C);
2051         str += L" [";
2052         str += driver->getName();
2053         str += L"]";
2054         device->setWindowCaption(str.c_str());
2055
2056         LocalPlayer *player = client->getEnv().getLocalPlayer();
2057         player->hurt_tilt_timer = 0;
2058         player->hurt_tilt_strength = 0;
2059
2060         hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2061
2062         if (!hud) {
2063                 *error_message = "Memory error: could not create HUD";
2064                 errorstream << *error_message << std::endl;
2065                 return false;
2066         }
2067
2068         return true;
2069 }
2070
2071 bool Game::initGui()
2072 {
2073         // First line of debug text
2074         guitext = guienv->addStaticText(
2075                         narrow_to_wide(PROJECT_NAME_C).c_str(),
2076                         core::rect<s32>(0, 0, 0, 0),
2077                         false, false, guiroot);
2078
2079         // Second line of debug text
2080         guitext2 = guienv->addStaticText(
2081                         L"",
2082                         core::rect<s32>(0, 0, 0, 0),
2083                         false, false, guiroot);
2084
2085         // At the middle of the screen
2086         // Object infos are shown in this
2087         guitext_info = guienv->addStaticText(
2088                         L"",
2089                         core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2090                         false, true, guiroot);
2091
2092         // Status text (displays info when showing and hiding GUI stuff, etc.)
2093         guitext_status = guienv->addStaticText(
2094                         L"<Status>",
2095                         core::rect<s32>(0, 0, 0, 0),
2096                         false, false, guiroot);
2097         guitext_status->setVisible(false);
2098
2099         // Chat text
2100         guitext_chat = guienv->addStaticText(
2101                         L"",
2102                         core::rect<s32>(0, 0, 0, 0),
2103                         //false, false); // Disable word wrap as of now
2104                         false, true, guiroot);
2105         // Remove stale "recent" chat messages from previous connections
2106         chat_backend->clearRecentChat();
2107
2108         // Chat backend and console
2109         gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2110                         -1, chat_backend, client);
2111         if (!gui_chat_console) {
2112                 *error_message = "Could not allocate memory for chat console";
2113                 errorstream << *error_message << std::endl;
2114                 return false;
2115         }
2116
2117         // Profiler text (size is updated when text is updated)
2118         guitext_profiler = guienv->addStaticText(
2119                         L"<Profiler>",
2120                         core::rect<s32>(0, 0, 0, 0),
2121                         false, false, guiroot);
2122         guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2123         guitext_profiler->setVisible(false);
2124         guitext_profiler->setWordWrap(true);
2125
2126 #ifdef HAVE_TOUCHSCREENGUI
2127
2128         if (g_touchscreengui)
2129                 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2130
2131 #endif
2132
2133         return true;
2134 }
2135
2136 bool Game::connectToServer(const std::string &playername,
2137                 const std::string &password, std::string *address, u16 port,
2138                 bool *connect_ok, bool *aborted)
2139 {
2140         *connect_ok = false;    // Let's not be overly optimistic
2141         *aborted = false;
2142         bool local_server_mode = false;
2143
2144         showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2145
2146         Address connect_address(0, 0, 0, 0, port);
2147
2148         try {
2149                 connect_address.Resolve(address->c_str());
2150
2151                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2152                         //connect_address.Resolve("localhost");
2153                         if (connect_address.isIPv6()) {
2154                                 IPv6AddressBytes addr_bytes;
2155                                 addr_bytes.bytes[15] = 1;
2156                                 connect_address.setAddress(&addr_bytes);
2157                         } else {
2158                                 connect_address.setAddress(127, 0, 0, 1);
2159                         }
2160                         local_server_mode = true;
2161                 }
2162         } catch (ResolveError &e) {
2163                 *error_message = std::string("Couldn't resolve address: ") + e.what();
2164                 errorstream << *error_message << std::endl;
2165                 return false;
2166         }
2167
2168         if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2169                 *error_message = "Unable to connect to " +
2170                                 connect_address.serializeString() +
2171                                 " because IPv6 is disabled";
2172                 errorstream << *error_message << std::endl;
2173                 return false;
2174         }
2175
2176         client = new Client(device,
2177                         playername.c_str(), password,
2178                         *draw_control, texture_src, shader_src,
2179                         itemdef_manager, nodedef_manager, sound, eventmgr,
2180                         connect_address.isIPv6());
2181
2182         if (!client)
2183                 return false;
2184
2185         gamedef = client;       // Client acts as our GameDef
2186
2187         infostream << "Connecting to server at ";
2188         connect_address.print(&infostream);
2189         infostream << std::endl;
2190
2191         client->connect(connect_address, *address,
2192                 simple_singleplayer_mode || local_server_mode);
2193
2194         /*
2195                 Wait for server to accept connection
2196         */
2197
2198         try {
2199                 input->clear();
2200
2201                 FpsControl fps_control = { 0 };
2202                 f32 dtime;
2203                 f32 wait_time = 0; // in seconds
2204
2205                 fps_control.last_time = device->getTimer()->getTime();
2206
2207                 while (device->run()) {
2208
2209                         limitFps(&fps_control, &dtime);
2210
2211                         // Update client and server
2212                         client->step(dtime);
2213
2214                         if (server != NULL)
2215                                 server->step(dtime);
2216
2217                         // End condition
2218                         if (client->getState() == LC_Init) {
2219                                 *connect_ok = true;
2220                                 break;
2221                         }
2222
2223                         // Break conditions
2224                         if (client->accessDenied()) {
2225                                 *error_message = "Access denied. Reason: "
2226                                                 + client->accessDeniedReason();
2227                                 errorstream << *error_message << std::endl;
2228                                 break;
2229                         }
2230
2231                         if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2232                                 *aborted = true;
2233                                 infostream << "Connect aborted [Escape]" << std::endl;
2234                                 break;
2235                         }
2236
2237                         wait_time += dtime;
2238                         // Only time out if we aren't waiting for the server we started
2239                         if ((*address != "") && (wait_time > 10)) {
2240                                 *error_message = "Connection timed out.";
2241                                 errorstream << *error_message << std::endl;
2242                                 break;
2243                         }
2244
2245                         // Update status
2246                         showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2247                 }
2248         } catch (con::PeerNotFoundException &e) {
2249                 // TODO: Should something be done here? At least an info/error
2250                 // message?
2251                 return false;
2252         }
2253
2254         return true;
2255 }
2256
2257 bool Game::getServerContent(bool *aborted)
2258 {
2259         input->clear();
2260
2261         FpsControl fps_control = { 0 };
2262         f32 dtime; // in seconds
2263
2264         fps_control.last_time = device->getTimer()->getTime();
2265
2266         while (device->run()) {
2267
2268                 limitFps(&fps_control, &dtime);
2269
2270                 // Update client and server
2271                 client->step(dtime);
2272
2273                 if (server != NULL)
2274                         server->step(dtime);
2275
2276                 // End condition
2277                 if (client->mediaReceived() && client->itemdefReceived() &&
2278                                 client->nodedefReceived()) {
2279                         break;
2280                 }
2281
2282                 // Error conditions
2283                 if (!checkConnection())
2284                         return false;
2285
2286                 if (client->getState() < LC_Init) {
2287                         *error_message = "Client disconnected";
2288                         errorstream << *error_message << std::endl;
2289                         return false;
2290                 }
2291
2292                 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2293                         *aborted = true;
2294                         infostream << "Connect aborted [Escape]" << std::endl;
2295                         return false;
2296                 }
2297
2298                 // Display status
2299                 int progress = 25;
2300
2301                 if (!client->itemdefReceived()) {
2302                         const wchar_t *text = wgettext("Item definitions...");
2303                         progress = 25;
2304                         draw_load_screen(text, device, guienv, dtime, progress);
2305                         delete[] text;
2306                 } else if (!client->nodedefReceived()) {
2307                         const wchar_t *text = wgettext("Node definitions...");
2308                         progress = 30;
2309                         draw_load_screen(text, device, guienv, dtime, progress);
2310                         delete[] text;
2311                 } else {
2312                         std::stringstream message;
2313                         message.precision(3);
2314                         message << gettext("Media...");
2315
2316                         if ((USE_CURL == 0) ||
2317                                         (!g_settings->getBool("enable_remote_media_server"))) {
2318                                 float cur = client->getCurRate();
2319                                 std::string cur_unit = gettext("KiB/s");
2320
2321                                 if (cur > 900) {
2322                                         cur /= 1024.0;
2323                                         cur_unit = gettext("MiB/s");
2324                                 }
2325
2326                                 message << " (" << cur << ' ' << cur_unit << ")";
2327                         }
2328
2329                         progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2330                         draw_load_screen(narrow_to_wide(message.str()), device,
2331                                         guienv, dtime, progress);
2332                 }
2333         }
2334
2335         return true;
2336 }
2337
2338
2339 /****************************************************************************/
2340 /****************************************************************************
2341  Run
2342  ****************************************************************************/
2343 /****************************************************************************/
2344
2345 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2346 {
2347         if (runData->nodig_delay_timer >= 0)
2348                 runData->nodig_delay_timer -= dtime;
2349
2350         if (runData->object_hit_delay_timer >= 0)
2351                 runData->object_hit_delay_timer -= dtime;
2352
2353         runData->time_from_last_punch += dtime;
2354 }
2355
2356
2357 /* returns false if game should exit, otherwise true
2358  */
2359 inline bool Game::checkConnection()
2360 {
2361         if (client->accessDenied()) {
2362                 *error_message = "Access denied. Reason: "
2363                                 + client->accessDeniedReason();
2364                 errorstream << *error_message << std::endl;
2365                 return false;
2366         }
2367
2368         return true;
2369 }
2370
2371
2372 /* returns false if game should exit, otherwise true
2373  */
2374 inline bool Game::handleCallbacks()
2375 {
2376         if (g_gamecallback->disconnect_requested) {
2377                 g_gamecallback->disconnect_requested = false;
2378                 return false;
2379         }
2380
2381         if (g_gamecallback->changepassword_requested) {
2382                 (new GUIPasswordChange(guienv, guiroot, -1,
2383                                        &g_menumgr, client))->drop();
2384                 g_gamecallback->changepassword_requested = false;
2385         }
2386
2387         if (g_gamecallback->changevolume_requested) {
2388                 (new GUIVolumeChange(guienv, guiroot, -1,
2389                                      &g_menumgr, client))->drop();
2390                 g_gamecallback->changevolume_requested = false;
2391         }
2392
2393         if (g_gamecallback->keyconfig_requested) {
2394                 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2395                                       &g_menumgr))->drop();
2396                 g_gamecallback->keyconfig_requested = false;
2397         }
2398
2399         if (g_gamecallback->keyconfig_changed) {
2400                 keycache.populate(); // update the cache with new settings
2401                 g_gamecallback->keyconfig_changed = false;
2402         }
2403
2404         return true;
2405 }
2406
2407
2408 void Game::processQueues()
2409 {
2410         texture_src->processQueue();
2411         itemdef_manager->processQueue(gamedef);
2412         shader_src->processQueue();
2413 }
2414
2415
2416 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2417                 const FpsControl &draw_times, f32 dtime)
2418 {
2419         float profiler_print_interval =
2420                         g_settings->getFloat("profiler_print_interval");
2421         bool print_to_log = true;
2422
2423         if (profiler_print_interval == 0) {
2424                 print_to_log = false;
2425                 profiler_print_interval = 5;
2426         }
2427
2428         if (profiler_interval.step(dtime, profiler_print_interval)) {
2429                 if (print_to_log) {
2430                         infostream << "Profiler:" << std::endl;
2431                         g_profiler->print(infostream);
2432                 }
2433
2434                 update_profiler_gui(guitext_profiler, g_fontengine,
2435                                 runData.profiler_current_page, runData.profiler_max_page,
2436                                 driver->getScreenSize().Height);
2437
2438                 g_profiler->clear();
2439         }
2440
2441         addProfilerGraphs(stats, draw_times, dtime);
2442 }
2443
2444
2445 void Game::addProfilerGraphs(const RunStats &stats,
2446                 const FpsControl &draw_times, f32 dtime)
2447 {
2448         g_profiler->graphAdd("mainloop_other",
2449                         draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2450
2451         if (draw_times.sleep_time != 0)
2452                 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2453         g_profiler->graphAdd("mainloop_dtime", dtime);
2454
2455         g_profiler->add("Elapsed time", dtime);
2456         g_profiler->avg("FPS", 1. / dtime);
2457 }
2458
2459
2460 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2461                 f32 dtime)
2462 {
2463
2464         f32 jitter;
2465         Jitter *jp;
2466
2467         /* Time average and jitter calculation
2468          */
2469         jp = &stats->dtime_jitter;
2470         jp->avg = jp->avg * 0.96 + dtime * 0.04;
2471
2472         jitter = dtime - jp->avg;
2473
2474         if (jitter > jp->max)
2475                 jp->max = jitter;
2476
2477         jp->counter += dtime;
2478
2479         if (jp->counter > 0.0) {
2480                 jp->counter -= 3.0;
2481                 jp->max_sample = jp->max;
2482                 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2483                 jp->max = 0.0;
2484         }
2485
2486         /* Busytime average and jitter calculation
2487          */
2488         jp = &stats->busy_time_jitter;
2489         jp->avg = jp->avg + draw_times.busy_time * 0.02;
2490
2491         jitter = draw_times.busy_time - jp->avg;
2492
2493         if (jitter > jp->max)
2494                 jp->max = jitter;
2495         if (jitter < jp->min)
2496                 jp->min = jitter;
2497
2498         jp->counter += dtime;
2499
2500         if (jp->counter > 0.0) {
2501                 jp->counter -= 3.0;
2502                 jp->max_sample = jp->max;
2503                 jp->min_sample = jp->min;
2504                 jp->max = 0.0;
2505                 jp->min = 0.0;
2506         }
2507 }
2508
2509
2510
2511 /****************************************************************************
2512  Input handling
2513  ****************************************************************************/
2514
2515 void Game::processUserInput(VolatileRunFlags *flags,
2516                 GameRunData *runData, f32 dtime)
2517 {
2518         // Reset input if window not active or some menu is active
2519         if (device->isWindowActive() == false
2520                         || noMenuActive() == false
2521                         || guienv->hasFocus(gui_chat_console)) {
2522                 input->clear();
2523         }
2524
2525         if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2526                 gui_chat_console->closeConsoleAtOnce();
2527         }
2528
2529         // Input handler step() (used by the random input generator)
2530         input->step(dtime);
2531
2532 #ifdef HAVE_TOUCHSCREENGUI
2533
2534         if (g_touchscreengui) {
2535                 g_touchscreengui->step(dtime);
2536         }
2537
2538 #endif
2539 #ifdef __ANDROID__
2540
2541         if (current_formspec != 0)
2542                 current_formspec->getAndroidUIInput();
2543
2544 #endif
2545
2546         // Increase timer for double tap of "keymap_jump"
2547         if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2548                 runData->jump_timer += dtime;
2549
2550         processKeyboardInput(
2551                         flags,
2552                         &runData->statustext_time,
2553                         &runData->jump_timer,
2554                         &runData->reset_jump_timer,
2555                         &runData->profiler_current_page,
2556                         runData->profiler_max_page);
2557
2558         processItemSelection(&runData->new_playeritem);
2559 }
2560
2561
2562 void Game::processKeyboardInput(VolatileRunFlags *flags,
2563                 float *statustext_time,
2564                 float *jump_timer,
2565                 bool *reset_jump_timer,
2566                 u32 *profiler_current_page,
2567                 u32 profiler_max_page)
2568 {
2569
2570         //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2571
2572         if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2573                 dropSelectedItem();
2574         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2575                 openInventory();
2576         } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2577                 show_pause_menu(&current_formspec, client, gamedef, texture_src, device,
2578                                 simple_singleplayer_mode);
2579         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2580                 show_chat_menu(&current_formspec, client, gamedef, texture_src, device,
2581                                 client, "");
2582         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2583                 show_chat_menu(&current_formspec, client, gamedef, texture_src, device,
2584                                 client, "/");
2585         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2586                 openConsole();
2587         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2588                 toggleFreeMove(statustext_time);
2589         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2590                 toggleFreeMoveAlt(statustext_time, jump_timer);
2591                 *reset_jump_timer = true;
2592         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2593                 toggleFast(statustext_time);
2594         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2595                 toggleNoClip(statustext_time);
2596         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2597                 toggleCinematic(statustext_time);
2598         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2599                 client->makeScreenshot(device);
2600         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2601                 toggleHud(statustext_time, &flags->show_hud);
2602         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2603                 toggleChat(statustext_time, &flags->show_chat);
2604         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2605                 toggleFog(statustext_time, &flags->force_fog_off);
2606         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2607                 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2608         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2609                 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2610         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2611                 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2612         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2613                 increaseViewRange(statustext_time);
2614         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2615                 decreaseViewRange(statustext_time);
2616         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2617                 toggleFullViewRange(statustext_time);
2618         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2619                 quicktune->next();
2620         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2621                 quicktune->prev();
2622         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2623                 quicktune->inc();
2624         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2625                 quicktune->dec();
2626         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2627                 // Print debug stacks
2628                 dstream << "-----------------------------------------"
2629                         << std::endl;
2630                 dstream << DTIME << "Printing debug stacks:" << std::endl;
2631                 dstream << "-----------------------------------------"
2632                         << std::endl;
2633                 debug_stacks_print();
2634         }
2635
2636         if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2637                 *reset_jump_timer = false;
2638                 *jump_timer = 0.0;
2639         }
2640
2641         //tt.stop();
2642
2643         if (quicktune->hasMessage()) {
2644                 std::string msg = quicktune->getMessage();
2645                 statustext = narrow_to_wide(msg);
2646                 *statustext_time = 0;
2647         }
2648 }
2649
2650
2651 void Game::processItemSelection(u16 *new_playeritem)
2652 {
2653         LocalPlayer *player = client->getEnv().getLocalPlayer();
2654
2655         /* Item selection using mouse wheel
2656          */
2657         *new_playeritem = client->getPlayerItem();
2658
2659         s32 wheel = input->getMouseWheel();
2660         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2661                                  player->hud_hotbar_itemcount - 1);
2662
2663         if (wheel < 0)
2664                 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2665         else if (wheel > 0)
2666                 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2667         // else wheel == 0
2668
2669
2670         /* Item selection using keyboard
2671          */
2672         for (u16 i = 0; i < 10; i++) {
2673                 static const KeyPress *item_keys[10] = {
2674                         NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2675                         NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2676                         NumberKey + 9, NumberKey + 0,
2677                 };
2678
2679                 if (input->wasKeyDown(*item_keys[i])) {
2680                         if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2681                                 *new_playeritem = i;
2682                                 infostream << "Selected item: " << new_playeritem << std::endl;
2683                         }
2684                         break;
2685                 }
2686         }
2687 }
2688
2689
2690 void Game::dropSelectedItem()
2691 {
2692         IDropAction *a = new IDropAction();
2693         a->count = 0;
2694         a->from_inv.setCurrentPlayer();
2695         a->from_list = "main";
2696         a->from_i = client->getPlayerItem();
2697         client->inventoryAction(a);
2698 }
2699
2700
2701 void Game::openInventory()
2702 {
2703         /*
2704          * Don't permit to open inventory is CAO or player doesn't exists.
2705          * This prevent showing an empty inventory at player load
2706          */
2707
2708         LocalPlayer *player = client->getEnv().getLocalPlayer();
2709         if (player == NULL || player->getCAO() == NULL)
2710                 return;
2711
2712         infostream << "the_game: " << "Launching inventory" << std::endl;
2713
2714         PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2715         TextDest *txt_dst = new TextDestPlayerInventory(client);
2716
2717         create_formspec_menu(&current_formspec, client, gamedef, texture_src,
2718                         device, fs_src, txt_dst, client);
2719
2720         InventoryLocation inventoryloc;
2721         inventoryloc.setCurrentPlayer();
2722         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2723 }
2724
2725
2726 void Game::openConsole()
2727 {
2728         if (!gui_chat_console->isOpenInhibited()) {
2729                 // Open up to over half of the screen
2730                 gui_chat_console->openConsole(0.6);
2731                 guienv->setFocus(gui_chat_console);
2732         }
2733 }
2734
2735
2736 void Game::toggleFreeMove(float *statustext_time)
2737 {
2738         static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2739
2740         bool free_move = !g_settings->getBool("free_move");
2741         g_settings->set("free_move", bool_to_cstr(free_move));
2742
2743         *statustext_time = 0;
2744         statustext = msg[free_move];
2745         if (free_move && !client->checkPrivilege("fly"))
2746                 statustext += L" (note: no 'fly' privilege)";
2747 }
2748
2749
2750 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2751 {
2752         if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2753                 toggleFreeMove(statustext_time);
2754 }
2755
2756
2757 void Game::toggleFast(float *statustext_time)
2758 {
2759         static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2760         bool fast_move = !g_settings->getBool("fast_move");
2761         g_settings->set("fast_move", bool_to_cstr(fast_move));
2762
2763         *statustext_time = 0;
2764         statustext = msg[fast_move];
2765
2766         bool has_fast_privs = client->checkPrivilege("fast");
2767
2768         if (fast_move && !has_fast_privs)
2769                 statustext += L" (note: no 'fast' privilege)";
2770
2771 #ifdef __ANDROID__
2772         m_cache_hold_aux1 = fast_move && has_fast_privs;
2773 #endif
2774 }
2775
2776
2777 void Game::toggleNoClip(float *statustext_time)
2778 {
2779         static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2780         bool noclip = !g_settings->getBool("noclip");
2781         g_settings->set("noclip", bool_to_cstr(noclip));
2782
2783         *statustext_time = 0;
2784         statustext = msg[noclip];
2785
2786         if (noclip && !client->checkPrivilege("noclip"))
2787                 statustext += L" (note: no 'noclip' privilege)";
2788 }
2789
2790 void Game::toggleCinematic(float *statustext_time)
2791 {
2792         static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2793         bool cinematic = !g_settings->getBool("cinematic");
2794         g_settings->set("cinematic", bool_to_cstr(cinematic));
2795
2796         *statustext_time = 0;
2797         statustext = msg[cinematic];
2798 }
2799
2800
2801 void Game::toggleChat(float *statustext_time, bool *flag)
2802 {
2803         static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2804
2805         *flag = !*flag;
2806         *statustext_time = 0;
2807         statustext = msg[*flag];
2808 }
2809
2810
2811 void Game::toggleHud(float *statustext_time, bool *flag)
2812 {
2813         static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2814
2815         *flag = !*flag;
2816         *statustext_time = 0;
2817         statustext = msg[*flag];
2818         if (g_settings->getBool("enable_node_highlighting"))
2819                 client->setHighlighted(client->getHighlighted(), *flag);
2820 }
2821
2822
2823 void Game::toggleFog(float *statustext_time, bool *flag)
2824 {
2825         static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2826
2827         *flag = !*flag;
2828         *statustext_time = 0;
2829         statustext = msg[*flag];
2830 }
2831
2832
2833 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2834                 bool *show_profiler_graph)
2835 {
2836         // Initial / 3x toggle: Chat only
2837         // 1x toggle: Debug text with chat
2838         // 2x toggle: Debug text with profiler graph
2839         if (!*show_debug) {
2840                 *show_debug = true;
2841                 *show_profiler_graph = false;
2842                 statustext = L"Debug info shown";
2843         } else if (*show_profiler_graph) {
2844                 *show_debug = false;
2845                 *show_profiler_graph = false;
2846                 statustext = L"Debug info and profiler graph hidden";
2847         } else {
2848                 *show_profiler_graph = true;
2849                 statustext = L"Profiler graph shown";
2850         }
2851         *statustext_time = 0;
2852 }
2853
2854
2855 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2856 {
2857         static const wchar_t *msg[] = {
2858                 L"Camera update enabled",
2859                 L"Camera update disabled"
2860         };
2861
2862         *flag = !*flag;
2863         *statustext_time = 0;
2864         statustext = msg[*flag];
2865 }
2866
2867
2868 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2869                 u32 profiler_max_page)
2870 {
2871         *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2872
2873         // FIXME: This updates the profiler with incomplete values
2874         update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2875                         profiler_max_page, driver->getScreenSize().Height);
2876
2877         if (*profiler_current_page != 0) {
2878                 std::wstringstream sstr;
2879                 sstr << "Profiler shown (page " << *profiler_current_page
2880                      << " of " << profiler_max_page << ")";
2881                 statustext = sstr.str();
2882         } else {
2883                 statustext = L"Profiler hidden";
2884         }
2885         *statustext_time = 0;
2886 }
2887
2888
2889 void Game::increaseViewRange(float *statustext_time)
2890 {
2891         s16 range = g_settings->getS16("viewing_range_nodes_min");
2892         s16 range_new = range + 10;
2893         g_settings->set("viewing_range_nodes_min", itos(range_new));
2894         statustext = narrow_to_wide("Minimum viewing range changed to "
2895                         + itos(range_new));
2896         *statustext_time = 0;
2897 }
2898
2899
2900 void Game::decreaseViewRange(float *statustext_time)
2901 {
2902         s16 range = g_settings->getS16("viewing_range_nodes_min");
2903         s16 range_new = range - 10;
2904
2905         if (range_new < 0)
2906                 range_new = range;
2907
2908         g_settings->set("viewing_range_nodes_min", itos(range_new));
2909         statustext = narrow_to_wide("Minimum viewing range changed to "
2910                         + itos(range_new));
2911         *statustext_time = 0;
2912 }
2913
2914
2915 void Game::toggleFullViewRange(float *statustext_time)
2916 {
2917         static const wchar_t *msg[] = {
2918                 L"Disabled full viewing range",
2919                 L"Enabled full viewing range"
2920         };
2921
2922         draw_control->range_all = !draw_control->range_all;
2923         infostream << msg[draw_control->range_all] << std::endl;
2924         statustext = msg[draw_control->range_all];
2925         *statustext_time = 0;
2926 }
2927
2928
2929 void Game::updateCameraDirection(CameraOrientation *cam,
2930                 VolatileRunFlags *flags)
2931 {
2932         if ((device->isWindowActive() && noMenuActive()) || random_input) {
2933
2934 #ifndef __ANDROID__
2935                 if (!random_input) {
2936                         // Mac OSX gets upset if this is set every frame
2937                         if (device->getCursorControl()->isVisible())
2938                                 device->getCursorControl()->setVisible(false);
2939                 }
2940 #endif
2941
2942                 if (flags->first_loop_after_window_activation)
2943                         flags->first_loop_after_window_activation = false;
2944                 else
2945                         updateCameraOrientation(cam, *flags);
2946
2947                 input->setMousePos((driver->getScreenSize().Width / 2),
2948                                 (driver->getScreenSize().Height / 2));
2949         } else {
2950
2951 #ifndef ANDROID
2952                 // Mac OSX gets upset if this is set every frame
2953                 if (device->getCursorControl()->isVisible() == false)
2954                         device->getCursorControl()->setVisible(true);
2955 #endif
2956
2957                 if (!flags->first_loop_after_window_activation)
2958                         flags->first_loop_after_window_activation = true;
2959
2960         }
2961 }
2962
2963
2964 void Game::updateCameraOrientation(CameraOrientation *cam,
2965                 const VolatileRunFlags &flags)
2966 {
2967 #ifdef HAVE_TOUCHSCREENGUI
2968         if (g_touchscreengui) {
2969                 cam->camera_yaw   = g_touchscreengui->getYaw();
2970                 cam->camera_pitch = g_touchscreengui->getPitch();
2971         } else {
2972 #endif
2973                 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2974                 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2975
2976                 if (flags.invert_mouse
2977                                 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2978                         dy = -dy;
2979                 }
2980
2981                 cam->camera_yaw   -= dx * m_cache_mouse_sensitivity;
2982                 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
2983
2984 #ifdef HAVE_TOUCHSCREENGUI
2985         }
2986 #endif
2987
2988         cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
2989 }
2990
2991
2992 void Game::updatePlayerControl(const CameraOrientation &cam)
2993 {
2994         //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2995
2996         PlayerControl control(
2997                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2998                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2999                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3000                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3001                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3002                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3003                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3004                 input->getLeftState(),
3005                 input->getRightState(),
3006                 cam.camera_pitch,
3007                 cam.camera_yaw
3008         );
3009
3010         u32 keypress_bits =
3011                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD])  & 0x1) << 0) |
3012                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3013                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT])     & 0x1) << 2) |
3014                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT])    & 0x1) << 3) |
3015                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])     & 0x1) << 4) |
3016                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3017                         ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK])    & 0x1) << 6) |
3018                         ( (u32)(input->getLeftState()                                        & 0x1) << 7) |
3019                         ( (u32)(input->getRightState()                                       & 0x1) << 8
3020                 );
3021
3022 #ifdef ANDROID
3023         /* For Android, simulate holding down AUX1 (fast move) if the user has
3024          * the fast_move setting toggled on. If there is an aux1 key defined for
3025          * Android then its meaning is inverted (i.e. holding aux1 means walk and
3026          * not fast)
3027          */
3028         if (m_cache_hold_aux1) {
3029                 control.aux1 = control.aux1 ^ true;
3030                 keypress_bits ^= ((u32)(1U << 5));
3031         }
3032 #endif
3033
3034         client->setPlayerControl(control);
3035         LocalPlayer *player = client->getEnv().getLocalPlayer();
3036         player->keyPressed = keypress_bits;
3037
3038         //tt.stop();
3039 }
3040
3041
3042 inline void Game::step(f32 *dtime)
3043 {
3044         bool can_be_and_is_paused =
3045                         (simple_singleplayer_mode && g_menumgr.pausesGame());
3046
3047         if (can_be_and_is_paused) {     // This is for a singleplayer server
3048                 *dtime = 0;             // No time passes
3049         } else {
3050                 if (server != NULL) {
3051                         //TimeTaker timer("server->step(dtime)");
3052                         server->step(*dtime);
3053                 }
3054
3055                 //TimeTaker timer("client.step(dtime)");
3056                 client->step(*dtime);
3057         }
3058 }
3059
3060
3061 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3062 {
3063         ClientEvent event = client->getClientEvent();
3064
3065         LocalPlayer *player = client->getEnv().getLocalPlayer();
3066
3067         for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3068
3069                 if (event.type == CE_PLAYER_DAMAGE &&
3070                                 client->getHP() != 0) {
3071                         //u16 damage = event.player_damage.amount;
3072                         //infostream<<"Player damage: "<<damage<<std::endl;
3073
3074                         *damage_flash += 100.0;
3075                         *damage_flash += 8.0 * event.player_damage.amount;
3076
3077                         player->hurt_tilt_timer = 1.5;
3078                         player->hurt_tilt_strength = event.player_damage.amount / 4;
3079                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3080
3081                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3082                         gamedef->event()->put(e);
3083                 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3084                         cam->camera_yaw = event.player_force_move.yaw;
3085                         cam->camera_pitch = event.player_force_move.pitch;
3086                 } else if (event.type == CE_DEATHSCREEN) {
3087                         show_deathscreen(&current_formspec, client, gamedef, texture_src,
3088                                          device, client);
3089
3090                         chat_backend->addMessage(L"", L"You died.");
3091
3092                         /* Handle visualization */
3093                         *damage_flash = 0;
3094                         player->hurt_tilt_timer = 0;
3095                         player->hurt_tilt_strength = 0;
3096
3097                 } else if (event.type == CE_SHOW_FORMSPEC) {
3098                         FormspecFormSource *fs_src =
3099                                 new FormspecFormSource(*(event.show_formspec.formspec));
3100                         TextDestPlayerInventory *txt_dst =
3101                                 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3102
3103                         create_formspec_menu(&current_formspec, client, gamedef,
3104                                              texture_src, device, fs_src, txt_dst, client);
3105
3106                         delete(event.show_formspec.formspec);
3107                         delete(event.show_formspec.formname);
3108                 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3109                                 (event.type == CE_ADD_PARTICLESPAWNER) ||
3110                                 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3111                         client->getParticleManager()->handleParticleEvent(&event, gamedef,
3112                                         smgr, player);
3113                 } else if (event.type == CE_HUDADD) {
3114                         u32 id = event.hudadd.id;
3115
3116                         LocalPlayer *player = client->getEnv().getLocalPlayer();
3117                         HudElement *e = player->getHud(id);
3118
3119                         if (e != NULL) {
3120                                 delete event.hudadd.pos;
3121                                 delete event.hudadd.name;
3122                                 delete event.hudadd.scale;
3123                                 delete event.hudadd.text;
3124                                 delete event.hudadd.align;
3125                                 delete event.hudadd.offset;
3126                                 delete event.hudadd.world_pos;
3127                                 delete event.hudadd.size;
3128                                 continue;
3129                         }
3130
3131                         e = new HudElement;
3132                         e->type   = (HudElementType)event.hudadd.type;
3133                         e->pos    = *event.hudadd.pos;
3134                         e->name   = *event.hudadd.name;
3135                         e->scale  = *event.hudadd.scale;
3136                         e->text   = *event.hudadd.text;
3137                         e->number = event.hudadd.number;
3138                         e->item   = event.hudadd.item;
3139                         e->dir    = event.hudadd.dir;
3140                         e->align  = *event.hudadd.align;
3141                         e->offset = *event.hudadd.offset;
3142                         e->world_pos = *event.hudadd.world_pos;
3143                         e->size = *event.hudadd.size;
3144
3145                         u32 new_id = player->addHud(e);
3146                         //if this isn't true our huds aren't consistent
3147                         sanity_check(new_id == id);
3148
3149                         delete event.hudadd.pos;
3150                         delete event.hudadd.name;
3151                         delete event.hudadd.scale;
3152                         delete event.hudadd.text;
3153                         delete event.hudadd.align;
3154                         delete event.hudadd.offset;
3155                         delete event.hudadd.world_pos;
3156                         delete event.hudadd.size;
3157                 } else if (event.type == CE_HUDRM) {
3158                         HudElement *e = player->removeHud(event.hudrm.id);
3159
3160                         if (e != NULL)
3161                                 delete(e);
3162                 } else if (event.type == CE_HUDCHANGE) {
3163                         u32 id = event.hudchange.id;
3164                         HudElement *e = player->getHud(id);
3165
3166                         if (e == NULL) {
3167                                 delete event.hudchange.v3fdata;
3168                                 delete event.hudchange.v2fdata;
3169                                 delete event.hudchange.sdata;
3170                                 delete event.hudchange.v2s32data;
3171                                 continue;
3172                         }
3173
3174                         switch (event.hudchange.stat) {
3175                         case HUD_STAT_POS:
3176                                 e->pos = *event.hudchange.v2fdata;
3177                                 break;
3178
3179                         case HUD_STAT_NAME:
3180                                 e->name = *event.hudchange.sdata;
3181                                 break;
3182
3183                         case HUD_STAT_SCALE:
3184                                 e->scale = *event.hudchange.v2fdata;
3185                                 break;
3186
3187                         case HUD_STAT_TEXT:
3188                                 e->text = *event.hudchange.sdata;
3189                                 break;
3190
3191                         case HUD_STAT_NUMBER:
3192                                 e->number = event.hudchange.data;
3193                                 break;
3194
3195                         case HUD_STAT_ITEM:
3196                                 e->item = event.hudchange.data;
3197                                 break;
3198
3199                         case HUD_STAT_DIR:
3200                                 e->dir = event.hudchange.data;
3201                                 break;
3202
3203                         case HUD_STAT_ALIGN:
3204                                 e->align = *event.hudchange.v2fdata;
3205                                 break;
3206
3207                         case HUD_STAT_OFFSET:
3208                                 e->offset = *event.hudchange.v2fdata;
3209                                 break;
3210
3211                         case HUD_STAT_WORLD_POS:
3212                                 e->world_pos = *event.hudchange.v3fdata;
3213                                 break;
3214
3215                         case HUD_STAT_SIZE:
3216                                 e->size = *event.hudchange.v2s32data;
3217                                 break;
3218                         }
3219
3220                         delete event.hudchange.v3fdata;
3221                         delete event.hudchange.v2fdata;
3222                         delete event.hudchange.sdata;
3223                         delete event.hudchange.v2s32data;
3224                 } else if (event.type == CE_SET_SKY) {
3225                         sky->setVisible(false);
3226
3227                         if (skybox) {
3228                                 skybox->remove();
3229                                 skybox = NULL;
3230                         }
3231
3232                         // Handle according to type
3233                         if (*event.set_sky.type == "regular") {
3234                                 sky->setVisible(true);
3235                         } else if (*event.set_sky.type == "skybox" &&
3236                                         event.set_sky.params->size() == 6) {
3237                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3238                                 skybox = smgr->addSkyBoxSceneNode(
3239                                                  texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3240                                                  texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3241                                                  texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3242                                                  texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3243                                                  texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3244                                                  texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3245                         }
3246                         // Handle everything else as plain color
3247                         else {
3248                                 if (*event.set_sky.type != "plain")
3249                                         infostream << "Unknown sky type: "
3250                                                    << (*event.set_sky.type) << std::endl;
3251
3252                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3253                         }
3254
3255                         delete event.set_sky.bgcolor;
3256                         delete event.set_sky.type;
3257                         delete event.set_sky.params;
3258                 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3259                         bool enable = event.override_day_night_ratio.do_override;
3260                         u32 value = event.override_day_night_ratio.ratio_f * 1000;
3261                         client->getEnv().setDayNightRatioOverride(enable, value);
3262                 }
3263         }
3264 }
3265
3266
3267 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3268                 f32 dtime, float time_from_last_punch)
3269 {
3270         LocalPlayer *player = client->getEnv().getLocalPlayer();
3271
3272         /*
3273                 For interaction purposes, get info about the held item
3274                 - What item is it?
3275                 - Is it a usable item?
3276                 - Can it point to liquids?
3277         */
3278         ItemStack playeritem;
3279         {
3280                 InventoryList *mlist = local_inventory->getList("main");
3281
3282                 if (mlist && client->getPlayerItem() < mlist->getSize())
3283                         playeritem = mlist->getItem(client->getPlayerItem());
3284         }
3285
3286         ToolCapabilities playeritem_toolcap =
3287                 playeritem.getToolCapabilities(itemdef_manager);
3288
3289         v3s16 old_camera_offset = camera->getOffset();
3290
3291         if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3292                 GenericCAO *playercao = player->getCAO();
3293
3294                 // If playercao not loaded, don't change camera
3295                 if (playercao == NULL)
3296                         return;
3297
3298                 camera->toggleCameraMode();
3299
3300                 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3301                 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3302         }
3303
3304         float full_punch_interval = playeritem_toolcap.full_punch_interval;
3305         float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3306
3307         tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3308         camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3309                       client->getEnv());
3310         camera->step(dtime);
3311
3312         v3f camera_position = camera->getPosition();
3313         v3f camera_direction = camera->getDirection();
3314         f32 camera_fov = camera->getFovMax();
3315         v3s16 camera_offset = camera->getOffset();
3316
3317         flags->camera_offset_changed = (camera_offset != old_camera_offset);
3318
3319         if (!flags->disable_camera_update) {
3320                 client->getEnv().getClientMap().updateCamera(camera_position,
3321                                 camera_direction, camera_fov, camera_offset);
3322
3323                 if (flags->camera_offset_changed) {
3324                         client->updateCameraOffset(camera_offset);
3325                         client->getEnv().updateCameraOffset(camera_offset);
3326
3327                         if (clouds)
3328                                 clouds->updateCameraOffset(camera_offset);
3329                 }
3330         }
3331 }
3332
3333
3334 void Game::updateSound(f32 dtime)
3335 {
3336         // Update sound listener
3337         v3s16 camera_offset = camera->getOffset();
3338         sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3339                               v3f(0, 0, 0), // velocity
3340                               camera->getDirection(),
3341                               camera->getCameraNode()->getUpVector());
3342         sound->setListenerGain(g_settings->getFloat("sound_volume"));
3343
3344
3345         //      Update sound maker
3346         soundmaker->step(dtime);
3347
3348         LocalPlayer *player = client->getEnv().getLocalPlayer();
3349
3350         ClientMap &map = client->getEnv().getClientMap();
3351         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3352         soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3353 }
3354
3355
3356 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3357                 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3358 {
3359         LocalPlayer *player = client->getEnv().getLocalPlayer();
3360
3361         ItemStack playeritem;
3362         {
3363                 InventoryList *mlist = local_inventory->getList("main");
3364
3365                 if (mlist && client->getPlayerItem() < mlist->getSize())
3366                         playeritem = mlist->getItem(client->getPlayerItem());
3367         }
3368
3369         const ItemDefinition &playeritem_def =
3370                         playeritem.getDefinition(itemdef_manager);
3371
3372         v3f player_position  = player->getPosition();
3373         v3f camera_position  = camera->getPosition();
3374         v3f camera_direction = camera->getDirection();
3375         v3s16 camera_offset  = camera->getOffset();
3376
3377
3378         /*
3379                 Calculate what block is the crosshair pointing to
3380         */
3381
3382         f32 d = playeritem_def.range; // max. distance
3383         f32 d_hand = itemdef_manager->get("").range;
3384
3385         if (d < 0 && d_hand >= 0)
3386                 d = d_hand;
3387         else if (d < 0)
3388                 d = 4.0;
3389
3390         core::line3d<f32> shootline;
3391
3392         if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3393
3394                 shootline = core::line3d<f32>(camera_position,
3395                                                 camera_position + camera_direction * BS * (d + 1));
3396
3397         } else {
3398             // prevent player pointing anything in front-view
3399                 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3400                         shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3401         }
3402
3403 #ifdef HAVE_TOUCHSCREENGUI
3404
3405         if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3406                 shootline = g_touchscreengui->getShootline();
3407                 shootline.start += intToFloat(camera_offset, BS);
3408                 shootline.end += intToFloat(camera_offset, BS);
3409         }
3410
3411 #endif
3412
3413         PointedThing pointed = getPointedThing(
3414                         // input
3415                         client, player_position, camera_direction,
3416                         camera_position, shootline, d,
3417                         playeritem_def.liquids_pointable,
3418                         !runData->ldown_for_dig,
3419                         camera_offset,
3420                         // output
3421                         highlight_boxes,
3422                         runData->selected_object);
3423
3424         if (pointed != runData->pointed_old) {
3425                 infostream << "Pointing at " << pointed.dump() << std::endl;
3426
3427                 if (m_cache_enable_node_highlighting) {
3428                         if (pointed.type == POINTEDTHING_NODE) {
3429                                 client->setHighlighted(pointed.node_undersurface, show_hud);
3430                         } else {
3431                                 client->setHighlighted(pointed.node_undersurface, false);
3432                         }
3433                 }
3434         }
3435
3436         /*
3437                 Stop digging when
3438                 - releasing left mouse button
3439                 - pointing away from node
3440         */
3441         if (runData->digging) {
3442                 if (input->getLeftReleased()) {
3443                         infostream << "Left button released"
3444                                    << " (stopped digging)" << std::endl;
3445                         runData->digging = false;
3446                 } else if (pointed != runData->pointed_old) {
3447                         if (pointed.type == POINTEDTHING_NODE
3448                                         && runData->pointed_old.type == POINTEDTHING_NODE
3449                                         && pointed.node_undersurface
3450                                                         == runData->pointed_old.node_undersurface) {
3451                                 // Still pointing to the same node, but a different face.
3452                                 // Don't reset.
3453                         } else {
3454                                 infostream << "Pointing away from node"
3455                                            << " (stopped digging)" << std::endl;
3456                                 runData->digging = false;
3457                         }
3458                 }
3459
3460                 if (!runData->digging) {
3461                         client->interact(1, runData->pointed_old);
3462                         client->setCrack(-1, v3s16(0, 0, 0));
3463                         runData->dig_time = 0.0;
3464                 }
3465         }
3466
3467         if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3468                 runData->ldown_for_dig = false;
3469         }
3470
3471         runData->left_punch = false;
3472
3473         soundmaker->m_player_leftpunch_sound.name = "";
3474
3475         if (input->getRightState())
3476                 runData->repeat_rightclick_timer += dtime;
3477         else
3478                 runData->repeat_rightclick_timer = 0;
3479
3480         if (playeritem_def.usable && input->getLeftState()) {
3481                 if (input->getLeftClicked())
3482                         client->interact(4, pointed);
3483         } else if (pointed.type == POINTEDTHING_NODE) {
3484                 ToolCapabilities playeritem_toolcap =
3485                                 playeritem.getToolCapabilities(itemdef_manager);
3486                 handlePointingAtNode(runData, pointed, playeritem_def,
3487                                 playeritem_toolcap, dtime);
3488         } else if (pointed.type == POINTEDTHING_OBJECT) {
3489                 handlePointingAtObject(runData, pointed, playeritem,
3490                                 player_position, show_debug);
3491         } else if (input->getLeftState()) {
3492                 // When button is held down in air, show continuous animation
3493                 runData->left_punch = true;
3494         }
3495
3496         runData->pointed_old = pointed;
3497
3498         if (runData->left_punch || input->getLeftClicked())
3499                 camera->setDigging(0); // left click animation
3500
3501         input->resetLeftClicked();
3502         input->resetRightClicked();
3503
3504         input->resetLeftReleased();
3505         input->resetRightReleased();
3506 }
3507
3508
3509 void Game::handlePointingAtNode(GameRunData *runData,
3510                 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3511                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3512 {
3513         v3s16 nodepos = pointed.node_undersurface;
3514         v3s16 neighbourpos = pointed.node_abovesurface;
3515
3516         /*
3517                 Check information text of node
3518         */
3519
3520         ClientMap &map = client->getEnv().getClientMap();
3521         NodeMetadata *meta = map.getNodeMetadata(nodepos);
3522
3523         if (meta) {
3524                 infotext = narrow_to_wide(meta->getString("infotext"));
3525         } else {
3526                 MapNode n = map.getNodeNoEx(nodepos);
3527
3528                 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3529                         infotext = L"Unknown node: ";
3530                         infotext += narrow_to_wide(nodedef_manager->get(n).name);
3531                 }
3532         }
3533
3534         if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3535                         && client->checkPrivilege("interact")) {
3536                 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3537         }
3538
3539         if ((input->getRightClicked() ||
3540                         runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3541                         client->checkPrivilege("interact")) {
3542                 runData->repeat_rightclick_timer = 0;
3543                 infostream << "Ground right-clicked" << std::endl;
3544
3545                 if (meta && meta->getString("formspec") != "" && !random_input
3546                                 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3547                         infostream << "Launching custom inventory view" << std::endl;
3548
3549                         InventoryLocation inventoryloc;
3550                         inventoryloc.setNodeMeta(nodepos);
3551
3552                         NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3553                                 &client->getEnv().getClientMap(), nodepos);
3554                         TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3555
3556                         create_formspec_menu(&current_formspec, client, gamedef,
3557                                              texture_src, device, fs_src, txt_dst, client);
3558
3559                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3560                 } else {
3561                         // Report right click to server
3562
3563                         camera->setDigging(1);  // right click animation (always shown for feedback)
3564
3565                         // If the wielded item has node placement prediction,
3566                         // make that happen
3567                         bool placed = nodePlacementPrediction(*client,
3568                                         playeritem_def,
3569                                         nodepos, neighbourpos);
3570
3571                         if (placed) {
3572                                 // Report to server
3573                                 client->interact(3, pointed);
3574                                 // Read the sound
3575                                 soundmaker->m_player_rightpunch_sound =
3576                                                 playeritem_def.sound_place;
3577                         } else {
3578                                 soundmaker->m_player_rightpunch_sound =
3579                                                 SimpleSoundSpec();
3580                         }
3581
3582                         if (playeritem_def.node_placement_prediction == "" ||
3583                                         nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3584                                 client->interact(3, pointed); // Report to server
3585                 }
3586         }
3587 }
3588
3589
3590 void Game::handlePointingAtObject(GameRunData *runData,
3591                 const PointedThing &pointed,
3592                 const ItemStack &playeritem,
3593                 const v3f &player_position,
3594                 bool show_debug)
3595 {
3596         infotext = narrow_to_wide(runData->selected_object->infoText());
3597
3598         if (infotext == L"" && show_debug) {
3599                 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3600         }
3601
3602         if (input->getLeftState()) {
3603                 bool do_punch = false;
3604                 bool do_punch_damage = false;
3605
3606                 if (runData->object_hit_delay_timer <= 0.0) {
3607                         do_punch = true;
3608                         do_punch_damage = true;
3609                         runData->object_hit_delay_timer = object_hit_delay;
3610                 }
3611
3612                 if (input->getLeftClicked())
3613                         do_punch = true;
3614
3615                 if (do_punch) {
3616                         infostream << "Left-clicked object" << std::endl;
3617                         runData->left_punch = true;
3618                 }
3619
3620                 if (do_punch_damage) {
3621                         // Report direct punch
3622                         v3f objpos = runData->selected_object->getPosition();
3623                         v3f dir = (objpos - player_position).normalize();
3624
3625                         bool disable_send = runData->selected_object->directReportPunch(
3626                                         dir, &playeritem, runData->time_from_last_punch);
3627                         runData->time_from_last_punch = 0;
3628
3629                         if (!disable_send)
3630                                 client->interact(0, pointed);
3631                 }
3632         } else if (input->getRightClicked()) {
3633                 infostream << "Right-clicked object" << std::endl;
3634                 client->interact(3, pointed);  // place
3635         }
3636 }
3637
3638
3639 void Game::handleDigging(GameRunData *runData,
3640                 const PointedThing &pointed, const v3s16 &nodepos,
3641                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3642 {
3643         if (!runData->digging) {
3644                 infostream << "Started digging" << std::endl;
3645                 client->interact(0, pointed);
3646                 runData->digging = true;
3647                 runData->ldown_for_dig = true;
3648         }
3649
3650         LocalPlayer *player = client->getEnv().getLocalPlayer();
3651         ClientMap &map = client->getEnv().getClientMap();
3652         MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3653
3654         // NOTE: Similar piece of code exists on the server side for
3655         // cheat detection.
3656         // Get digging parameters
3657         DigParams params = getDigParams(nodedef_manager->get(n).groups,
3658                         &playeritem_toolcap);
3659
3660         // If can't dig, try hand
3661         if (!params.diggable) {
3662                 const ItemDefinition &hand = itemdef_manager->get("");
3663                 const ToolCapabilities *tp = hand.tool_capabilities;
3664
3665                 if (tp)
3666                         params = getDigParams(nodedef_manager->get(n).groups, tp);
3667         }
3668
3669         if (params.diggable == false) {
3670                 // I guess nobody will wait for this long
3671                 runData->dig_time_complete = 10000000.0;
3672         } else {
3673                 runData->dig_time_complete = params.time;
3674
3675                 if (m_cache_enable_particles) {
3676                         const ContentFeatures &features =
3677                                         client->getNodeDefManager()->get(n);
3678                         client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3679                                         player, nodepos, features.tiles);
3680                 }
3681         }
3682
3683         if (runData->dig_time_complete >= 0.001) {
3684                 runData->dig_index = (float)crack_animation_length
3685                                 * runData->dig_time
3686                                 / runData->dig_time_complete;
3687         } else {
3688                 // This is for torches
3689                 runData->dig_index = crack_animation_length;
3690         }
3691
3692         SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3693
3694         if (sound_dig.exists() && params.diggable) {
3695                 if (sound_dig.name == "__group") {
3696                         if (params.main_group != "") {
3697                                 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3698                                 soundmaker->m_player_leftpunch_sound.name =
3699                                                 std::string("default_dig_") +
3700                                                 params.main_group;
3701                         }
3702                 } else {
3703                         soundmaker->m_player_leftpunch_sound = sound_dig;
3704                 }
3705         }
3706
3707         // Don't show cracks if not diggable
3708         if (runData->dig_time_complete >= 100000.0) {
3709         } else if (runData->dig_index < crack_animation_length) {
3710                 //TimeTaker timer("client.setTempMod");
3711                 //infostream<<"dig_index="<<dig_index<<std::endl;
3712                 client->setCrack(runData->dig_index, nodepos);
3713         } else {
3714                 infostream << "Digging completed" << std::endl;
3715                 client->interact(2, pointed);
3716                 client->setCrack(-1, v3s16(0, 0, 0));
3717                 bool is_valid_position;
3718                 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3719                 if (is_valid_position)
3720                         client->removeNode(nodepos);
3721
3722                 if (m_cache_enable_particles) {
3723                         const ContentFeatures &features =
3724                                 client->getNodeDefManager()->get(wasnode);
3725                         client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3726                                         player, nodepos, features.tiles);
3727                 }
3728
3729                 runData->dig_time = 0;
3730                 runData->digging = false;
3731
3732                 runData->nodig_delay_timer =
3733                                 runData->dig_time_complete / (float)crack_animation_length;
3734
3735                 // We don't want a corresponding delay to
3736                 // very time consuming nodes
3737                 if (runData->nodig_delay_timer > 0.3)
3738                         runData->nodig_delay_timer = 0.3;
3739
3740                 // We want a slight delay to very little
3741                 // time consuming nodes
3742                 const float mindelay = 0.15;
3743
3744                 if (runData->nodig_delay_timer < mindelay)
3745                         runData->nodig_delay_timer = mindelay;
3746
3747                 // Send event to trigger sound
3748                 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3749                 gamedef->event()->put(e);
3750         }
3751
3752         if (runData->dig_time_complete < 100000.0) {
3753                 runData->dig_time += dtime;
3754         } else {
3755                 runData->dig_time = 0;
3756                 client->setCrack(-1, nodepos);
3757         }
3758
3759         camera->setDigging(0);  // left click animation
3760 }
3761
3762
3763 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3764                 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3765                 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3766 {
3767         LocalPlayer *player = client->getEnv().getLocalPlayer();
3768
3769         /*
3770                 Fog range
3771         */
3772
3773         if (draw_control->range_all) {
3774                 runData->fog_range = 100000 * BS;
3775         } else {
3776                 runData->fog_range = draw_control->wanted_range * BS
3777                                 + 0.0 * MAP_BLOCKSIZE * BS;
3778                 runData->fog_range = MYMIN(
3779                                 runData->fog_range,
3780                                 (draw_control->farthest_drawn + 20) * BS);
3781                 runData->fog_range *= 0.9;
3782         }
3783
3784         /*
3785                 Calculate general brightness
3786         */
3787         u32 daynight_ratio = client->getEnv().getDayNightRatio();
3788         float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3789         float direct_brightness;
3790         bool sunlight_seen;
3791
3792         if (g_settings->getBool("free_move")) {
3793                 direct_brightness = time_brightness;
3794                 sunlight_seen = true;
3795         } else {
3796                 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3797                 float old_brightness = sky->getBrightness();
3798                 direct_brightness = client->getEnv().getClientMap()
3799                                 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3800                                         daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3801                                     / 255.0;
3802         }
3803
3804         float time_of_day = runData->time_of_day;
3805         float time_of_day_smooth = runData->time_of_day_smooth;
3806
3807         time_of_day = client->getEnv().getTimeOfDayF();
3808
3809         const float maxsm = 0.05;
3810         const float todsm = 0.05;
3811
3812         if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3813                         fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3814                         fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3815                 time_of_day_smooth = time_of_day;
3816
3817         if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3818                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3819                                 + (time_of_day + 1.0) * todsm;
3820         else
3821                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3822                                 + time_of_day * todsm;
3823
3824         runData->time_of_day = time_of_day;
3825         runData->time_of_day_smooth = time_of_day_smooth;
3826
3827         sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3828                         sunlight_seen, camera->getCameraMode(), player->getYaw(),
3829                         player->getPitch());
3830
3831         /*
3832                 Update clouds
3833         */
3834         if (clouds) {
3835                 v3f player_position = player->getPosition();
3836                 if (sky->getCloudsVisible()) {
3837                         clouds->setVisible(true);
3838                         clouds->step(dtime);
3839                         clouds->update(v2f(player_position.X, player_position.Z),
3840                                        sky->getCloudColor());
3841                 } else {
3842                         clouds->setVisible(false);
3843                 }
3844         }
3845
3846         /*
3847                 Update particles
3848         */
3849         client->getParticleManager()->step(dtime);
3850
3851         /*
3852                 Fog
3853         */
3854
3855         if (m_cache_enable_fog && !flags.force_fog_off) {
3856                 driver->setFog(
3857                                 sky->getBgColor(),
3858                                 video::EFT_FOG_LINEAR,
3859                                 runData->fog_range * 0.4,
3860                                 runData->fog_range * 1.0,
3861                                 0.01,
3862                                 false, // pixel fog
3863                                 false // range fog
3864                 );
3865         } else {
3866                 driver->setFog(
3867                                 sky->getBgColor(),
3868                                 video::EFT_FOG_LINEAR,
3869                                 100000 * BS,
3870                                 110000 * BS,
3871                                 0.01,
3872                                 false, // pixel fog
3873                                 false // range fog
3874                 );
3875         }
3876
3877         /*
3878                 Get chat messages from client
3879         */
3880
3881         v2u32 screensize = driver->getScreenSize();
3882
3883         updateChat(*client, dtime, flags.show_debug, screensize,
3884                         flags.show_chat, runData->profiler_current_page,
3885                         *chat_backend, guitext_chat);
3886
3887         /*
3888                 Inventory
3889         */
3890
3891         if (client->getPlayerItem() != runData->new_playeritem)
3892                 client->selectPlayerItem(runData->new_playeritem);
3893
3894         // Update local inventory if it has changed
3895         if (client->getLocalInventoryUpdated()) {
3896                 //infostream<<"Updating local inventory"<<std::endl;
3897                 client->getLocalInventory(*local_inventory);
3898                 runData->update_wielded_item_trigger = true;
3899         }
3900
3901         if (runData->update_wielded_item_trigger) {
3902                 // Update wielded tool
3903                 InventoryList *mlist = local_inventory->getList("main");
3904
3905                 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3906                         ItemStack item = mlist->getItem(client->getPlayerItem());
3907                         camera->wield(item);
3908                 }
3909                 runData->update_wielded_item_trigger = false;
3910         }
3911
3912         /*
3913                 Update block draw list every 200ms or when camera direction has
3914                 changed much
3915         */
3916         runData->update_draw_list_timer += dtime;
3917
3918         v3f camera_direction = camera->getDirection();
3919         if (runData->update_draw_list_timer >= 0.2
3920                         || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3921                         || flags.camera_offset_changed) {
3922                 runData->update_draw_list_timer = 0;
3923                 client->getEnv().getClientMap().updateDrawList(driver);
3924                 runData->update_draw_list_last_cam_dir = camera_direction;
3925         }
3926
3927         updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3928
3929         /*
3930            make sure menu is on top
3931            1. Delete formspec menu reference if menu was removed
3932            2. Else, make sure formspec menu is on top
3933         */
3934         if (current_formspec) {
3935                 if (current_formspec->getReferenceCount() == 1) {
3936                         current_formspec->drop();
3937                         current_formspec = NULL;
3938                 } else if (!noMenuActive()) {
3939                         guiroot->bringToFront(current_formspec);
3940                 }
3941         }
3942
3943         /*
3944                 Drawing begins
3945         */
3946
3947         video::SColor skycolor = sky->getSkyColor();
3948
3949         TimeTaker tt_draw("mainloop: draw");
3950         {
3951                 TimeTaker timer("beginScene");
3952                 driver->beginScene(true, true, skycolor);
3953                 stats->beginscenetime = timer.stop(true);
3954         }
3955
3956         draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3957                         highlight_boxes, screensize, skycolor, flags.show_hud);
3958
3959         /*
3960                 Profiler graph
3961         */
3962         if (flags.show_profiler_graph)
3963                 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3964
3965         /*
3966                 Damage flash
3967         */
3968         if (runData->damage_flash > 0.0) {
3969                 video::SColor color(std::min(runData->damage_flash, 180.0f),
3970                                 180,
3971                                 0,
3972                                 0);
3973                 driver->draw2DRectangle(color,
3974                                         core::rect<s32>(0, 0, screensize.X, screensize.Y),
3975                                         NULL);
3976
3977                 runData->damage_flash -= 100.0 * dtime;
3978         }
3979
3980         /*
3981                 Damage camera tilt
3982         */
3983         if (player->hurt_tilt_timer > 0.0) {
3984                 player->hurt_tilt_timer -= dtime * 5;
3985
3986                 if (player->hurt_tilt_timer < 0)
3987                         player->hurt_tilt_strength = 0;
3988         }
3989
3990         /*
3991                 End scene
3992         */
3993         {
3994                 TimeTaker timer("endScene");
3995                 driver->endScene();
3996                 stats->endscenetime = timer.stop(true);
3997         }
3998
3999         stats->drawtime = tt_draw.stop(true);
4000         g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4001 }
4002
4003
4004 inline static const char *yawToDirectionString(int yaw)
4005 {
4006         // NOTE: TODO: This can be done mathematically without the else/else-if
4007         // cascade.
4008
4009         const char *player_direction;
4010
4011         yaw = wrapDegrees_0_360(yaw);
4012
4013         if (yaw >= 45 && yaw < 135)
4014                 player_direction = "West [-X]";
4015         else if (yaw >= 135 && yaw < 225)
4016                 player_direction = "South [-Z]";
4017         else if (yaw >= 225 && yaw < 315)
4018                 player_direction = "East [+X]";
4019         else
4020                 player_direction = "North [+Z]";
4021
4022         return player_direction;
4023 }
4024
4025
4026 void Game::updateGui(float *statustext_time, const RunStats &stats,
4027                 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4028                 const CameraOrientation &cam)
4029 {
4030         v2u32 screensize = driver->getScreenSize();
4031         LocalPlayer *player = client->getEnv().getLocalPlayer();
4032         v3f player_position = player->getPosition();
4033
4034         if (flags.show_debug) {
4035                 static float drawtime_avg = 0;
4036                 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4037
4038                 u16 fps = 1.0 / stats.dtime_jitter.avg;
4039                 //s32 fps = driver->getFPS();
4040
4041                 std::ostringstream os(std::ios_base::binary);
4042                 os << std::fixed
4043                    << PROJECT_NAME_C " " << g_version_hash
4044                    << " FPS = " << fps
4045                    << " (R: range_all=" << draw_control->range_all << ")"
4046                    << std::setprecision(0)
4047                    << " drawtime = " << drawtime_avg
4048                    << std::setprecision(1)
4049                    << ", dtime_jitter = "
4050                    << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4051                    << std::setprecision(1)
4052                    << ", v_range = " << draw_control->wanted_range
4053                    << std::setprecision(3)
4054                    << ", RTT = " << client->getRTT();
4055                 guitext->setText(narrow_to_wide(os.str()).c_str());
4056                 guitext->setVisible(true);
4057         } else if (flags.show_hud || flags.show_chat) {
4058                 std::ostringstream os(std::ios_base::binary);
4059                 os << PROJECT_NAME_C " " << g_version_hash;
4060                 guitext->setText(narrow_to_wide(os.str()).c_str());
4061                 guitext->setVisible(true);
4062         } else {
4063                 guitext->setVisible(false);
4064         }
4065
4066         if (guitext->isVisible()) {
4067                 core::rect<s32> rect(
4068                                 5,              5,
4069                                 screensize.X,   5 + g_fontengine->getTextHeight()
4070                 );
4071                 guitext->setRelativePosition(rect);
4072         }
4073
4074         if (flags.show_debug) {
4075                 std::ostringstream os(std::ios_base::binary);
4076                 os << std::setprecision(1) << std::fixed
4077                    << "(" << (player_position.X / BS)
4078                    << ", " << (player_position.Y / BS)
4079                    << ", " << (player_position.Z / BS)
4080                    << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4081                    << " " << yawToDirectionString(cam.camera_yaw)
4082                    << ") (seed = " << ((u64)client->getMapSeed())
4083                    << ")";
4084
4085                 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4086                         ClientMap &map = client->getEnv().getClientMap();
4087                         const INodeDefManager *nodedef = client->getNodeDefManager();
4088                         MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4089                         if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4090                                 const ContentFeatures &features = nodedef->get(n);
4091                                 os << " (pointing_at = " << nodedef->get(n).name
4092                                    << " - " << features.tiledef[0].name.c_str()
4093                                    << ")";
4094                         }
4095                 }
4096
4097                 guitext2->setText(narrow_to_wide(os.str()).c_str());
4098                 guitext2->setVisible(true);
4099
4100                 core::rect<s32> rect(
4101                                 5,             5 + g_fontengine->getTextHeight(),
4102                                 screensize.X,  5 + g_fontengine->getTextHeight() * 2
4103                 );
4104                 guitext2->setRelativePosition(rect);
4105         } else {
4106                 guitext2->setVisible(false);
4107         }
4108
4109         guitext_info->setText(infotext.c_str());
4110         guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4111
4112         float statustext_time_max = 1.5;
4113
4114         if (!statustext.empty()) {
4115                 *statustext_time += dtime;
4116
4117                 if (*statustext_time >= statustext_time_max) {
4118                         statustext = L"";
4119                         *statustext_time = 0;
4120                 }
4121         }
4122
4123         guitext_status->setText(statustext.c_str());
4124         guitext_status->setVisible(!statustext.empty());
4125
4126         if (!statustext.empty()) {
4127                 s32 status_width  = guitext_status->getTextWidth();
4128                 s32 status_height = guitext_status->getTextHeight();
4129                 s32 status_y = screensize.Y - 150;
4130                 s32 status_x = (screensize.X - status_width) / 2;
4131                 core::rect<s32> rect(
4132                                 status_x , status_y - status_height,
4133                                 status_x + status_width, status_y
4134                 );
4135                 guitext_status->setRelativePosition(rect);
4136
4137                 // Fade out
4138                 video::SColor initial_color(255, 0, 0, 0);
4139
4140                 if (guienv->getSkin())
4141                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4142
4143                 video::SColor final_color = initial_color;
4144                 final_color.setAlpha(0);
4145                 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4146                                 initial_color, final_color,
4147                                 pow(*statustext_time / statustext_time_max, 2.0f));
4148                 guitext_status->setOverrideColor(fade_color);
4149                 guitext_status->enableOverrideColor(true);
4150         }
4151 }
4152
4153
4154 /* Log times and stuff for visualization */
4155 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4156 {
4157         Profiler::GraphValues values;
4158         g_profiler->graphGet(values);
4159         graph->put(values);
4160 }
4161
4162
4163
4164 /****************************************************************************
4165  Misc
4166  ****************************************************************************/
4167
4168 /* On some computers framerate doesn't seem to be automatically limited
4169  */
4170 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4171 {
4172         // not using getRealTime is necessary for wine
4173         device->getTimer()->tick(); // Maker sure device time is up-to-date
4174         u32 time = device->getTimer()->getTime();
4175         u32 last_time = fps_timings->last_time;
4176
4177         if (time > last_time)  // Make sure time hasn't overflowed
4178                 fps_timings->busy_time = time - last_time;
4179         else
4180                 fps_timings->busy_time = 0;
4181
4182         u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4183                         ? g_settings->getFloat("pause_fps_max")
4184                         : g_settings->getFloat("fps_max"));
4185
4186         if (fps_timings->busy_time < frametime_min) {
4187                 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4188                 device->sleep(fps_timings->sleep_time);
4189         } else {
4190                 fps_timings->sleep_time = 0;
4191         }
4192
4193         /* Get the new value of the device timer. Note that device->sleep() may
4194          * not sleep for the entire requested time as sleep may be interrupted and
4195          * therefore it is arguably more accurate to get the new time from the
4196          * device rather than calculating it by adding sleep_time to time.
4197          */
4198
4199         device->getTimer()->tick(); // Update device timer
4200         time = device->getTimer()->getTime();
4201
4202         if (time > last_time)  // Make sure last_time hasn't overflowed
4203                 *dtime = (time - last_time) / 1000.0;
4204         else
4205                 *dtime = 0;
4206
4207         fps_timings->last_time = time;
4208 }
4209
4210 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4211 // pass a copy of it to this function
4212 // Note: \p msg must be allocated using new (not malloc())
4213 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4214                 int percent, bool draw_clouds)
4215 {
4216         draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4217         delete[] msg;
4218 }
4219
4220
4221 /****************************************************************************/
4222 /****************************************************************************
4223  Shutdown / cleanup
4224  ****************************************************************************/
4225 /****************************************************************************/
4226
4227 void Game::extendedResourceCleanup()
4228 {
4229         // Extended resource accounting
4230         infostream << "Irrlicht resources after cleanup:" << std::endl;
4231         infostream << "\tRemaining meshes   : "
4232                    << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4233         infostream << "\tRemaining textures : "
4234                    << driver->getTextureCount() << std::endl;
4235
4236         for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4237                 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4238                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4239                            << std::endl;
4240         }
4241
4242         clearTextureNameCache();
4243         infostream << "\tRemaining materials: "
4244                << driver-> getMaterialRendererCount()
4245                        << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4246 }
4247
4248
4249 /****************************************************************************/
4250 /****************************************************************************
4251  extern function for launching the game
4252  ****************************************************************************/
4253 /****************************************************************************/
4254
4255 void the_game(bool *kill,
4256                 bool random_input,
4257                 InputHandler *input,
4258                 IrrlichtDevice *device,
4259
4260                 const std::string &map_dir,
4261                 const std::string &playername,
4262                 const std::string &password,
4263                 const std::string &address,         // If empty local server is created
4264                 u16 port,
4265
4266                 std::string &error_message,
4267                 ChatBackend &chat_backend,
4268                 const SubgameSpec &gamespec,        // Used for local game
4269                 bool simple_singleplayer_mode)
4270 {
4271         Game game;
4272
4273         /* Make a copy of the server address because if a local singleplayer server
4274          * is created then this is updated and we don't want to change the value
4275          * passed to us by the calling function
4276          */
4277         std::string server_address = address;
4278
4279         try {
4280
4281                 if (game.startup(kill, random_input, input, device, map_dir,
4282                                 playername, password, &server_address, port,
4283                                 error_message, &chat_backend, gamespec,
4284                                 simple_singleplayer_mode)) {
4285                         game.run();
4286                         game.shutdown();
4287                 }
4288
4289         } catch (SerializationError &e) {
4290                 error_message = std::string("A serialization error occurred:\n")
4291                                 + e.what() + "\n\nThe server is probably "
4292                                 " running a different version of " PROJECT_NAME_C ".";
4293                 errorstream << error_message << std::endl;
4294         } catch (ServerError &e) {
4295                 error_message = e.what();
4296                 errorstream << "ServerError: " << error_message << std::endl;
4297         } catch (ModError &e) {
4298                 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4299                 errorstream << "ModError: " << error_message << std::endl;
4300         }
4301 }
4302