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