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