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