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