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