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