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