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