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