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