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