ed2673c7123cfb16d5366eba078866cddd6c8e4c
[oweals/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 + "testsounds";
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         f32  m_cache_mouse_sensitivity;
1745         f32  m_cache_joystick_frustum_sensitivity;
1746         f32  m_repeat_right_click_time;
1747
1748 #ifdef __ANDROID__
1749         bool m_cache_hold_aux1;
1750         bool m_android_chat_open;
1751 #endif
1752 };
1753
1754 Game::Game() :
1755         client(NULL),
1756         server(NULL),
1757         texture_src(NULL),
1758         shader_src(NULL),
1759         itemdef_manager(NULL),
1760         nodedef_manager(NULL),
1761         sound(NULL),
1762         sound_is_dummy(false),
1763         soundmaker(NULL),
1764         chat_backend(NULL),
1765         current_formspec(NULL),
1766         eventmgr(NULL),
1767         quicktune(NULL),
1768         gui_chat_console(NULL),
1769         draw_control(NULL),
1770         camera(NULL),
1771         clouds(NULL),
1772         sky(NULL),
1773         local_inventory(NULL),
1774         hud(NULL),
1775         mapper(NULL)
1776 {
1777         g_settings->registerChangedCallback("doubletap_jump",
1778                 &settingChangedCallback, this);
1779         g_settings->registerChangedCallback("enable_clouds",
1780                 &settingChangedCallback, this);
1781         g_settings->registerChangedCallback("doubletap_joysticks",
1782                 &settingChangedCallback, this);
1783         g_settings->registerChangedCallback("enable_particles",
1784                 &settingChangedCallback, this);
1785         g_settings->registerChangedCallback("enable_fog",
1786                 &settingChangedCallback, this);
1787         g_settings->registerChangedCallback("mouse_sensitivity",
1788                 &settingChangedCallback, this);
1789         g_settings->registerChangedCallback("joystick_frustum_sensitivity",
1790                 &settingChangedCallback, this);
1791         g_settings->registerChangedCallback("repeat_rightclick_time",
1792                 &settingChangedCallback, this);
1793
1794         readSettings();
1795
1796 #ifdef __ANDROID__
1797         m_cache_hold_aux1 = false;      // This is initialised properly later
1798 #endif
1799
1800 }
1801
1802
1803
1804 /****************************************************************************
1805  MinetestApp Public
1806  ****************************************************************************/
1807
1808 Game::~Game()
1809 {
1810         delete client;
1811         delete soundmaker;
1812         if (!sound_is_dummy)
1813                 delete sound;
1814
1815         delete server; // deleted first to stop all server threads
1816
1817         delete hud;
1818         delete local_inventory;
1819         delete camera;
1820         delete quicktune;
1821         delete eventmgr;
1822         delete texture_src;
1823         delete shader_src;
1824         delete nodedef_manager;
1825         delete itemdef_manager;
1826         delete draw_control;
1827
1828         extendedResourceCleanup();
1829
1830         g_settings->deregisterChangedCallback("doubletap_jump",
1831                 &settingChangedCallback, this);
1832         g_settings->deregisterChangedCallback("enable_clouds",
1833                 &settingChangedCallback, this);
1834         g_settings->deregisterChangedCallback("enable_particles",
1835                 &settingChangedCallback, this);
1836         g_settings->deregisterChangedCallback("enable_fog",
1837                 &settingChangedCallback, this);
1838         g_settings->deregisterChangedCallback("mouse_sensitivity",
1839                 &settingChangedCallback, this);
1840         g_settings->deregisterChangedCallback("repeat_rightclick_time",
1841                 &settingChangedCallback, this);
1842 }
1843
1844 bool Game::startup(bool *kill,
1845                 bool random_input,
1846                 InputHandler *input,
1847                 IrrlichtDevice *device,
1848                 const std::string &map_dir,
1849                 const std::string &playername,
1850                 const std::string &password,
1851                 std::string *address,     // can change if simple_singleplayer_mode
1852                 u16 port,
1853                 std::string &error_message,
1854                 bool *reconnect,
1855                 ChatBackend *chat_backend,
1856                 const SubgameSpec &gamespec,
1857                 bool simple_singleplayer_mode)
1858 {
1859         // "cache"
1860         this->device              = device;
1861         this->kill                = kill;
1862         this->error_message       = &error_message;
1863         this->reconnect_requested = reconnect;
1864         this->random_input        = random_input;
1865         this->input               = input;
1866         this->chat_backend        = chat_backend;
1867         this->simple_singleplayer_mode = simple_singleplayer_mode;
1868
1869         keycache.handler = input;
1870         keycache.populate();
1871
1872         driver              = device->getVideoDriver();
1873         smgr                = device->getSceneManager();
1874
1875         smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1876
1877         if (!init(map_dir, address, port, gamespec))
1878                 return false;
1879
1880         if (!createClient(playername, password, address, port))
1881                 return false;
1882
1883         return true;
1884 }
1885
1886
1887 void Game::run()
1888 {
1889         ProfilerGraph graph;
1890         RunStats stats              = { 0 };
1891         CameraOrientation cam_view_target  = { 0 };
1892         CameraOrientation cam_view  = { 0 };
1893         GameRunData runData         = { 0 };
1894         FpsControl draw_times       = { 0 };
1895         VolatileRunFlags flags      = { 0 };
1896         f32 dtime; // in seconds
1897
1898         runData.time_from_last_punch  = 10.0;
1899         runData.profiler_max_page = 3;
1900         runData.update_wielded_item_trigger = true;
1901
1902         flags.show_chat = true;
1903         flags.show_hud = true;
1904         flags.show_minimap = g_settings->getBool("enable_minimap");
1905         flags.show_debug = g_settings->getBool("show_debug");
1906         flags.invert_mouse = g_settings->getBool("invert_mouse");
1907         flags.first_loop_after_window_activation = true;
1908
1909         /* Clear the profiler */
1910         Profiler::GraphValues dummyvalues;
1911         g_profiler->graphGet(dummyvalues);
1912
1913         draw_times.last_time = device->getTimer()->getTime();
1914
1915         shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1916                         sky,
1917                         &flags.force_fog_off,
1918                         &runData.fog_range,
1919                         client));
1920
1921         set_light_table(g_settings->getFloat("display_gamma"));
1922
1923 #ifdef __ANDROID__
1924         m_cache_hold_aux1 = g_settings->getBool("fast_move")
1925                         && client->checkPrivilege("fast");
1926 #endif
1927
1928         while (device->run()
1929                         && !(*kill || g_gamecallback->shutdown_requested
1930                         || (server && server->getShutdownRequested()))) {
1931
1932                 /* Must be called immediately after a device->run() call because it
1933                  * uses device->getTimer()->getTime()
1934                  */
1935                 limitFps(&draw_times, &dtime);
1936
1937                 updateStats(&stats, draw_times, dtime);
1938                 updateInteractTimers(&runData, dtime);
1939
1940                 if (!checkConnection())
1941                         break;
1942                 if (!handleCallbacks())
1943                         break;
1944
1945                 processQueues();
1946
1947                 infotext = L"";
1948                 hud->resizeHotbar();
1949
1950                 updateProfilers(runData, stats, draw_times, dtime);
1951                 processUserInput(&flags, &runData, dtime);
1952                 // Update camera before player movement to avoid camera lag of one frame
1953                 updateCameraDirection(&cam_view_target, &flags, dtime);
1954                 float cam_smoothing = 0;
1955                 if (g_settings->getBool("cinematic"))
1956                         cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1957                 else
1958                         cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1959                 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1960                 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1961                                 cam_view.camera_yaw) * cam_smoothing;
1962                 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1963                                 cam_view.camera_pitch) * cam_smoothing;
1964                 updatePlayerControl(cam_view);
1965                 step(&dtime);
1966                 processClientEvents(&cam_view_target, &runData.damage_flash);
1967                 updateCamera(&flags, draw_times.busy_time, dtime,
1968                                 runData.time_from_last_punch);
1969                 updateSound(dtime);
1970                 processPlayerInteraction(&runData, dtime, flags.show_hud,
1971                                 flags.show_debug);
1972                 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1973                 updateProfilerGraphs(&graph);
1974
1975                 // Update if minimap has been disabled by the server
1976                 flags.show_minimap &= !client->isMinimapDisabledByServer();
1977         }
1978 }
1979
1980
1981 void Game::shutdown()
1982 {
1983         if (g_settings->get("3d_mode") == "pageflip") {
1984                 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1985         }
1986
1987         showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1988
1989         if (clouds)
1990                 clouds->drop();
1991
1992         if (gui_chat_console)
1993                 gui_chat_console->drop();
1994
1995         if (sky)
1996                 sky->drop();
1997
1998         /* cleanup menus */
1999         while (g_menumgr.menuCount() > 0) {
2000                 g_menumgr.m_stack.front()->setVisible(false);
2001                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
2002         }
2003
2004         if (current_formspec) {
2005                 current_formspec->drop();
2006                 current_formspec = NULL;
2007         }
2008
2009         chat_backend->addMessage(L"", L"# Disconnected.");
2010         chat_backend->addMessage(L"", L"");
2011
2012         if (client) {
2013                 client->Stop();
2014                 while (!client->isShutdown()) {
2015                         assert(texture_src != NULL);
2016                         assert(shader_src != NULL);
2017                         texture_src->processQueue();
2018                         shader_src->processQueue();
2019                         sleep_ms(100);
2020                 }
2021         }
2022 }
2023
2024
2025 /****************************************************************************/
2026 /****************************************************************************
2027  Startup
2028  ****************************************************************************/
2029 /****************************************************************************/
2030
2031 bool Game::init(
2032                 const std::string &map_dir,
2033                 std::string *address,
2034                 u16 port,
2035                 const SubgameSpec &gamespec)
2036 {
2037         showOverlayMessage(wgettext("Loading..."), 0, 0);
2038
2039         texture_src = createTextureSource(device);
2040         shader_src = createShaderSource(device);
2041
2042         itemdef_manager = createItemDefManager();
2043         nodedef_manager = createNodeDefManager();
2044
2045         eventmgr = new EventManager();
2046         quicktune = new QuicktuneShortcutter();
2047
2048         if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2049                         && eventmgr && quicktune))
2050                 return false;
2051
2052         if (!initSound())
2053                 return false;
2054
2055         // Create a server if not connecting to an existing one
2056         if (*address == "") {
2057                 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2058                         return false;
2059         }
2060
2061         return true;
2062 }
2063
2064 bool Game::initSound()
2065 {
2066 #if USE_SOUND
2067         if (g_settings->getBool("enable_sound")) {
2068                 infostream << "Attempting to use OpenAL audio" << std::endl;
2069                 sound = createOpenALSoundManager(&soundfetcher);
2070                 if (!sound)
2071                         infostream << "Failed to initialize OpenAL audio" << std::endl;
2072         } else
2073                 infostream << "Sound disabled." << std::endl;
2074 #endif
2075
2076         if (!sound) {
2077                 infostream << "Using dummy audio." << std::endl;
2078                 sound = &dummySoundManager;
2079                 sound_is_dummy = true;
2080         }
2081
2082         soundmaker = new SoundMaker(sound, nodedef_manager);
2083         if (!soundmaker)
2084                 return false;
2085
2086         soundmaker->registerReceiver(eventmgr);
2087
2088         return true;
2089 }
2090
2091 bool Game::createSingleplayerServer(const std::string map_dir,
2092                 const SubgameSpec &gamespec, u16 port, std::string *address)
2093 {
2094         showOverlayMessage(wgettext("Creating server..."), 0, 5);
2095
2096         std::string bind_str = g_settings->get("bind_address");
2097         Address bind_addr(0, 0, 0, 0, port);
2098
2099         if (g_settings->getBool("ipv6_server")) {
2100                 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2101         }
2102
2103         try {
2104                 bind_addr.Resolve(bind_str.c_str());
2105         } catch (ResolveError &e) {
2106                 infostream << "Resolving bind address \"" << bind_str
2107                            << "\" failed: " << e.what()
2108                            << " -- Listening on all addresses." << std::endl;
2109         }
2110
2111         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2112                 *error_message = "Unable to listen on " +
2113                                 bind_addr.serializeString() +
2114                                 " because IPv6 is disabled";
2115                 errorstream << *error_message << std::endl;
2116                 return false;
2117         }
2118
2119         server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2120                             bind_addr.isIPv6());
2121
2122         server->start(bind_addr);
2123
2124         return true;
2125 }
2126
2127 bool Game::createClient(const std::string &playername,
2128                 const std::string &password, std::string *address, u16 port)
2129 {
2130         showOverlayMessage(wgettext("Creating client..."), 0, 10);
2131
2132         draw_control = new MapDrawControl;
2133         if (!draw_control)
2134                 return false;
2135
2136         bool could_connect, connect_aborted;
2137
2138         if (!connectToServer(playername, password, address, port,
2139                         &could_connect, &connect_aborted))
2140                 return false;
2141
2142         if (!could_connect) {
2143                 if (error_message->empty() && !connect_aborted) {
2144                         // Should not happen if error messages are set properly
2145                         *error_message = "Connection failed for unknown reason";
2146                         errorstream << *error_message << std::endl;
2147                 }
2148                 return false;
2149         }
2150
2151         if (!getServerContent(&connect_aborted)) {
2152                 if (error_message->empty() && !connect_aborted) {
2153                         // Should not happen if error messages are set properly
2154                         *error_message = "Connection failed for unknown reason";
2155                         errorstream << *error_message << std::endl;
2156                 }
2157                 return false;
2158         }
2159
2160         // Update cached textures, meshes and materials
2161         client->afterContentReceived(device);
2162
2163         /* Camera
2164          */
2165         camera = new Camera(smgr, *draw_control, gamedef);
2166         if (!camera || !camera->successfullyCreated(*error_message))
2167                 return false;
2168         client->setCamera(camera);
2169
2170         /* Clouds
2171          */
2172         if (m_cache_enable_clouds) {
2173                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2174                 if (!clouds) {
2175                         *error_message = "Memory allocation error (clouds)";
2176                         errorstream << *error_message << std::endl;
2177                         return false;
2178                 }
2179         }
2180
2181         /* Skybox
2182          */
2183         sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2184         skybox = NULL;  // This is used/set later on in the main run loop
2185
2186         local_inventory = new Inventory(itemdef_manager);
2187
2188         if (!(sky && local_inventory)) {
2189                 *error_message = "Memory allocation error (sky or local inventory)";
2190                 errorstream << *error_message << std::endl;
2191                 return false;
2192         }
2193
2194         /* Pre-calculated values
2195          */
2196         video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2197         if (t) {
2198                 v2u32 size = t->getOriginalSize();
2199                 crack_animation_length = size.Y / size.X;
2200         } else {
2201                 crack_animation_length = 5;
2202         }
2203
2204         if (!initGui())
2205                 return false;
2206
2207         /* Set window caption
2208          */
2209         std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2210         str += L" ";
2211         str += utf8_to_wide(g_version_hash);
2212         str += L" [";
2213         str += driver->getName();
2214         str += L"]";
2215         device->setWindowCaption(str.c_str());
2216
2217         LocalPlayer *player = client->getEnv().getLocalPlayer();
2218         player->hurt_tilt_timer = 0;
2219         player->hurt_tilt_strength = 0;
2220
2221         hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2222
2223         if (!hud) {
2224                 *error_message = "Memory error: could not create HUD";
2225                 errorstream << *error_message << std::endl;
2226                 return false;
2227         }
2228
2229         mapper = client->getMapper();
2230         mapper->setMinimapMode(MINIMAP_MODE_OFF);
2231
2232         return true;
2233 }
2234
2235 bool Game::initGui()
2236 {
2237         // First line of debug text
2238         guitext = addStaticText(guienv,
2239                         utf8_to_wide(PROJECT_NAME_C).c_str(),
2240                         core::rect<s32>(0, 0, 0, 0),
2241                         false, false, guiroot);
2242
2243         // Second line of debug text
2244         guitext2 = addStaticText(guienv,
2245                         L"",
2246                         core::rect<s32>(0, 0, 0, 0),
2247                         false, false, guiroot);
2248
2249         // At the middle of the screen
2250         // Object infos are shown in this
2251         guitext_info = addStaticText(guienv,
2252                         L"",
2253                         core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2254                         false, true, guiroot);
2255
2256         // Status text (displays info when showing and hiding GUI stuff, etc.)
2257         guitext_status = addStaticText(guienv,
2258                         L"<Status>",
2259                         core::rect<s32>(0, 0, 0, 0),
2260                         false, false, guiroot);
2261         guitext_status->setVisible(false);
2262
2263         // Chat text
2264         guitext_chat = addStaticText(
2265                         guienv,
2266                         L"",
2267                         core::rect<s32>(0, 0, 0, 0),
2268                         //false, false); // Disable word wrap as of now
2269                         false, true, guiroot);
2270
2271         // Remove stale "recent" chat messages from previous connections
2272         chat_backend->clearRecentChat();
2273
2274         // Chat backend and console
2275         gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2276                         -1, chat_backend, client, &g_menumgr);
2277         if (!gui_chat_console) {
2278                 *error_message = "Could not allocate memory for chat console";
2279                 errorstream << *error_message << std::endl;
2280                 return false;
2281         }
2282
2283         // Profiler text (size is updated when text is updated)
2284         guitext_profiler = addStaticText(guienv,
2285                         L"<Profiler>",
2286                         core::rect<s32>(0, 0, 0, 0),
2287                         false, false, guiroot);
2288         guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2289         guitext_profiler->setVisible(false);
2290         guitext_profiler->setWordWrap(true);
2291
2292 #ifdef HAVE_TOUCHSCREENGUI
2293
2294         if (g_touchscreengui)
2295                 g_touchscreengui->init(texture_src);
2296
2297 #endif
2298
2299         return true;
2300 }
2301
2302 bool Game::connectToServer(const std::string &playername,
2303                 const std::string &password, std::string *address, u16 port,
2304                 bool *connect_ok, bool *aborted)
2305 {
2306         *connect_ok = false;    // Let's not be overly optimistic
2307         *aborted = false;
2308         bool local_server_mode = false;
2309
2310         showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2311
2312         Address connect_address(0, 0, 0, 0, port);
2313
2314         try {
2315                 connect_address.Resolve(address->c_str());
2316
2317                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2318                         //connect_address.Resolve("localhost");
2319                         if (connect_address.isIPv6()) {
2320                                 IPv6AddressBytes addr_bytes;
2321                                 addr_bytes.bytes[15] = 1;
2322                                 connect_address.setAddress(&addr_bytes);
2323                         } else {
2324                                 connect_address.setAddress(127, 0, 0, 1);
2325                         }
2326                         local_server_mode = true;
2327                 }
2328         } catch (ResolveError &e) {
2329                 *error_message = std::string("Couldn't resolve address: ") + e.what();
2330                 errorstream << *error_message << std::endl;
2331                 return false;
2332         }
2333
2334         if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2335                 *error_message = "Unable to connect to " +
2336                                 connect_address.serializeString() +
2337                                 " because IPv6 is disabled";
2338                 errorstream << *error_message << std::endl;
2339                 return false;
2340         }
2341
2342         client = new Client(device,
2343                         playername.c_str(), password,
2344                         *draw_control, texture_src, shader_src,
2345                         itemdef_manager, nodedef_manager, sound, eventmgr,
2346                         connect_address.isIPv6());
2347
2348         if (!client)
2349                 return false;
2350
2351         gamedef = client;       // Client acts as our GameDef
2352
2353         infostream << "Connecting to server at ";
2354         connect_address.print(&infostream);
2355         infostream << std::endl;
2356
2357         client->connect(connect_address, *address,
2358                 simple_singleplayer_mode || local_server_mode);
2359
2360         /*
2361                 Wait for server to accept connection
2362         */
2363
2364         try {
2365                 input->clear();
2366
2367                 FpsControl fps_control = { 0 };
2368                 f32 dtime;
2369                 f32 wait_time = 0; // in seconds
2370
2371                 fps_control.last_time = device->getTimer()->getTime();
2372
2373                 while (device->run()) {
2374
2375                         limitFps(&fps_control, &dtime);
2376
2377                         // Update client and server
2378                         client->step(dtime);
2379
2380                         if (server != NULL)
2381                                 server->step(dtime);
2382
2383                         // End condition
2384                         if (client->getState() == LC_Init) {
2385                                 *connect_ok = true;
2386                                 break;
2387                         }
2388
2389                         // Break conditions
2390                         if (client->accessDenied()) {
2391                                 *error_message = "Access denied. Reason: "
2392                                                 + client->accessDeniedReason();
2393                                 *reconnect_requested = client->reconnectRequested();
2394                                 errorstream << *error_message << std::endl;
2395                                 break;
2396                         }
2397
2398                         if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2399                                 *aborted = true;
2400                                 infostream << "Connect aborted [Escape]" << std::endl;
2401                                 break;
2402                         }
2403
2404                         wait_time += dtime;
2405                         // Only time out if we aren't waiting for the server we started
2406                         if ((*address != "") && (wait_time > 10)) {
2407                                 bool sent_old_init = g_settings->getFlag("send_pre_v25_init");
2408                                 // If no pre v25 init was sent, and no answer was received,
2409                                 // but the low level connection could be established
2410                                 // (meaning that we have a peer id), then we probably wanted
2411                                 // to connect to a legacy server. In this case, tell the user
2412                                 // to enable the option to be able to connect.
2413                                 if (!sent_old_init &&
2414                                                 (client->getProtoVersion() == 0) &&
2415                                                 client->connectedToServer()) {
2416                                         *error_message = "Connection failure: init packet not "
2417                                         "recognized by server.\n"
2418                                         "Most likely the server uses an old protocol version (<v25).\n"
2419                                         "Please ask the server owner to update to 0.4.13 or later.\n"
2420                                         "To still connect to the server in the meantime,\n"
2421                                         "you can enable the 'send_pre_v25_init' setting by editing minetest.conf,\n"
2422                                         "or by enabling the 'Client -> Network -> Support older Servers'\n"
2423                                         "entry in the advanced settings menu.";
2424                                 } else {
2425                                         *error_message = "Connection timed out.";
2426                                 }
2427                                 errorstream << *error_message << std::endl;
2428                                 break;
2429                         }
2430
2431                         // Update status
2432                         showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2433                 }
2434         } catch (con::PeerNotFoundException &e) {
2435                 // TODO: Should something be done here? At least an info/error
2436                 // message?
2437                 return false;
2438         }
2439
2440         return true;
2441 }
2442
2443 bool Game::getServerContent(bool *aborted)
2444 {
2445         input->clear();
2446
2447         FpsControl fps_control = { 0 };
2448         f32 dtime; // in seconds
2449
2450         fps_control.last_time = device->getTimer()->getTime();
2451
2452         while (device->run()) {
2453
2454                 limitFps(&fps_control, &dtime);
2455
2456                 // Update client and server
2457                 client->step(dtime);
2458
2459                 if (server != NULL)
2460                         server->step(dtime);
2461
2462                 // End condition
2463                 if (client->mediaReceived() && client->itemdefReceived() &&
2464                                 client->nodedefReceived()) {
2465                         break;
2466                 }
2467
2468                 // Error conditions
2469                 if (!checkConnection())
2470                         return false;
2471
2472                 if (client->getState() < LC_Init) {
2473                         *error_message = "Client disconnected";
2474                         errorstream << *error_message << std::endl;
2475                         return false;
2476                 }
2477
2478                 if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2479                         *aborted = true;
2480                         infostream << "Connect aborted [Escape]" << std::endl;
2481                         return false;
2482                 }
2483
2484                 // Display status
2485                 int progress = 25;
2486
2487                 if (!client->itemdefReceived()) {
2488                         const wchar_t *text = wgettext("Item definitions...");
2489                         progress = 25;
2490                         draw_load_screen(text, device, guienv, dtime, progress);
2491                         delete[] text;
2492                 } else if (!client->nodedefReceived()) {
2493                         const wchar_t *text = wgettext("Node definitions...");
2494                         progress = 30;
2495                         draw_load_screen(text, device, guienv, dtime, progress);
2496                         delete[] text;
2497                 } else {
2498                         std::stringstream message;
2499                         message.precision(3);
2500                         message << gettext("Media...");
2501
2502                         if ((USE_CURL == 0) ||
2503                                         (!g_settings->getBool("enable_remote_media_server"))) {
2504                                 float cur = client->getCurRate();
2505                                 std::string cur_unit = gettext("KiB/s");
2506
2507                                 if (cur > 900) {
2508                                         cur /= 1024.0;
2509                                         cur_unit = gettext("MiB/s");
2510                                 }
2511
2512                                 message << " (" << cur << ' ' << cur_unit << ")";
2513                         }
2514
2515                         progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2516                         draw_load_screen(utf8_to_wide(message.str()), device,
2517                                         guienv, dtime, progress);
2518                 }
2519         }
2520
2521         return true;
2522 }
2523
2524
2525 /****************************************************************************/
2526 /****************************************************************************
2527  Run
2528  ****************************************************************************/
2529 /****************************************************************************/
2530
2531 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2532 {
2533         if (runData->nodig_delay_timer >= 0)
2534                 runData->nodig_delay_timer -= dtime;
2535
2536         if (runData->object_hit_delay_timer >= 0)
2537                 runData->object_hit_delay_timer -= dtime;
2538
2539         runData->time_from_last_punch += dtime;
2540 }
2541
2542
2543 /* returns false if game should exit, otherwise true
2544  */
2545 inline bool Game::checkConnection()
2546 {
2547         if (client->accessDenied()) {
2548                 *error_message = "Access denied. Reason: "
2549                                 + client->accessDeniedReason();
2550                 *reconnect_requested = client->reconnectRequested();
2551                 errorstream << *error_message << std::endl;
2552                 return false;
2553         }
2554
2555         return true;
2556 }
2557
2558
2559 /* returns false if game should exit, otherwise true
2560  */
2561 inline bool Game::handleCallbacks()
2562 {
2563         if (g_gamecallback->disconnect_requested) {
2564                 g_gamecallback->disconnect_requested = false;
2565                 return false;
2566         }
2567
2568         if (g_gamecallback->changepassword_requested) {
2569                 (new GUIPasswordChange(guienv, guiroot, -1,
2570                                        &g_menumgr, client))->drop();
2571                 g_gamecallback->changepassword_requested = false;
2572         }
2573
2574         if (g_gamecallback->changevolume_requested) {
2575                 (new GUIVolumeChange(guienv, guiroot, -1,
2576                                      &g_menumgr))->drop();
2577                 g_gamecallback->changevolume_requested = false;
2578         }
2579
2580         if (g_gamecallback->keyconfig_requested) {
2581                 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2582                                       &g_menumgr))->drop();
2583                 g_gamecallback->keyconfig_requested = false;
2584         }
2585
2586         if (g_gamecallback->keyconfig_changed) {
2587                 keycache.populate(); // update the cache with new settings
2588                 g_gamecallback->keyconfig_changed = false;
2589         }
2590
2591         return true;
2592 }
2593
2594
2595 void Game::processQueues()
2596 {
2597         texture_src->processQueue();
2598         itemdef_manager->processQueue(gamedef);
2599         shader_src->processQueue();
2600 }
2601
2602
2603 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2604                 const FpsControl &draw_times, f32 dtime)
2605 {
2606         float profiler_print_interval =
2607                         g_settings->getFloat("profiler_print_interval");
2608         bool print_to_log = true;
2609
2610         if (profiler_print_interval == 0) {
2611                 print_to_log = false;
2612                 profiler_print_interval = 5;
2613         }
2614
2615         if (profiler_interval.step(dtime, profiler_print_interval)) {
2616                 if (print_to_log) {
2617                         infostream << "Profiler:" << std::endl;
2618                         g_profiler->print(infostream);
2619                 }
2620
2621                 update_profiler_gui(guitext_profiler, g_fontengine,
2622                                 runData.profiler_current_page, runData.profiler_max_page,
2623                                 driver->getScreenSize().Height);
2624
2625                 g_profiler->clear();
2626         }
2627
2628         addProfilerGraphs(stats, draw_times, dtime);
2629 }
2630
2631
2632 void Game::addProfilerGraphs(const RunStats &stats,
2633                 const FpsControl &draw_times, f32 dtime)
2634 {
2635         g_profiler->graphAdd("mainloop_other",
2636                         draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2637
2638         if (draw_times.sleep_time != 0)
2639                 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2640         g_profiler->graphAdd("mainloop_dtime", dtime);
2641
2642         g_profiler->add("Elapsed time", dtime);
2643         g_profiler->avg("FPS", 1. / dtime);
2644 }
2645
2646
2647 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2648                 f32 dtime)
2649 {
2650
2651         f32 jitter;
2652         Jitter *jp;
2653
2654         /* Time average and jitter calculation
2655          */
2656         jp = &stats->dtime_jitter;
2657         jp->avg = jp->avg * 0.96 + dtime * 0.04;
2658
2659         jitter = dtime - jp->avg;
2660
2661         if (jitter > jp->max)
2662                 jp->max = jitter;
2663
2664         jp->counter += dtime;
2665
2666         if (jp->counter > 0.0) {
2667                 jp->counter -= 3.0;
2668                 jp->max_sample = jp->max;
2669                 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2670                 jp->max = 0.0;
2671         }
2672
2673         /* Busytime average and jitter calculation
2674          */
2675         jp = &stats->busy_time_jitter;
2676         jp->avg = jp->avg + draw_times.busy_time * 0.02;
2677
2678         jitter = draw_times.busy_time - jp->avg;
2679
2680         if (jitter > jp->max)
2681                 jp->max = jitter;
2682         if (jitter < jp->min)
2683                 jp->min = jitter;
2684
2685         jp->counter += dtime;
2686
2687         if (jp->counter > 0.0) {
2688                 jp->counter -= 3.0;
2689                 jp->max_sample = jp->max;
2690                 jp->min_sample = jp->min;
2691                 jp->max = 0.0;
2692                 jp->min = 0.0;
2693         }
2694 }
2695
2696
2697
2698 /****************************************************************************
2699  Input handling
2700  ****************************************************************************/
2701
2702 void Game::processUserInput(VolatileRunFlags *flags,
2703                 GameRunData *runData, f32 dtime)
2704 {
2705         // Reset input if window not active or some menu is active
2706         if (device->isWindowActive() == false
2707                         || noMenuActive() == false
2708                         || guienv->hasFocus(gui_chat_console)) {
2709                 input->clear();
2710 #ifdef HAVE_TOUCHSCREENGUI
2711                 g_touchscreengui->hide();
2712 #endif
2713         }
2714 #ifdef HAVE_TOUCHSCREENGUI
2715         else if (g_touchscreengui) {
2716                 /* on touchscreengui step may generate own input events which ain't
2717                  * what we want in case we just did clear them */
2718                 g_touchscreengui->step(dtime);
2719         }
2720 #endif
2721
2722         if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2723                 gui_chat_console->closeConsoleAtOnce();
2724         }
2725
2726         // Input handler step() (used by the random input generator)
2727         input->step(dtime);
2728
2729 #ifdef __ANDROID__
2730         if (current_formspec != NULL)
2731                 current_formspec->getAndroidUIInput();
2732         else
2733                 handleAndroidChatInput();
2734 #endif
2735
2736         // Increase timer for double tap of "keymap_jump"
2737         if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2738                 runData->jump_timer += dtime;
2739
2740         processKeyInput(
2741                         flags,
2742                         &runData->statustext_time,
2743                         &runData->jump_timer,
2744                         &runData->reset_jump_timer,
2745                         &runData->profiler_current_page,
2746                         runData->profiler_max_page);
2747
2748         processItemSelection(&runData->new_playeritem);
2749 }
2750
2751
2752 void Game::processKeyInput(VolatileRunFlags *flags,
2753                 float *statustext_time,
2754                 float *jump_timer,
2755                 bool *reset_jump_timer,
2756                 u32 *profiler_current_page,
2757                 u32 profiler_max_page)
2758 {
2759
2760         //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2761
2762         if (wasKeyDown(KeyType::DROP)) {
2763                 dropSelectedItem();
2764         } else if (wasKeyDown(KeyType::AUTORUN)) {
2765                 toggleAutorun(statustext_time);
2766         } else if (wasKeyDown(KeyType::INVENTORY)) {
2767                 openInventory();
2768         } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
2769                 if (!gui_chat_console->isOpenInhibited()) {
2770                         show_pause_menu(&current_formspec, client, gamedef,
2771                                 texture_src, device, &input->joystick,
2772                                 simple_singleplayer_mode);
2773                 }
2774         } else if (wasKeyDown(KeyType::CHAT)) {
2775                 openConsole(0.2, L"");
2776         } else if (wasKeyDown(KeyType::CMD)) {
2777                 openConsole(0.2, L"/");
2778         } else if (wasKeyDown(KeyType::CONSOLE)) {
2779                 openConsole(1);
2780         } else if (wasKeyDown(KeyType::FREEMOVE)) {
2781                 toggleFreeMove(statustext_time);
2782         } else if (wasKeyDown(KeyType::JUMP)) {
2783                 toggleFreeMoveAlt(statustext_time, jump_timer);
2784                 *reset_jump_timer = true;
2785         } else if (wasKeyDown(KeyType::FASTMOVE)) {
2786                 toggleFast(statustext_time);
2787         } else if (wasKeyDown(KeyType::NOCLIP)) {
2788                 toggleNoClip(statustext_time);
2789         } else if (wasKeyDown(KeyType::CINEMATIC)) {
2790                 toggleCinematic(statustext_time);
2791         } else if (wasKeyDown(KeyType::SCREENSHOT)) {
2792                 client->makeScreenshot(device);
2793         } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
2794                 toggleHud(statustext_time, &flags->show_hud);
2795         } else if (wasKeyDown(KeyType::MINIMAP)) {
2796                 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2797                         isKeyDown(KeyType::SNEAK));
2798         } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
2799                 toggleChat(statustext_time, &flags->show_chat);
2800         } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
2801                 toggleFog(statustext_time, &flags->force_fog_off);
2802         } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
2803                 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2804         } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
2805                 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2806         } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
2807                 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2808         } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
2809                 increaseViewRange(statustext_time);
2810         } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
2811                 decreaseViewRange(statustext_time);
2812         } else if (wasKeyDown(KeyType::RANGESELECT)) {
2813                 toggleFullViewRange(statustext_time);
2814         } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
2815                 quicktune->next();
2816         } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
2817                 quicktune->prev();
2818         } else if (wasKeyDown(KeyType::QUICKTUNE_INC)) {
2819                 quicktune->inc();
2820         } else if (wasKeyDown(KeyType::QUICKTUNE_DEC)) {
2821                 quicktune->dec();
2822         } else if (wasKeyDown(KeyType::DEBUG_STACKS)) {
2823                 // Print debug stacks
2824                 dstream << "-----------------------------------------"
2825                         << std::endl;
2826                 dstream << "Printing debug stacks:" << std::endl;
2827                 dstream << "-----------------------------------------"
2828                         << std::endl;
2829                 debug_stacks_print();
2830         }
2831
2832         if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
2833                 *reset_jump_timer = false;
2834                 *jump_timer = 0.0;
2835         }
2836
2837         //tt.stop();
2838
2839         if (quicktune->hasMessage()) {
2840                 std::string msg = quicktune->getMessage();
2841                 statustext = utf8_to_wide(msg);
2842                 *statustext_time = 0;
2843         }
2844 }
2845
2846 void Game::processItemSelection(u16 *new_playeritem)
2847 {
2848         LocalPlayer *player = client->getEnv().getLocalPlayer();
2849
2850         /* Item selection using mouse wheel
2851          */
2852         *new_playeritem = client->getPlayerItem();
2853
2854         s32 wheel = input->getMouseWheel();
2855         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2856                     player->hud_hotbar_itemcount - 1);
2857
2858         s32 dir = wheel;
2859
2860         if (input->joystick.wasKeyDown(KeyType::SCROLL_DOWN)) {
2861                 dir = -1;
2862         }
2863
2864         if (input->joystick.wasKeyDown(KeyType::SCROLL_UP)) {
2865                 dir = 1;
2866         }
2867
2868         if (dir < 0)
2869                 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2870         else if (dir > 0)
2871                 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2872         // else dir == 0
2873
2874         /* Item selection using keyboard
2875          */
2876         for (u16 i = 0; i < 10; i++) {
2877                 static const KeyPress *item_keys[10] = {
2878                         NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2879                         NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2880                         NumberKey + 9, NumberKey + 0,
2881                 };
2882
2883                 if (input->wasKeyDown(*item_keys[i])) {
2884                         if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2885                                 *new_playeritem = i;
2886                                 infostream << "Selected item: " << new_playeritem << std::endl;
2887                         }
2888                         break;
2889                 }
2890         }
2891 }
2892
2893
2894 void Game::dropSelectedItem()
2895 {
2896         IDropAction *a = new IDropAction();
2897         a->count = 0;
2898         a->from_inv.setCurrentPlayer();
2899         a->from_list = "main";
2900         a->from_i = client->getPlayerItem();
2901         client->inventoryAction(a);
2902 }
2903
2904
2905 void Game::openInventory()
2906 {
2907         /*
2908          * Don't permit to open inventory is CAO or player doesn't exists.
2909          * This prevent showing an empty inventory at player load
2910          */
2911
2912         LocalPlayer *player = client->getEnv().getLocalPlayer();
2913         if (player == NULL || player->getCAO() == NULL)
2914                 return;
2915
2916         infostream << "the_game: " << "Launching inventory" << std::endl;
2917
2918         PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2919         TextDest *txt_dst = new TextDestPlayerInventory(client);
2920
2921         create_formspec_menu(&current_formspec, client, gamedef, texture_src,
2922                         device, &input->joystick, fs_src, txt_dst, client);
2923
2924         InventoryLocation inventoryloc;
2925         inventoryloc.setCurrentPlayer();
2926         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2927 }
2928
2929
2930 void Game::openConsole(float height, const wchar_t *line)
2931 {
2932 #ifdef __ANDROID__
2933         porting::showInputDialog(gettext("ok"), "", "", 2);
2934         m_android_chat_open = true;
2935 #else
2936         if (gui_chat_console->isOpenInhibited())
2937                 return;
2938         gui_chat_console->openConsole(height);
2939         if (line) {
2940                 gui_chat_console->setCloseOnEnter(true);
2941                 gui_chat_console->replaceAndAddToHistory(line);
2942         }
2943 #endif
2944 }
2945
2946 #ifdef __ANDROID__
2947 void Game::handleAndroidChatInput()
2948 {
2949         if (m_android_chat_open && porting::getInputDialogState() == 0) {
2950                 std::string text = porting::getInputDialogValue();
2951                 client->typeChatMessage(utf8_to_wide(text));
2952         }
2953 }
2954 #endif
2955
2956
2957 void Game::toggleFreeMove(float *statustext_time)
2958 {
2959         static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2960
2961         bool free_move = !g_settings->getBool("free_move");
2962         g_settings->set("free_move", bool_to_cstr(free_move));
2963
2964         *statustext_time = 0;
2965         statustext = msg[free_move];
2966         if (free_move && !client->checkPrivilege("fly"))
2967                 statustext += L" (note: no 'fly' privilege)";
2968 }
2969
2970
2971 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2972 {
2973         if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2974                 toggleFreeMove(statustext_time);
2975 }
2976
2977
2978 void Game::toggleFast(float *statustext_time)
2979 {
2980         static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2981         bool fast_move = !g_settings->getBool("fast_move");
2982         g_settings->set("fast_move", bool_to_cstr(fast_move));
2983
2984         *statustext_time = 0;
2985         statustext = msg[fast_move];
2986
2987         bool has_fast_privs = client->checkPrivilege("fast");
2988
2989         if (fast_move && !has_fast_privs)
2990                 statustext += L" (note: no 'fast' privilege)";
2991
2992 #ifdef __ANDROID__
2993         m_cache_hold_aux1 = fast_move && has_fast_privs;
2994 #endif
2995 }
2996
2997
2998 void Game::toggleNoClip(float *statustext_time)
2999 {
3000         static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
3001         bool noclip = !g_settings->getBool("noclip");
3002         g_settings->set("noclip", bool_to_cstr(noclip));
3003
3004         *statustext_time = 0;
3005         statustext = msg[noclip];
3006
3007         if (noclip && !client->checkPrivilege("noclip"))
3008                 statustext += L" (note: no 'noclip' privilege)";
3009 }
3010
3011 void Game::toggleCinematic(float *statustext_time)
3012 {
3013         static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
3014         bool cinematic = !g_settings->getBool("cinematic");
3015         g_settings->set("cinematic", bool_to_cstr(cinematic));
3016
3017         *statustext_time = 0;
3018         statustext = msg[cinematic];
3019 }
3020
3021 // Add WoW-style autorun by toggling continuous forward.
3022 void Game::toggleAutorun(float *statustext_time)
3023 {
3024         static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
3025         bool autorun_enabled = !g_settings->getBool("continuous_forward");
3026         g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
3027
3028         *statustext_time = 0;
3029         statustext = msg[autorun_enabled ? 1 : 0];
3030 }
3031
3032 void Game::toggleChat(float *statustext_time, bool *flag)
3033 {
3034         static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
3035
3036         *flag = !*flag;
3037         *statustext_time = 0;
3038         statustext = msg[*flag];
3039 }
3040
3041
3042 void Game::toggleHud(float *statustext_time, bool *flag)
3043 {
3044         static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
3045
3046         *flag = !*flag;
3047         *statustext_time = 0;
3048         statustext = msg[*flag];
3049 }
3050
3051 void Game::toggleMinimap(float *statustext_time, bool *flag,
3052         bool show_hud, bool shift_pressed)
3053 {
3054         if (!show_hud || !g_settings->getBool("enable_minimap"))
3055                 return;
3056
3057         if (shift_pressed) {
3058                 mapper->toggleMinimapShape();
3059                 return;
3060         }
3061
3062         u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
3063
3064         MinimapMode mode = MINIMAP_MODE_OFF;
3065         if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
3066                 mode = mapper->getMinimapMode();
3067                 mode = (MinimapMode)((int)mode + 1);
3068         }
3069
3070         *flag = true;
3071         switch (mode) {
3072                 case MINIMAP_MODE_SURFACEx1:
3073                         statustext = L"Minimap in surface mode, Zoom x1";
3074                         break;
3075                 case MINIMAP_MODE_SURFACEx2:
3076                         statustext = L"Minimap in surface mode, Zoom x2";
3077                         break;
3078                 case MINIMAP_MODE_SURFACEx4:
3079                         statustext = L"Minimap in surface mode, Zoom x4";
3080                         break;
3081                 case MINIMAP_MODE_RADARx1:
3082                         statustext = L"Minimap in radar mode, Zoom x1";
3083                         break;
3084                 case MINIMAP_MODE_RADARx2:
3085                         statustext = L"Minimap in radar mode, Zoom x2";
3086                         break;
3087                 case MINIMAP_MODE_RADARx4:
3088                         statustext = L"Minimap in radar mode, Zoom x4";
3089                         break;
3090                 default:
3091                         mode = MINIMAP_MODE_OFF;
3092                         *flag = false;
3093                         statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3094                                 L"Minimap hidden" : L"Minimap disabled by server";
3095         }
3096
3097         *statustext_time = 0;
3098         mapper->setMinimapMode(mode);
3099 }
3100
3101 void Game::toggleFog(float *statustext_time, bool *flag)
3102 {
3103         static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3104
3105         *flag = !*flag;
3106         *statustext_time = 0;
3107         statustext = msg[*flag];
3108 }
3109
3110
3111 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3112                 bool *show_profiler_graph)
3113 {
3114         // Initial / 3x toggle: Chat only
3115         // 1x toggle: Debug text with chat
3116         // 2x toggle: Debug text with profiler graph
3117         if (!*show_debug) {
3118                 *show_debug = true;
3119                 *show_profiler_graph = false;
3120                 statustext = L"Debug info shown";
3121         } else if (*show_profiler_graph) {
3122                 *show_debug = false;
3123                 *show_profiler_graph = false;
3124                 statustext = L"Debug info and profiler graph hidden";
3125         } else {
3126                 *show_profiler_graph = true;
3127                 statustext = L"Profiler graph shown";
3128         }
3129         *statustext_time = 0;
3130 }
3131
3132
3133 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3134 {
3135         static const wchar_t *msg[] = {
3136                 L"Camera update enabled",
3137                 L"Camera update disabled"
3138         };
3139
3140         *flag = !*flag;
3141         *statustext_time = 0;
3142         statustext = msg[*flag];
3143 }
3144
3145
3146 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3147                 u32 profiler_max_page)
3148 {
3149         *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3150
3151         // FIXME: This updates the profiler with incomplete values
3152         update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3153                         profiler_max_page, driver->getScreenSize().Height);
3154
3155         if (*profiler_current_page != 0) {
3156                 std::wstringstream sstr;
3157                 sstr << "Profiler shown (page " << *profiler_current_page
3158                      << " of " << profiler_max_page << ")";
3159                 statustext = sstr.str();
3160         } else {
3161                 statustext = L"Profiler hidden";
3162         }
3163         *statustext_time = 0;
3164 }
3165
3166
3167 void Game::increaseViewRange(float *statustext_time)
3168 {
3169         s16 range = g_settings->getS16("viewing_range");
3170         s16 range_new = range + 10;
3171         g_settings->set("viewing_range", itos(range_new));
3172         statustext = utf8_to_wide("Viewing range changed to "
3173                         + itos(range_new));
3174         *statustext_time = 0;
3175 }
3176
3177
3178 void Game::decreaseViewRange(float *statustext_time)
3179 {
3180         s16 range = g_settings->getS16("viewing_range");
3181         s16 range_new = range - 10;
3182
3183         if (range_new < 20)
3184                 range_new = 20;
3185
3186         g_settings->set("viewing_range", itos(range_new));
3187         statustext = utf8_to_wide("Viewing range changed to "
3188                         + itos(range_new));
3189         *statustext_time = 0;
3190 }
3191
3192
3193 void Game::toggleFullViewRange(float *statustext_time)
3194 {
3195         static const wchar_t *msg[] = {
3196                 L"Disabled full viewing range",
3197                 L"Enabled full viewing range"
3198         };
3199
3200         draw_control->range_all = !draw_control->range_all;
3201         infostream << msg[draw_control->range_all] << std::endl;
3202         statustext = msg[draw_control->range_all];
3203         *statustext_time = 0;
3204 }
3205
3206
3207 void Game::updateCameraDirection(CameraOrientation *cam,
3208                 VolatileRunFlags *flags, float dtime)
3209 {
3210         if ((device->isWindowActive() && noMenuActive()) || random_input) {
3211
3212 #ifndef __ANDROID__
3213                 if (!random_input) {
3214                         // Mac OSX gets upset if this is set every frame
3215                         if (device->getCursorControl()->isVisible())
3216                                 device->getCursorControl()->setVisible(false);
3217                 }
3218 #endif
3219
3220                 if (flags->first_loop_after_window_activation)
3221                         flags->first_loop_after_window_activation = false;
3222                 else
3223                         updateCameraOrientation(cam, *flags, dtime);
3224
3225                 input->setMousePos((driver->getScreenSize().Width / 2),
3226                                 (driver->getScreenSize().Height / 2));
3227         } else {
3228
3229 #ifndef ANDROID
3230                 // Mac OSX gets upset if this is set every frame
3231                 if (device->getCursorControl()->isVisible() == false)
3232                         device->getCursorControl()->setVisible(true);
3233 #endif
3234
3235                 if (!flags->first_loop_after_window_activation)
3236                         flags->first_loop_after_window_activation = true;
3237
3238         }
3239 }
3240
3241 void Game::updateCameraOrientation(CameraOrientation *cam,
3242                 const VolatileRunFlags &flags, float dtime)
3243 {
3244 #ifdef HAVE_TOUCHSCREENGUI
3245         if (g_touchscreengui) {
3246                 cam->camera_yaw   = g_touchscreengui->getYaw();
3247                 cam->camera_pitch = g_touchscreengui->getPitch();
3248         } else {
3249 #endif
3250
3251                 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3252                 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3253
3254                 if (flags.invert_mouse
3255                                 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3256                         dy = -dy;
3257                 }
3258
3259                 cam->camera_yaw   -= dx * m_cache_mouse_sensitivity;
3260                 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3261
3262 #ifdef HAVE_TOUCHSCREENGUI
3263         }
3264 #endif
3265
3266         if (m_cache_enable_joysticks) {
3267                 f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime;
3268                 cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) *
3269                         c;
3270                 cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) *
3271                         c;
3272         }
3273
3274         cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3275 }
3276
3277
3278 void Game::updatePlayerControl(const CameraOrientation &cam)
3279 {
3280         //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3281
3282         // DO NOT use the isKeyDown method for the forward, backward, left, right
3283         // buttons, as the code that uses the controls needs to be able to
3284         // distinguish between the two in order to know when to use joysticks.
3285
3286         PlayerControl control(
3287                 input->isKeyDown(keycache.key[KeyType::FORWARD]),
3288                 input->isKeyDown(keycache.key[KeyType::BACKWARD]),
3289                 input->isKeyDown(keycache.key[KeyType::LEFT]),
3290                 input->isKeyDown(keycache.key[KeyType::RIGHT]),
3291                 isKeyDown(KeyType::JUMP),
3292                 isKeyDown(KeyType::SPECIAL1),
3293                 isKeyDown(KeyType::SNEAK),
3294                 isKeyDown(KeyType::ZOOM),
3295                 isLeftPressed(),
3296                 isRightPressed(),
3297                 cam.camera_pitch,
3298                 cam.camera_yaw,
3299                 input->joystick.getAxisWithoutDead(JA_SIDEWARD_MOVE),
3300                 input->joystick.getAxisWithoutDead(JA_FORWARD_MOVE)
3301         );
3302
3303         u32 keypress_bits =
3304                         ( (u32)(isKeyDown(KeyType::FORWARD)                       & 0x1) << 0) |
3305                         ( (u32)(isKeyDown(KeyType::BACKWARD)                      & 0x1) << 1) |
3306                         ( (u32)(isKeyDown(KeyType::LEFT)                          & 0x1) << 2) |
3307                         ( (u32)(isKeyDown(KeyType::RIGHT)                         & 0x1) << 3) |
3308                         ( (u32)(isKeyDown(KeyType::JUMP)                          & 0x1) << 4) |
3309                         ( (u32)(isKeyDown(KeyType::SPECIAL1)                      & 0x1) << 5) |
3310                         ( (u32)(isKeyDown(KeyType::SNEAK)                         & 0x1) << 6) |
3311                         ( (u32)(isLeftPressed()                                   & 0x1) << 7) |
3312                         ( (u32)(isRightPressed()                                  & 0x1) << 8
3313                 );
3314
3315 #ifdef ANDROID
3316         /* For Android, simulate holding down AUX1 (fast move) if the user has
3317          * the fast_move setting toggled on. If there is an aux1 key defined for
3318          * Android then its meaning is inverted (i.e. holding aux1 means walk and
3319          * not fast)
3320          */
3321         if (m_cache_hold_aux1) {
3322                 control.aux1 = control.aux1 ^ true;
3323                 keypress_bits ^= ((u32)(1U << 5));
3324         }
3325 #endif
3326
3327         client->setPlayerControl(control);
3328         LocalPlayer *player = client->getEnv().getLocalPlayer();
3329         player->keyPressed = keypress_bits;
3330
3331         //tt.stop();
3332 }
3333
3334
3335 inline void Game::step(f32 *dtime)
3336 {
3337         bool can_be_and_is_paused =
3338                         (simple_singleplayer_mode && g_menumgr.pausesGame());
3339
3340         if (can_be_and_is_paused) {     // This is for a singleplayer server
3341                 *dtime = 0;             // No time passes
3342         } else {
3343                 if (server != NULL) {
3344                         //TimeTaker timer("server->step(dtime)");
3345                         server->step(*dtime);
3346                 }
3347
3348                 //TimeTaker timer("client.step(dtime)");
3349                 client->step(*dtime);
3350         }
3351 }
3352
3353
3354 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3355 {
3356         ClientEvent event = client->getClientEvent();
3357
3358         LocalPlayer *player = client->getEnv().getLocalPlayer();
3359
3360         for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3361
3362                 if (event.type == CE_PLAYER_DAMAGE &&
3363                                 client->getHP() != 0) {
3364                         //u16 damage = event.player_damage.amount;
3365                         //infostream<<"Player damage: "<<damage<<std::endl;
3366
3367                         *damage_flash += 100.0;
3368                         *damage_flash += 8.0 * event.player_damage.amount;
3369
3370                         player->hurt_tilt_timer = 1.5;
3371                         player->hurt_tilt_strength = event.player_damage.amount / 4;
3372                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3373
3374                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3375                         gamedef->event()->put(e);
3376                 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3377                         cam->camera_yaw = event.player_force_move.yaw;
3378                         cam->camera_pitch = event.player_force_move.pitch;
3379                 } else if (event.type == CE_DEATHSCREEN) {
3380                         show_deathscreen(&current_formspec, client, gamedef, texture_src,
3381                                 device, &input->joystick, client);
3382
3383                         chat_backend->addMessage(L"", L"You died.");
3384
3385                         /* Handle visualization */
3386                         *damage_flash = 0;
3387                         player->hurt_tilt_timer = 0;
3388                         player->hurt_tilt_strength = 0;
3389
3390                 } else if (event.type == CE_SHOW_FORMSPEC) {
3391                         FormspecFormSource *fs_src =
3392                                 new FormspecFormSource(*(event.show_formspec.formspec));
3393                         TextDestPlayerInventory *txt_dst =
3394                                 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3395
3396                         create_formspec_menu(&current_formspec, client, gamedef,
3397                                 texture_src, device, &input->joystick,
3398                                 fs_src, txt_dst, client);
3399
3400                         delete(event.show_formspec.formspec);
3401                         delete(event.show_formspec.formname);
3402                 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3403                                 (event.type == CE_ADD_PARTICLESPAWNER) ||
3404                                 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3405                         client->getParticleManager()->handleParticleEvent(&event, gamedef,
3406                                         smgr, player);
3407                 } else if (event.type == CE_HUDADD) {
3408                         u32 id = event.hudadd.id;
3409
3410                         LocalPlayer *player = client->getEnv().getLocalPlayer();
3411                         HudElement *e = player->getHud(id);
3412
3413                         if (e != NULL) {
3414                                 delete event.hudadd.pos;
3415                                 delete event.hudadd.name;
3416                                 delete event.hudadd.scale;
3417                                 delete event.hudadd.text;
3418                                 delete event.hudadd.align;
3419                                 delete event.hudadd.offset;
3420                                 delete event.hudadd.world_pos;
3421                                 delete event.hudadd.size;
3422                                 continue;
3423                         }
3424
3425                         e = new HudElement;
3426                         e->type   = (HudElementType)event.hudadd.type;
3427                         e->pos    = *event.hudadd.pos;
3428                         e->name   = *event.hudadd.name;
3429                         e->scale  = *event.hudadd.scale;
3430                         e->text   = *event.hudadd.text;
3431                         e->number = event.hudadd.number;
3432                         e->item   = event.hudadd.item;
3433                         e->dir    = event.hudadd.dir;
3434                         e->align  = *event.hudadd.align;
3435                         e->offset = *event.hudadd.offset;
3436                         e->world_pos = *event.hudadd.world_pos;
3437                         e->size = *event.hudadd.size;
3438
3439                         u32 new_id = player->addHud(e);
3440                         //if this isn't true our huds aren't consistent
3441                         sanity_check(new_id == id);
3442
3443                         delete event.hudadd.pos;
3444                         delete event.hudadd.name;
3445                         delete event.hudadd.scale;
3446                         delete event.hudadd.text;
3447                         delete event.hudadd.align;
3448                         delete event.hudadd.offset;
3449                         delete event.hudadd.world_pos;
3450                         delete event.hudadd.size;
3451                 } else if (event.type == CE_HUDRM) {
3452                         HudElement *e = player->removeHud(event.hudrm.id);
3453
3454                         if (e != NULL)
3455                                 delete(e);
3456                 } else if (event.type == CE_HUDCHANGE) {
3457                         u32 id = event.hudchange.id;
3458                         HudElement *e = player->getHud(id);
3459
3460                         if (e == NULL) {
3461                                 delete event.hudchange.v3fdata;
3462                                 delete event.hudchange.v2fdata;
3463                                 delete event.hudchange.sdata;
3464                                 delete event.hudchange.v2s32data;
3465                                 continue;
3466                         }
3467
3468                         switch (event.hudchange.stat) {
3469                         case HUD_STAT_POS:
3470                                 e->pos = *event.hudchange.v2fdata;
3471                                 break;
3472
3473                         case HUD_STAT_NAME:
3474                                 e->name = *event.hudchange.sdata;
3475                                 break;
3476
3477                         case HUD_STAT_SCALE:
3478                                 e->scale = *event.hudchange.v2fdata;
3479                                 break;
3480
3481                         case HUD_STAT_TEXT:
3482                                 e->text = *event.hudchange.sdata;
3483                                 break;
3484
3485                         case HUD_STAT_NUMBER:
3486                                 e->number = event.hudchange.data;
3487                                 break;
3488
3489                         case HUD_STAT_ITEM:
3490                                 e->item = event.hudchange.data;
3491                                 break;
3492
3493                         case HUD_STAT_DIR:
3494                                 e->dir = event.hudchange.data;
3495                                 break;
3496
3497                         case HUD_STAT_ALIGN:
3498                                 e->align = *event.hudchange.v2fdata;
3499                                 break;
3500
3501                         case HUD_STAT_OFFSET:
3502                                 e->offset = *event.hudchange.v2fdata;
3503                                 break;
3504
3505                         case HUD_STAT_WORLD_POS:
3506                                 e->world_pos = *event.hudchange.v3fdata;
3507                                 break;
3508
3509                         case HUD_STAT_SIZE:
3510                                 e->size = *event.hudchange.v2s32data;
3511                                 break;
3512                         }
3513
3514                         delete event.hudchange.v3fdata;
3515                         delete event.hudchange.v2fdata;
3516                         delete event.hudchange.sdata;
3517                         delete event.hudchange.v2s32data;
3518                 } else if (event.type == CE_SET_SKY) {
3519                         sky->setVisible(false);
3520
3521                         if (skybox) {
3522                                 skybox->remove();
3523                                 skybox = NULL;
3524                         }
3525
3526                         // Handle according to type
3527                         if (*event.set_sky.type == "regular") {
3528                                 sky->setVisible(true);
3529                         } else if (*event.set_sky.type == "skybox" &&
3530                                         event.set_sky.params->size() == 6) {
3531                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3532                                 skybox = smgr->addSkyBoxSceneNode(
3533                                                  texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3534                                                  texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3535                                                  texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3536                                                  texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3537                                                  texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3538                                                  texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3539                         }
3540                         // Handle everything else as plain color
3541                         else {
3542                                 if (*event.set_sky.type != "plain")
3543                                         infostream << "Unknown sky type: "
3544                                                    << (*event.set_sky.type) << std::endl;
3545
3546                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3547                         }
3548
3549                         delete event.set_sky.bgcolor;
3550                         delete event.set_sky.type;
3551                         delete event.set_sky.params;
3552                 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3553                         bool enable = event.override_day_night_ratio.do_override;
3554                         u32 value = event.override_day_night_ratio.ratio_f * 1000;
3555                         client->getEnv().setDayNightRatioOverride(enable, value);
3556                 }
3557         }
3558 }
3559
3560
3561 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3562                 f32 dtime, float time_from_last_punch)
3563 {
3564         LocalPlayer *player = client->getEnv().getLocalPlayer();
3565
3566         /*
3567                 For interaction purposes, get info about the held item
3568                 - What item is it?
3569                 - Is it a usable item?
3570                 - Can it point to liquids?
3571         */
3572         ItemStack playeritem;
3573         {
3574                 InventoryList *mlist = local_inventory->getList("main");
3575
3576                 if (mlist && client->getPlayerItem() < mlist->getSize())
3577                         playeritem = mlist->getItem(client->getPlayerItem());
3578         }
3579
3580         ToolCapabilities playeritem_toolcap =
3581                 playeritem.getToolCapabilities(itemdef_manager);
3582
3583         v3s16 old_camera_offset = camera->getOffset();
3584
3585         if (wasKeyDown(KeyType::CAMERA_MODE)) {
3586                 GenericCAO *playercao = player->getCAO();
3587
3588                 // If playercao not loaded, don't change camera
3589                 if (playercao == NULL)
3590                         return;
3591
3592                 camera->toggleCameraMode();
3593
3594                 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3595                 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3596         }
3597
3598         float full_punch_interval = playeritem_toolcap.full_punch_interval;
3599         float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3600
3601         tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3602         camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3603                       client->getEnv());
3604         camera->step(dtime);
3605
3606         v3f camera_position = camera->getPosition();
3607         v3f camera_direction = camera->getDirection();
3608         f32 camera_fov = camera->getFovMax();
3609         v3s16 camera_offset = camera->getOffset();
3610
3611         flags->camera_offset_changed = (camera_offset != old_camera_offset);
3612
3613         if (!flags->disable_camera_update) {
3614                 client->getEnv().getClientMap().updateCamera(camera_position,
3615                                 camera_direction, camera_fov, camera_offset);
3616
3617                 if (flags->camera_offset_changed) {
3618                         client->updateCameraOffset(camera_offset);
3619                         client->getEnv().updateCameraOffset(camera_offset);
3620
3621                         if (clouds)
3622                                 clouds->updateCameraOffset(camera_offset);
3623                 }
3624         }
3625 }
3626
3627
3628 void Game::updateSound(f32 dtime)
3629 {
3630         // Update sound listener
3631         v3s16 camera_offset = camera->getOffset();
3632         sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3633                               v3f(0, 0, 0), // velocity
3634                               camera->getDirection(),
3635                               camera->getCameraNode()->getUpVector());
3636         sound->setListenerGain(g_settings->getFloat("sound_volume"));
3637
3638
3639         //      Update sound maker
3640         soundmaker->step(dtime);
3641
3642         LocalPlayer *player = client->getEnv().getLocalPlayer();
3643
3644         ClientMap &map = client->getEnv().getClientMap();
3645         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3646         soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3647 }
3648
3649
3650 void Game::processPlayerInteraction(GameRunData *runData,
3651                 f32 dtime, bool show_hud, bool show_debug)
3652 {
3653         LocalPlayer *player = client->getEnv().getLocalPlayer();
3654
3655         ItemStack playeritem;
3656         {
3657                 InventoryList *mlist = local_inventory->getList("main");
3658
3659                 if (mlist && client->getPlayerItem() < mlist->getSize())
3660                         playeritem = mlist->getItem(client->getPlayerItem());
3661         }
3662
3663         const ItemDefinition &playeritem_def =
3664                         playeritem.getDefinition(itemdef_manager);
3665
3666         v3f player_position  = player->getPosition();
3667         v3f camera_position  = camera->getPosition();
3668         v3f camera_direction = camera->getDirection();
3669         v3s16 camera_offset  = camera->getOffset();
3670
3671
3672         /*
3673                 Calculate what block is the crosshair pointing to
3674         */
3675
3676         f32 d = playeritem_def.range; // max. distance
3677         f32 d_hand = itemdef_manager->get("").range;
3678
3679         if (d < 0 && d_hand >= 0)
3680                 d = d_hand;
3681         else if (d < 0)
3682                 d = 4.0;
3683
3684         core::line3d<f32> shootline;
3685
3686         if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3687
3688                 shootline = core::line3d<f32>(camera_position,
3689                                                 camera_position + camera_direction * BS * (d + 1));
3690
3691         } else {
3692             // prevent player pointing anything in front-view
3693                 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3694                         shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3695         }
3696
3697 #ifdef HAVE_TOUCHSCREENGUI
3698
3699         if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3700                 shootline = g_touchscreengui->getShootline();
3701                 shootline.start += intToFloat(camera_offset, BS);
3702                 shootline.end += intToFloat(camera_offset, BS);
3703         }
3704
3705 #endif
3706
3707         PointedThing pointed = getPointedThing(
3708                         // input
3709                         client, hud, player_position, camera_direction,
3710                         camera_position, shootline, d,
3711                         playeritem_def.liquids_pointable,
3712                         !runData->ldown_for_dig,
3713                         camera_offset,
3714                         // output
3715                         runData->selected_object);
3716
3717         if (pointed != runData->pointed_old) {
3718                 infostream << "Pointing at " << pointed.dump() << std::endl;
3719                 hud->updateSelectionMesh(camera_offset);
3720         }
3721
3722         /*
3723                 Stop digging when
3724                 - releasing left mouse button
3725                 - pointing away from node
3726         */
3727         if (runData->digging) {
3728                 if (getLeftReleased()) {
3729                         infostream << "Left button released"
3730                                    << " (stopped digging)" << std::endl;
3731                         runData->digging = false;
3732                 } else if (pointed != runData->pointed_old) {
3733                         if (pointed.type == POINTEDTHING_NODE
3734                                         && runData->pointed_old.type == POINTEDTHING_NODE
3735                                         && pointed.node_undersurface
3736                                                         == runData->pointed_old.node_undersurface) {
3737                                 // Still pointing to the same node, but a different face.
3738                                 // Don't reset.
3739                         } else {
3740                                 infostream << "Pointing away from node"
3741                                            << " (stopped digging)" << std::endl;
3742                                 runData->digging = false;
3743                                 hud->updateSelectionMesh(camera_offset);
3744                         }
3745                 }
3746
3747                 if (!runData->digging) {
3748                         client->interact(1, runData->pointed_old);
3749                         client->setCrack(-1, v3s16(0, 0, 0));
3750                         runData->dig_time = 0.0;
3751                 }
3752         }
3753
3754         if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
3755                 runData->ldown_for_dig = false;
3756         }
3757
3758         runData->left_punch = false;
3759
3760         soundmaker->m_player_leftpunch_sound.name = "";
3761
3762         if (isRightPressed())
3763                 runData->repeat_rightclick_timer += dtime;
3764         else
3765                 runData->repeat_rightclick_timer = 0;
3766
3767         if (playeritem_def.usable && isLeftPressed()) {
3768                 if (getLeftClicked())
3769                         client->interact(4, pointed);
3770         } else if (pointed.type == POINTEDTHING_NODE) {
3771                 ToolCapabilities playeritem_toolcap =
3772                                 playeritem.getToolCapabilities(itemdef_manager);
3773                 handlePointingAtNode(runData, pointed, playeritem_def,
3774                                 playeritem_toolcap, dtime);
3775         } else if (pointed.type == POINTEDTHING_OBJECT) {
3776                 handlePointingAtObject(runData, pointed, playeritem,
3777                                 player_position, show_debug);
3778         } else if (isLeftPressed()) {
3779                 // When button is held down in air, show continuous animation
3780                 runData->left_punch = true;
3781         } else if (getRightClicked()) {
3782                 handlePointingAtNothing(runData, playeritem);
3783         }
3784
3785         runData->pointed_old = pointed;
3786
3787         if (runData->left_punch || getLeftClicked())
3788                 camera->setDigging(0); // left click animation
3789
3790         input->resetLeftClicked();
3791         input->resetRightClicked();
3792
3793         input->joystick.clearWasKeyDown(KeyType::MOUSE_L);
3794         input->joystick.clearWasKeyDown(KeyType::MOUSE_R);
3795
3796         input->resetLeftReleased();
3797         input->resetRightReleased();
3798
3799         input->joystick.clearWasKeyReleased(KeyType::MOUSE_L);
3800         input->joystick.clearWasKeyReleased(KeyType::MOUSE_R);
3801 }
3802
3803
3804 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3805 {
3806         infostream << "Right Clicked in Air" << std::endl;
3807         PointedThing fauxPointed;
3808         fauxPointed.type = POINTEDTHING_NOTHING;
3809         client->interact(5, fauxPointed);
3810 }
3811
3812
3813 void Game::handlePointingAtNode(GameRunData *runData,
3814                 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3815                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3816 {
3817         v3s16 nodepos = pointed.node_undersurface;
3818         v3s16 neighbourpos = pointed.node_abovesurface;
3819
3820         /*
3821                 Check information text of node
3822         */
3823
3824         ClientMap &map = client->getEnv().getClientMap();
3825         NodeMetadata *meta = map.getNodeMetadata(nodepos);
3826
3827         if (meta) {
3828                 infotext = unescape_enriched(utf8_to_wide(meta->getString("infotext")));
3829         } else {
3830                 MapNode n = map.getNodeNoEx(nodepos);
3831
3832                 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3833                         infotext = L"Unknown node: ";
3834                         infotext += utf8_to_wide(nodedef_manager->get(n).name);
3835                 }
3836         }
3837
3838         if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
3839                         && client->checkPrivilege("interact")) {
3840                 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3841         }
3842
3843         if ((getRightClicked() ||
3844                         runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3845                         client->checkPrivilege("interact")) {
3846                 runData->repeat_rightclick_timer = 0;
3847                 infostream << "Ground right-clicked" << std::endl;
3848
3849                 if (meta && meta->getString("formspec") != "" && !random_input
3850                                 && !isKeyDown(KeyType::SNEAK)) {
3851                         infostream << "Launching custom inventory view" << std::endl;
3852
3853                         InventoryLocation inventoryloc;
3854                         inventoryloc.setNodeMeta(nodepos);
3855
3856                         NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3857                                 &client->getEnv().getClientMap(), nodepos);
3858                         TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3859
3860                         create_formspec_menu(&current_formspec, client, gamedef,
3861                                 texture_src, device, &input->joystick, fs_src, txt_dst, client);
3862
3863                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3864                 } else {
3865                         // Report right click to server
3866
3867                         camera->setDigging(1);  // right click animation (always shown for feedback)
3868
3869                         // If the wielded item has node placement prediction,
3870                         // make that happen
3871                         bool placed = nodePlacementPrediction(*client,
3872                                         playeritem_def,
3873                                         nodepos, neighbourpos);
3874
3875                         if (placed) {
3876                                 // Report to server
3877                                 client->interact(3, pointed);
3878                                 // Read the sound
3879                                 soundmaker->m_player_rightpunch_sound =
3880                                                 playeritem_def.sound_place;
3881                         } else {
3882                                 soundmaker->m_player_rightpunch_sound =
3883                                                 SimpleSoundSpec();
3884
3885                                 if (playeritem_def.node_placement_prediction == "" ||
3886                                                 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3887                                         client->interact(3, pointed); // Report to server
3888                                 } else {
3889                                         soundmaker->m_player_rightpunch_sound =
3890                                                 playeritem_def.sound_place_failed;
3891                                 }
3892                         }
3893                 }
3894         }
3895 }
3896
3897
3898 void Game::handlePointingAtObject(GameRunData *runData,
3899                 const PointedThing &pointed,
3900                 const ItemStack &playeritem,
3901                 const v3f &player_position,
3902                 bool show_debug)
3903 {
3904         infotext = unescape_enriched(
3905                 utf8_to_wide(runData->selected_object->infoText()));
3906
3907         if (show_debug) {
3908                 if (infotext != L"") {
3909                         infotext += L"\n";
3910                 }
3911                 infotext += unescape_enriched(utf8_to_wide(
3912                         runData->selected_object->debugInfoText()));
3913         }
3914
3915         if (isLeftPressed()) {
3916                 bool do_punch = false;
3917                 bool do_punch_damage = false;
3918
3919                 if (runData->object_hit_delay_timer <= 0.0) {
3920                         do_punch = true;
3921                         do_punch_damage = true;
3922                         runData->object_hit_delay_timer = object_hit_delay;
3923                 }
3924
3925                 if (getLeftClicked())
3926                         do_punch = true;
3927
3928                 if (do_punch) {
3929                         infostream << "Left-clicked object" << std::endl;
3930                         runData->left_punch = true;
3931                 }
3932
3933                 if (do_punch_damage) {
3934                         // Report direct punch
3935                         v3f objpos = runData->selected_object->getPosition();
3936                         v3f dir = (objpos - player_position).normalize();
3937
3938                         bool disable_send = runData->selected_object->directReportPunch(
3939                                         dir, &playeritem, runData->time_from_last_punch);
3940                         runData->time_from_last_punch = 0;
3941
3942                         if (!disable_send)
3943                                 client->interact(0, pointed);
3944                 }
3945         } else if (getRightClicked()) {
3946                 infostream << "Right-clicked object" << std::endl;
3947                 client->interact(3, pointed);  // place
3948         }
3949 }
3950
3951
3952 void Game::handleDigging(GameRunData *runData,
3953                 const PointedThing &pointed, const v3s16 &nodepos,
3954                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3955 {
3956         if (!runData->digging) {
3957                 infostream << "Started digging" << std::endl;
3958                 client->interact(0, pointed);
3959                 runData->digging = true;
3960                 runData->ldown_for_dig = true;
3961         }
3962
3963         LocalPlayer *player = client->getEnv().getLocalPlayer();
3964         ClientMap &map = client->getEnv().getClientMap();
3965         MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3966
3967         // NOTE: Similar piece of code exists on the server side for
3968         // cheat detection.
3969         // Get digging parameters
3970         DigParams params = getDigParams(nodedef_manager->get(n).groups,
3971                         &playeritem_toolcap);
3972
3973         // If can't dig, try hand
3974         if (!params.diggable) {
3975                 const ItemDefinition &hand = itemdef_manager->get("");
3976                 const ToolCapabilities *tp = hand.tool_capabilities;
3977
3978                 if (tp)
3979                         params = getDigParams(nodedef_manager->get(n).groups, tp);
3980         }
3981
3982         if (params.diggable == false) {
3983                 // I guess nobody will wait for this long
3984                 runData->dig_time_complete = 10000000.0;
3985         } else {
3986                 runData->dig_time_complete = params.time;
3987
3988                 if (m_cache_enable_particles) {
3989                         const ContentFeatures &features =
3990                                         client->getNodeDefManager()->get(n);
3991                         client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3992                                         player, nodepos, features.tiles);
3993                 }
3994         }
3995
3996         if (runData->dig_time_complete >= 0.001) {
3997                 runData->dig_index = (float)crack_animation_length
3998                                 * runData->dig_time
3999                                 / runData->dig_time_complete;
4000         } else {
4001                 // This is for torches
4002                 runData->dig_index = crack_animation_length;
4003         }
4004
4005         SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
4006
4007         if (sound_dig.exists() && params.diggable) {
4008                 if (sound_dig.name == "__group") {
4009                         if (params.main_group != "") {
4010                                 soundmaker->m_player_leftpunch_sound.gain = 0.5;
4011                                 soundmaker->m_player_leftpunch_sound.name =
4012                                                 std::string("default_dig_") +
4013                                                 params.main_group;
4014                         }
4015                 } else {
4016                         soundmaker->m_player_leftpunch_sound = sound_dig;
4017                 }
4018         }
4019
4020         // Don't show cracks if not diggable
4021         if (runData->dig_time_complete >= 100000.0) {
4022         } else if (runData->dig_index < crack_animation_length) {
4023                 //TimeTaker timer("client.setTempMod");
4024                 //infostream<<"dig_index="<<dig_index<<std::endl;
4025                 client->setCrack(runData->dig_index, nodepos);
4026         } else {
4027                 infostream << "Digging completed" << std::endl;
4028                 client->interact(2, pointed);
4029                 client->setCrack(-1, v3s16(0, 0, 0));
4030                 bool is_valid_position;
4031                 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
4032                 if (is_valid_position)
4033                         client->removeNode(nodepos);
4034
4035                 if (m_cache_enable_particles) {
4036                         const ContentFeatures &features =
4037                                 client->getNodeDefManager()->get(wasnode);
4038                         client->getParticleManager()->addDiggingParticles(gamedef, smgr,
4039                                         player, nodepos, features.tiles);
4040                 }
4041
4042                 runData->dig_time = 0;
4043                 runData->digging = false;
4044
4045                 runData->nodig_delay_timer =
4046                                 runData->dig_time_complete / (float)crack_animation_length;
4047
4048                 // We don't want a corresponding delay to
4049                 // very time consuming nodes
4050                 if (runData->nodig_delay_timer > 0.3)
4051                         runData->nodig_delay_timer = 0.3;
4052
4053                 // We want a slight delay to very little
4054                 // time consuming nodes
4055                 const float mindelay = 0.15;
4056
4057                 if (runData->nodig_delay_timer < mindelay)
4058                         runData->nodig_delay_timer = mindelay;
4059
4060                 // Send event to trigger sound
4061                 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
4062                 gamedef->event()->put(e);
4063         }
4064
4065         if (runData->dig_time_complete < 100000.0) {
4066                 runData->dig_time += dtime;
4067         } else {
4068                 runData->dig_time = 0;
4069                 client->setCrack(-1, nodepos);
4070         }
4071
4072         camera->setDigging(0);  // left click animation
4073 }
4074
4075
4076 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
4077                 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
4078                 const CameraOrientation &cam)
4079 {
4080         LocalPlayer *player = client->getEnv().getLocalPlayer();
4081
4082         /*
4083                 Fog range
4084         */
4085
4086         if (draw_control->range_all) {
4087                 runData->fog_range = 100000 * BS;
4088         } else {
4089                 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
4090         }
4091
4092         /*
4093                 Calculate general brightness
4094         */
4095         u32 daynight_ratio = client->getEnv().getDayNightRatio();
4096         float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
4097         float direct_brightness;
4098         bool sunlight_seen;
4099
4100         if (g_settings->getBool("free_move")) {
4101                 direct_brightness = time_brightness;
4102                 sunlight_seen = true;
4103         } else {
4104                 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4105                 float old_brightness = sky->getBrightness();
4106                 direct_brightness = client->getEnv().getClientMap()
4107                                 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4108                                         daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4109                                     / 255.0;
4110         }
4111
4112         float time_of_day = runData->time_of_day;
4113         float time_of_day_smooth = runData->time_of_day_smooth;
4114
4115         time_of_day = client->getEnv().getTimeOfDayF();
4116
4117         const float maxsm = 0.05;
4118         const float todsm = 0.05;
4119
4120         if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4121                         fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4122                         fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4123                 time_of_day_smooth = time_of_day;
4124
4125         if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4126                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4127                                 + (time_of_day + 1.0) * todsm;
4128         else
4129                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4130                                 + time_of_day * todsm;
4131
4132         runData->time_of_day = time_of_day;
4133         runData->time_of_day_smooth = time_of_day_smooth;
4134
4135         sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4136                         sunlight_seen, camera->getCameraMode(), player->getYaw(),
4137                         player->getPitch());
4138
4139         /*
4140                 Update clouds
4141         */
4142         if (clouds) {
4143                 v3f player_position = player->getPosition();
4144                 if (sky->getCloudsVisible()) {
4145                         clouds->setVisible(true);
4146                         clouds->step(dtime);
4147                         clouds->update(v2f(player_position.X, player_position.Z),
4148                                        sky->getCloudColor());
4149                 } else {
4150                         clouds->setVisible(false);
4151                 }
4152         }
4153
4154         /*
4155                 Update particles
4156         */
4157         client->getParticleManager()->step(dtime);
4158
4159         /*
4160                 Fog
4161         */
4162
4163         if (m_cache_enable_fog && !flags.force_fog_off) {
4164                 driver->setFog(
4165                                 sky->getBgColor(),
4166                                 video::EFT_FOG_LINEAR,
4167                                 runData->fog_range * 0.4,
4168                                 runData->fog_range * 1.0,
4169                                 0.01,
4170                                 false, // pixel fog
4171                                 true // range fog
4172                 );
4173         } else {
4174                 driver->setFog(
4175                                 sky->getBgColor(),
4176                                 video::EFT_FOG_LINEAR,
4177                                 100000 * BS,
4178                                 110000 * BS,
4179                                 0.01,
4180                                 false, // pixel fog
4181                                 false // range fog
4182                 );
4183         }
4184
4185         /*
4186                 Get chat messages from client
4187         */
4188
4189         v2u32 screensize = driver->getScreenSize();
4190
4191         updateChat(*client, dtime, flags.show_debug, screensize,
4192                         flags.show_chat, runData->profiler_current_page,
4193                         *chat_backend, guitext_chat);
4194
4195         /*
4196                 Inventory
4197         */
4198
4199         if (client->getPlayerItem() != runData->new_playeritem)
4200                 client->selectPlayerItem(runData->new_playeritem);
4201
4202         // Update local inventory if it has changed
4203         if (client->getLocalInventoryUpdated()) {
4204                 //infostream<<"Updating local inventory"<<std::endl;
4205                 client->getLocalInventory(*local_inventory);
4206                 runData->update_wielded_item_trigger = true;
4207         }
4208
4209         if (runData->update_wielded_item_trigger) {
4210                 // Update wielded tool
4211                 InventoryList *mlist = local_inventory->getList("main");
4212
4213                 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4214                         ItemStack item = mlist->getItem(client->getPlayerItem());
4215                         camera->wield(item);
4216                 }
4217                 runData->update_wielded_item_trigger = false;
4218         }
4219
4220         /*
4221                 Update block draw list every 200ms or when camera direction has
4222                 changed much
4223         */
4224         runData->update_draw_list_timer += dtime;
4225
4226         v3f camera_direction = camera->getDirection();
4227         if (runData->update_draw_list_timer >= 0.2
4228                         || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4229                         || flags.camera_offset_changed) {
4230                 runData->update_draw_list_timer = 0;
4231                 client->getEnv().getClientMap().updateDrawList(driver);
4232                 runData->update_draw_list_last_cam_dir = camera_direction;
4233         }
4234
4235         updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4236
4237         /*
4238            make sure menu is on top
4239            1. Delete formspec menu reference if menu was removed
4240            2. Else, make sure formspec menu is on top
4241         */
4242         if (current_formspec) {
4243                 if (current_formspec->getReferenceCount() == 1) {
4244                         current_formspec->drop();
4245                         current_formspec = NULL;
4246                 } else if (!noMenuActive()) {
4247                         guiroot->bringToFront(current_formspec);
4248                 }
4249         }
4250
4251         /*
4252                 Drawing begins
4253         */
4254
4255         video::SColor skycolor = sky->getSkyColor();
4256
4257         TimeTaker tt_draw("mainloop: draw");
4258         {
4259                 TimeTaker timer("beginScene");
4260                 driver->beginScene(true, true, skycolor);
4261                 stats->beginscenetime = timer.stop(true);
4262         }
4263
4264         draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4265                         guienv, screensize, skycolor, flags.show_hud,
4266                         flags.show_minimap);
4267
4268         /*
4269                 Profiler graph
4270         */
4271         if (flags.show_profiler_graph)
4272                 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4273
4274         /*
4275                 Damage flash
4276         */
4277         if (runData->damage_flash > 0.0) {
4278                 video::SColor color(std::min(runData->damage_flash, 180.0f),
4279                                 180,
4280                                 0,
4281                                 0);
4282                 driver->draw2DRectangle(color,
4283                                         core::rect<s32>(0, 0, screensize.X, screensize.Y),
4284                                         NULL);
4285
4286                 runData->damage_flash -= 100.0 * dtime;
4287         }
4288
4289         /*
4290                 Damage camera tilt
4291         */
4292         if (player->hurt_tilt_timer > 0.0) {
4293                 player->hurt_tilt_timer -= dtime * 5;
4294
4295                 if (player->hurt_tilt_timer < 0)
4296                         player->hurt_tilt_strength = 0;
4297         }
4298
4299         /*
4300                 Update minimap pos and rotation
4301         */
4302         if (flags.show_minimap && flags.show_hud) {
4303                 mapper->setPos(floatToInt(player->getPosition(), BS));
4304                 mapper->setAngle(player->getYaw());
4305         }
4306
4307         /*
4308                 End scene
4309         */
4310         {
4311                 TimeTaker timer("endScene");
4312                 driver->endScene();
4313                 stats->endscenetime = timer.stop(true);
4314         }
4315
4316         stats->drawtime = tt_draw.stop(true);
4317         g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4318 }
4319
4320
4321 inline static const char *yawToDirectionString(int yaw)
4322 {
4323         static const char *direction[4] = {"North [+Z]", "West [-X]", "South [-Z]", "East [+X]"};
4324
4325         yaw = wrapDegrees_0_360(yaw);
4326         yaw = (yaw + 45) % 360 / 90;
4327
4328         return direction[yaw];
4329 }
4330
4331
4332 void Game::updateGui(float *statustext_time, const RunStats &stats,
4333                 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4334                 const CameraOrientation &cam)
4335 {
4336         v2u32 screensize = driver->getScreenSize();
4337         LocalPlayer *player = client->getEnv().getLocalPlayer();
4338         v3f player_position = player->getPosition();
4339
4340         if (flags.show_debug) {
4341                 static float drawtime_avg = 0;
4342                 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4343
4344                 u16 fps = 1.0 / stats.dtime_jitter.avg;
4345                 //s32 fps = driver->getFPS();
4346
4347                 std::ostringstream os(std::ios_base::binary);
4348                 os << std::fixed
4349                    << PROJECT_NAME_C " " << g_version_hash
4350                    << " FPS = " << fps
4351                    << " (R: range_all=" << draw_control->range_all << ")"
4352                    << std::setprecision(0)
4353                    << " drawtime = " << drawtime_avg
4354                    << std::setprecision(1)
4355                    << ", dtime_jitter = "
4356                    << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4357                    << std::setprecision(1)
4358                    << ", v_range = " << draw_control->wanted_range
4359                    << std::setprecision(3)
4360                    << ", RTT = " << client->getRTT();
4361                 setStaticText(guitext, utf8_to_wide(os.str()).c_str());
4362                 guitext->setVisible(true);
4363         } else {
4364                 guitext->setVisible(false);
4365         }
4366
4367         if (guitext->isVisible()) {
4368                 core::rect<s32> rect(
4369                                 5,              5,
4370                                 screensize.X,   5 + g_fontengine->getTextHeight()
4371                 );
4372                 guitext->setRelativePosition(rect);
4373         }
4374
4375         if (flags.show_debug) {
4376                 std::ostringstream os(std::ios_base::binary);
4377                 os << std::setprecision(1) << std::fixed
4378                    << "(" << (player_position.X / BS)
4379                    << ", " << (player_position.Y / BS)
4380                    << ", " << (player_position.Z / BS)
4381                    << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4382                    << " " << yawToDirectionString(cam.camera_yaw)
4383                    << ") (seed = " << ((u64)client->getMapSeed())
4384                    << ")";
4385
4386                 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4387                         ClientMap &map = client->getEnv().getClientMap();
4388                         const INodeDefManager *nodedef = client->getNodeDefManager();
4389                         MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4390                         if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4391                                 const ContentFeatures &features = nodedef->get(n);
4392                                 os << " (pointing_at = " << nodedef->get(n).name
4393                                    << " - " << features.tiledef[0].name.c_str()
4394                                    << ")";
4395                         }
4396                 }
4397
4398                 setStaticText(guitext2, utf8_to_wide(os.str()).c_str());
4399                 guitext2->setVisible(true);
4400
4401                 core::rect<s32> rect(
4402                                 5,             5 + g_fontengine->getTextHeight(),
4403                                 screensize.X,  5 + g_fontengine->getTextHeight() * 2
4404                 );
4405                 guitext2->setRelativePosition(rect);
4406         } else {
4407                 guitext2->setVisible(false);
4408         }
4409
4410         setStaticText(guitext_info, infotext.c_str());
4411         guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4412
4413         float statustext_time_max = 1.5;
4414
4415         if (!statustext.empty()) {
4416                 *statustext_time += dtime;
4417
4418                 if (*statustext_time >= statustext_time_max) {
4419                         statustext = L"";
4420                         *statustext_time = 0;
4421                 }
4422         }
4423
4424         setStaticText(guitext_status, statustext.c_str());
4425         guitext_status->setVisible(!statustext.empty());
4426
4427         if (!statustext.empty()) {
4428                 s32 status_width  = guitext_status->getTextWidth();
4429                 s32 status_height = guitext_status->getTextHeight();
4430                 s32 status_y = screensize.Y - 150;
4431                 s32 status_x = (screensize.X - status_width) / 2;
4432                 core::rect<s32> rect(
4433                                 status_x , status_y - status_height,
4434                                 status_x + status_width, status_y
4435                 );
4436                 guitext_status->setRelativePosition(rect);
4437
4438                 // Fade out
4439                 video::SColor initial_color(255, 0, 0, 0);
4440
4441                 if (guienv->getSkin())
4442                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4443
4444                 video::SColor final_color = initial_color;
4445                 final_color.setAlpha(0);
4446                 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4447                                 initial_color, final_color,
4448                                 pow(*statustext_time / statustext_time_max, 2.0f));
4449                 guitext_status->setOverrideColor(fade_color);
4450                 guitext_status->enableOverrideColor(true);
4451         }
4452 }
4453
4454
4455 /* Log times and stuff for visualization */
4456 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4457 {
4458         Profiler::GraphValues values;
4459         g_profiler->graphGet(values);
4460         graph->put(values);
4461 }
4462
4463
4464
4465 /****************************************************************************
4466  Misc
4467  ****************************************************************************/
4468
4469 /* On some computers framerate doesn't seem to be automatically limited
4470  */
4471 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4472 {
4473         // not using getRealTime is necessary for wine
4474         device->getTimer()->tick(); // Maker sure device time is up-to-date
4475         u32 time = device->getTimer()->getTime();
4476         u32 last_time = fps_timings->last_time;
4477
4478         if (time > last_time)  // Make sure time hasn't overflowed
4479                 fps_timings->busy_time = time - last_time;
4480         else
4481                 fps_timings->busy_time = 0;
4482
4483         u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4484                         ? g_settings->getFloat("pause_fps_max")
4485                         : g_settings->getFloat("fps_max"));
4486
4487         if (fps_timings->busy_time < frametime_min) {
4488                 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4489                 device->sleep(fps_timings->sleep_time);
4490         } else {
4491                 fps_timings->sleep_time = 0;
4492         }
4493
4494         /* Get the new value of the device timer. Note that device->sleep() may
4495          * not sleep for the entire requested time as sleep may be interrupted and
4496          * therefore it is arguably more accurate to get the new time from the
4497          * device rather than calculating it by adding sleep_time to time.
4498          */
4499
4500         device->getTimer()->tick(); // Update device timer
4501         time = device->getTimer()->getTime();
4502
4503         if (time > last_time)  // Make sure last_time hasn't overflowed
4504                 *dtime = (time - last_time) / 1000.0;
4505         else
4506                 *dtime = 0;
4507
4508         fps_timings->last_time = time;
4509 }
4510
4511 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4512 // pass a copy of it to this function
4513 // Note: \p msg must be allocated using new (not malloc())
4514 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4515                 int percent, bool draw_clouds)
4516 {
4517         draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4518         delete[] msg;
4519 }
4520
4521 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4522 {
4523         ((Game *)data)->readSettings();
4524 }
4525
4526 void Game::readSettings()
4527 {
4528         m_cache_doubletap_jump               = g_settings->getBool("doubletap_jump");
4529         m_cache_enable_clouds                = g_settings->getBool("enable_clouds");
4530         m_cache_enable_joysticks             = g_settings->getBool("enable_joysticks");
4531         m_cache_enable_particles             = g_settings->getBool("enable_particles");
4532         m_cache_enable_fog                   = g_settings->getBool("enable_fog");
4533         m_cache_mouse_sensitivity            = g_settings->getFloat("mouse_sensitivity");
4534         m_cache_joystick_frustum_sensitivity = g_settings->getFloat("joystick_frustum_sensitivity");
4535         m_repeat_right_click_time            = g_settings->getFloat("repeat_rightclick_time");
4536
4537         m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4538 }
4539
4540 /****************************************************************************/
4541 /****************************************************************************
4542  Shutdown / cleanup
4543  ****************************************************************************/
4544 /****************************************************************************/
4545
4546 void Game::extendedResourceCleanup()
4547 {
4548         // Extended resource accounting
4549         infostream << "Irrlicht resources after cleanup:" << std::endl;
4550         infostream << "\tRemaining meshes   : "
4551                    << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4552         infostream << "\tRemaining textures : "
4553                    << driver->getTextureCount() << std::endl;
4554
4555         for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4556                 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4557                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4558                            << std::endl;
4559         }
4560
4561         clearTextureNameCache();
4562         infostream << "\tRemaining materials: "
4563                << driver-> getMaterialRendererCount()
4564                        << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4565 }
4566
4567
4568 /****************************************************************************/
4569 /****************************************************************************
4570  extern function for launching the game
4571  ****************************************************************************/
4572 /****************************************************************************/
4573
4574 void the_game(bool *kill,
4575                 bool random_input,
4576                 InputHandler *input,
4577                 IrrlichtDevice *device,
4578
4579                 const std::string &map_dir,
4580                 const std::string &playername,
4581                 const std::string &password,
4582                 const std::string &address,         // If empty local server is created
4583                 u16 port,
4584
4585                 std::string &error_message,
4586                 ChatBackend &chat_backend,
4587                 bool *reconnect_requested,
4588                 const SubgameSpec &gamespec,        // Used for local game
4589                 bool simple_singleplayer_mode)
4590 {
4591         Game game;
4592
4593         /* Make a copy of the server address because if a local singleplayer server
4594          * is created then this is updated and we don't want to change the value
4595          * passed to us by the calling function
4596          */
4597         std::string server_address = address;
4598
4599         try {
4600
4601                 if (game.startup(kill, random_input, input, device, map_dir,
4602                                 playername, password, &server_address, port, error_message,
4603                                 reconnect_requested, &chat_backend, gamespec,
4604                                 simple_singleplayer_mode)) {
4605                         game.run();
4606                         game.shutdown();
4607                 }
4608
4609         } catch (SerializationError &e) {
4610                 error_message = std::string("A serialization error occurred:\n")
4611                                 + e.what() + "\n\nThe server is probably "
4612                                 " running a different version of " PROJECT_NAME_C ".";
4613                 errorstream << error_message << std::endl;
4614         } catch (ServerError &e) {
4615                 error_message = e.what();
4616                 errorstream << "ServerError: " << error_message << std::endl;
4617         } catch (ModError &e) {
4618                 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4619                 errorstream << "ModError: " << error_message << std::endl;
4620         }
4621 }