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