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