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