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