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