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