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