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