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