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