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