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