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