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