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