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