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