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