]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
Center status text for better visibility.
[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
1329 struct CameraOrientation {
1330         f32 camera_yaw;    // "right/left"
1331         f32 camera_pitch;  // "up/down"
1332 };
1333
1334 struct GameRunData {
1335         u16 dig_index;
1336         u16 new_playeritem;
1337         PointedThing pointed_old;
1338         bool digging;
1339         bool ldown_for_dig;
1340         bool left_punch;
1341         bool update_wielded_item_trigger;
1342         bool reset_jump_timer;
1343         float nodig_delay_timer;
1344         float dig_time;
1345         float dig_time_complete;
1346         float repeat_rightclick_timer;
1347         float object_hit_delay_timer;
1348         float time_from_last_punch;
1349         ClientActiveObject *selected_object;
1350
1351         float jump_timer;
1352         float damage_flash;
1353         float update_draw_list_timer;
1354         float statustext_time;
1355
1356         f32 fog_range;
1357
1358         v3f update_draw_list_last_cam_dir;
1359
1360         u32 profiler_current_page;
1361         u32 profiler_max_page;     // Number of pages
1362
1363         float time_of_day;
1364         float time_of_day_smooth;
1365 };
1366
1367 struct Jitter {
1368         f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1369 };
1370
1371 struct RunStats {
1372         u32 drawtime;
1373         u32 beginscenetime;
1374         u32 endscenetime;
1375
1376         Jitter dtime_jitter, busy_time_jitter;
1377 };
1378
1379 /* Flags that can, or may, change during main game loop
1380  */
1381 struct VolatileRunFlags {
1382         bool invert_mouse;
1383         bool show_chat;
1384         bool show_hud;
1385         bool force_fog_off;
1386         bool show_debug;
1387         bool show_profiler_graph;
1388         bool disable_camera_update;
1389         bool first_loop_after_window_activation;
1390         bool camera_offset_changed;
1391 };
1392
1393
1394 /****************************************************************************
1395  THE GAME
1396  ****************************************************************************/
1397
1398 /* This is not intended to be a public class. If a public class becomes
1399  * desirable then it may be better to create another 'wrapper' class that
1400  * hides most of the stuff in this class (nothing in this class is required
1401  * by any other file) but exposes the public methods/data only.
1402  */
1403 class Game
1404 {
1405 public:
1406         Game();
1407         ~Game();
1408
1409         bool startup(bool *kill,
1410                         bool random_input,
1411                         InputHandler *input,
1412                         IrrlichtDevice *device,
1413                         const std::string &map_dir,
1414                         const std::string &playername,
1415                         const std::string &password,
1416                         // If address is "", local server is used and address is updated
1417                         std::string *address,
1418                         u16 port,
1419                         std::wstring *error_message,
1420                         ChatBackend *chat_backend,
1421                         const SubgameSpec &gamespec,    // Used for local game
1422                         bool simple_singleplayer_mode);
1423
1424         void run();
1425         void shutdown();
1426
1427 protected:
1428
1429         void extendedResourceCleanup();
1430
1431         // Basic initialisation
1432         bool init(const std::string &map_dir, std::string *address,
1433                         u16 port,
1434                         const SubgameSpec &gamespec);
1435         bool initSound();
1436         bool createSingleplayerServer(const std::string map_dir,
1437                         const SubgameSpec &gamespec, u16 port, std::string *address);
1438
1439         // Client creation
1440         bool createClient(const std::string &playername,
1441                         const std::string &password, std::string *address, u16 port,
1442                         std::wstring *error_message);
1443         bool initGui(std::wstring *error_message);
1444
1445         // Client connection
1446         bool connectToServer(const std::string &playername,
1447                         const std::string &password, std::string *address, u16 port,
1448                         bool *connect_ok, bool *aborted);
1449         bool getServerContent(bool *aborted);
1450
1451         // Main loop
1452
1453         void updateInteractTimers(GameRunData *args, f32 dtime);
1454         bool checkConnection();
1455         bool handleCallbacks();
1456         void processQueues();
1457         void updateProfilers(const GameRunData &run_data, const RunStats &stats,
1458                         const FpsControl &draw_times, f32 dtime);
1459         void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1460                         f32 dtime);
1461         void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1462
1463         void processUserInput(VolatileRunFlags *flags, GameRunData *interact_args,
1464                         f32 dtime);
1465         void processKeyboardInput(VolatileRunFlags *flags,
1466                         float *statustext_time,
1467                         float *jump_timer,
1468                         bool *reset_jump_timer,
1469                         u32 *profiler_current_page,
1470                         u32 profiler_max_page);
1471         void processItemSelection(u16 *new_playeritem);
1472
1473         void dropSelectedItem();
1474         void openInventory();
1475         void openConsole();
1476         void toggleFreeMove(float *statustext_time);
1477         void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1478         void toggleFast(float *statustext_time);
1479         void toggleNoClip(float *statustext_time);
1480
1481         void toggleChat(float *statustext_time, bool *flag);
1482         void toggleHud(float *statustext_time, bool *flag);
1483         void toggleFog(float *statustext_time, bool *flag);
1484         void toggleDebug(float *statustext_time, bool *show_debug,
1485                         bool *show_profiler_graph);
1486         void toggleUpdateCamera(float *statustext_time, bool *flag);
1487         void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1488                         u32 profiler_max_page);
1489
1490         void increaseViewRange(float *statustext_time);
1491         void decreaseViewRange(float *statustext_time);
1492         void toggleFullViewRange(float *statustext_time);
1493
1494         void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1495         void updatePlayerControl(const CameraOrientation &cam);
1496         void step(f32 *dtime);
1497         void processClientEvents(CameraOrientation *cam, float *damage_flash);
1498         void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1499                         float time_from_last_punch);
1500         void updateSound(f32 dtime);
1501         void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1502                         GameRunData *runData, f32 dtime, bool show_hud,
1503                         bool show_debug);
1504         void handlePointingAtNode(GameRunData *runData,
1505                         const PointedThing &pointed, const ItemDefinition &playeritem_def,
1506                         const ToolCapabilities &playeritem_toolcap, f32 dtime);
1507         void handlePointingAtObject(GameRunData *runData,
1508                         const PointedThing &pointed, const ItemStack &playeritem,
1509                         const v3f &player_position, bool show_debug);
1510         void handleDigging(GameRunData *runData, const PointedThing &pointed,
1511                         const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1512                         f32 dtime);
1513         void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1514                         RunStats *stats, GameRunData *runData,
1515                         f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1516         void updateGui(float *statustext_time, const RunStats &stats,
1517                         const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1518                         const CameraOrientation &cam);
1519         void updateProfilerGraphs(ProfilerGraph *graph);
1520
1521         // Misc
1522         void limitFps(FpsControl *fps_timings, f32 *dtime);
1523
1524         void showOverlayMessage(const char *msg, float dtime, int percent,
1525                         bool draw_clouds = true);
1526
1527 private:
1528         InputHandler *input;
1529
1530         Client *client;
1531         Server *server;
1532
1533         IWritableTextureSource *texture_src;
1534         IWritableShaderSource *shader_src;
1535
1536         // When created, these will be filled with data received from the server
1537         IWritableItemDefManager *itemdef_manager;
1538         IWritableNodeDefManager *nodedef_manager;
1539
1540         GameOnDemandSoundFetcher soundfetcher; // useful when testing
1541         ISoundManager *sound;
1542         bool sound_is_dummy;
1543         SoundMaker *soundmaker;
1544
1545         ChatBackend *chat_backend;
1546
1547         GUIFormSpecMenu *current_formspec;
1548
1549         EventManager *eventmgr;
1550         QuicktuneShortcutter *quicktune;
1551
1552         GUIChatConsole *gui_chat_console; // Free using ->Drop()
1553         MapDrawControl *draw_control;
1554         Camera *camera;
1555         Clouds *clouds;                   // Free using ->Drop()
1556         Sky *sky;                         // Free using ->Drop()
1557         Inventory *local_inventory;
1558         Hud *hud;
1559
1560         /* 'cache'
1561            This class does take ownership/responsibily for cleaning up etc of any of
1562            these items (e.g. device)
1563         */
1564         IrrlichtDevice *device;
1565         video::IVideoDriver *driver;
1566         scene::ISceneManager *smgr;
1567         bool *kill;
1568         std::wstring *error_message;
1569         IGameDef *gamedef;                     // Convenience (same as *client)
1570         scene::ISceneNode *skybox;
1571
1572         bool random_input;
1573         bool simple_singleplayer_mode;
1574         /* End 'cache' */
1575
1576         /* Pre-calculated values
1577          */
1578         int crack_animation_length;
1579
1580         /* GUI stuff
1581          */
1582         gui::IGUIStaticText *guitext;          // First line of debug text
1583         gui::IGUIStaticText *guitext2;         // Second line of debug text
1584         gui::IGUIStaticText *guitext_info;     // At the middle of the screen
1585         gui::IGUIStaticText *guitext_status;
1586         gui::IGUIStaticText *guitext_chat;         // Chat text
1587         gui::IGUIStaticText *guitext_profiler; // Profiler text
1588
1589         std::wstring infotext;
1590         std::wstring statustext;
1591
1592         KeyCache keycache;
1593
1594         IntervalLimiter profiler_interval;
1595
1596         /* TODO: Add a callback function so these can be updated when a setting
1597          *       changes.  At this point in time it doesn't matter (e.g. /set
1598          *       is documented to change server settings only)
1599          *
1600          * TODO: Local caching of settings is not optimal and should at some stage
1601          *       be updated to use a global settings object for getting thse values
1602          *       (as opposed to the this local caching). This can be addressed in
1603          *       a later release.
1604          */
1605         bool m_cache_doubletap_jump;
1606         bool m_cache_enable_node_highlighting;
1607         bool m_cache_enable_clouds;
1608         bool m_cache_enable_particles;
1609         bool m_cache_enable_fog;
1610         f32  m_cache_mouse_sensitivity;
1611         f32  m_repeat_right_click_time;
1612 };
1613
1614 Game::Game() :
1615         client(NULL),
1616         server(NULL),
1617         texture_src(NULL),
1618         shader_src(NULL),
1619         itemdef_manager(NULL),
1620         nodedef_manager(NULL),
1621         sound(NULL),
1622         sound_is_dummy(false),
1623         soundmaker(NULL),
1624         chat_backend(NULL),
1625         current_formspec(NULL),
1626         eventmgr(NULL),
1627         quicktune(NULL),
1628         gui_chat_console(NULL),
1629         draw_control(NULL),
1630         camera(NULL),
1631         clouds(NULL),
1632         sky(NULL),
1633         local_inventory(NULL),
1634         hud(NULL)
1635 {
1636         m_cache_doubletap_jump            = g_settings->getBool("doubletap_jump");
1637         m_cache_enable_node_highlighting  = g_settings->getBool("enable_node_highlighting");
1638         m_cache_enable_clouds             = g_settings->getBool("enable_clouds");
1639         m_cache_enable_particles          = g_settings->getBool("enable_particles");
1640         m_cache_enable_fog                = g_settings->getBool("enable_fog");
1641         m_cache_mouse_sensitivity         = g_settings->getFloat("mouse_sensitivity");
1642         m_repeat_right_click_time         = g_settings->getFloat("repeat_rightclick_time");
1643 }
1644
1645
1646
1647 /****************************************************************************
1648  MinetestApp Public
1649  ****************************************************************************/
1650
1651 Game::~Game()
1652 {
1653         delete client;
1654         delete soundmaker;
1655         if (!sound_is_dummy)
1656                 delete sound;
1657
1658         delete server; // deleted first to stop all server threads
1659
1660         delete hud;
1661         delete local_inventory;
1662         delete camera;
1663         delete quicktune;
1664         delete eventmgr;
1665         delete texture_src;
1666         delete shader_src;
1667         delete nodedef_manager;
1668         delete itemdef_manager;
1669         delete draw_control;
1670
1671         extendedResourceCleanup();
1672 }
1673
1674 bool Game::startup(bool *kill,
1675                 bool random_input,
1676                 InputHandler *input,
1677                 IrrlichtDevice *device,
1678                 const std::string &map_dir,
1679                 const std::string &playername,
1680                 const std::string &password,
1681                 std::string *address,     // can change if simple_singleplayer_mode
1682                 u16 port,
1683                 std::wstring *error_message,
1684                 ChatBackend *chat_backend,
1685                 const SubgameSpec &gamespec,
1686                 bool simple_singleplayer_mode)
1687 {
1688         // "cache"
1689         this->device        = device;
1690         this->kill          = kill;
1691         this->error_message = error_message;
1692         this->random_input  = random_input;
1693         this->input         = input;
1694         this->chat_backend  = chat_backend;
1695         this->simple_singleplayer_mode = simple_singleplayer_mode;
1696
1697         driver              = device->getVideoDriver();
1698         smgr                = device->getSceneManager();
1699
1700         smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1701
1702         if (!init(map_dir, address, port, gamespec))
1703                 return false;
1704
1705         if (!createClient(playername, password, address, port, error_message))
1706                 return false;
1707
1708         return true;
1709 }
1710
1711
1712 void Game::run()
1713 {
1714         ProfilerGraph graph;
1715         RunStats stats              = { 0 };
1716         CameraOrientation cam_view  = { 0 };
1717         GameRunData runData         = { 0 };
1718         FpsControl draw_times       = { 0 };
1719         VolatileRunFlags flags      = { 0 };
1720         f32 dtime; // in seconds
1721
1722         runData.time_from_last_punch  = 10.0;
1723         runData.profiler_max_page = 3;
1724         runData.update_wielded_item_trigger = true;
1725
1726         flags.show_chat = true;
1727         flags.show_hud = true;
1728         flags.show_debug = g_settings->getBool("show_debug");
1729         flags.invert_mouse = g_settings->getBool("invert_mouse");
1730
1731         /* Clear the profiler */
1732         Profiler::GraphValues dummyvalues;
1733         g_profiler->graphGet(dummyvalues);
1734
1735         draw_times.last_time = device->getTimer()->getTime();
1736
1737         shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1738                         sky,
1739                         &flags.force_fog_off,
1740                         &runData.fog_range,
1741                         client));
1742
1743         std::vector<aabb3f> highlight_boxes;
1744
1745         while (device->run() && !(*kill || g_gamecallback->shutdown_requested)) {
1746
1747                 /* Must be called immediately after a device->run() call because it
1748                  * uses device->getTimer()->getTime()
1749                  */
1750                 limitFps(&draw_times, &dtime);
1751
1752                 updateStats(&stats, draw_times, dtime);
1753                 updateInteractTimers(&runData, dtime);
1754
1755                 if (!checkConnection())
1756                         break;
1757                 if (!handleCallbacks())
1758                         break;
1759
1760                 processQueues();
1761
1762                 infotext = L"";
1763                 hud->resizeHotbar();
1764
1765                 updateProfilers(runData, stats, draw_times, dtime);
1766                 processUserInput(&flags, &runData, dtime);
1767                 // Update camera before player movement to avoid camera lag of one frame
1768                 updateCameraDirection(&cam_view, &flags);
1769                 updatePlayerControl(cam_view);
1770                 step(&dtime);
1771                 processClientEvents(&cam_view, &runData.damage_flash);
1772                 updateCamera(&flags, draw_times.busy_time, dtime,
1773                                 runData.time_from_last_punch);
1774                 updateSound(dtime);
1775                 processPlayerInteraction(highlight_boxes, &runData, dtime,
1776                                 flags.show_hud, flags.show_debug);
1777                 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1778                                 flags, cam_view);
1779                 updateProfilerGraphs(&graph);
1780         }
1781 }
1782
1783
1784 void Game::shutdown()
1785 {
1786         showOverlayMessage("Shutting down...", 0, 0, false);
1787
1788         if (clouds)
1789                 clouds->drop();
1790
1791         if (gui_chat_console)
1792                 gui_chat_console->drop();
1793
1794         if (sky)
1795                 sky->drop();
1796
1797         clear_particles();
1798
1799         /* cleanup menus */
1800         while (g_menumgr.menuCount() > 0) {
1801                 g_menumgr.m_stack.front()->setVisible(false);
1802                 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1803         }
1804
1805         if (current_formspec) {
1806                 current_formspec->drop();
1807                 current_formspec = NULL;
1808         }
1809
1810         chat_backend->addMessage(L"", L"# Disconnected.");
1811         chat_backend->addMessage(L"", L"");
1812
1813         if (client) {
1814                 client->Stop();
1815                 while (!client->isShutdown()) {
1816                         assert(texture_src != NULL);
1817                         assert(shader_src != NULL);
1818                         texture_src->processQueue();
1819                         shader_src->processQueue();
1820                         sleep_ms(100);
1821                 }
1822         }
1823 }
1824
1825
1826
1827 /****************************************************************************
1828  Startup
1829  ****************************************************************************/
1830
1831 bool Game::init(
1832                 const std::string &map_dir,
1833                 std::string *address,
1834                 u16 port,
1835                 const SubgameSpec &gamespec)
1836 {
1837         showOverlayMessage("Loading...", 0, 0);
1838
1839         texture_src = createTextureSource(device);
1840         shader_src = createShaderSource(device);
1841
1842         itemdef_manager = createItemDefManager();
1843         nodedef_manager = createNodeDefManager();
1844
1845         eventmgr = new EventManager();
1846         quicktune = new QuicktuneShortcutter();
1847
1848         if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1849                         && eventmgr && quicktune))
1850                 return false;
1851
1852         if (!initSound())
1853                 return false;
1854
1855         // Create a server if not connecting to an existing one
1856         if (*address == "") {
1857                 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1858                         return false;
1859         }
1860
1861         return true;
1862 }
1863
1864 bool Game::initSound()
1865 {
1866 #if USE_SOUND
1867         if (g_settings->getBool("enable_sound")) {
1868                 infostream << "Attempting to use OpenAL audio" << std::endl;
1869                 sound = createOpenALSoundManager(&soundfetcher);
1870                 if (!sound)
1871                         infostream << "Failed to initialize OpenAL audio" << std::endl;
1872         } else
1873                 infostream << "Sound disabled." << std::endl;
1874 #endif
1875
1876         if (!sound) {
1877                 infostream << "Using dummy audio." << std::endl;
1878                 sound = &dummySoundManager;
1879                 sound_is_dummy = true;
1880         }
1881
1882         soundmaker = new SoundMaker(sound, nodedef_manager);
1883         if (!soundmaker)
1884                 return false;
1885
1886         soundmaker->registerReceiver(eventmgr);
1887
1888         return true;
1889 }
1890
1891 bool Game::createSingleplayerServer(const std::string map_dir,
1892                 const SubgameSpec &gamespec, u16 port, std::string *address)
1893 {
1894         showOverlayMessage("Creating server...", 0, 25);
1895
1896         std::string bind_str = g_settings->get("bind_address");
1897         Address bind_addr(0, 0, 0, 0, port);
1898
1899         if (g_settings->getBool("ipv6_server")) {
1900                 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1901         }
1902
1903         try {
1904                 bind_addr.Resolve(bind_str.c_str());
1905                 *address = bind_str;
1906         } catch (ResolveError &e) {
1907                 infostream << "Resolving bind address \"" << bind_str
1908                            << "\" failed: " << e.what()
1909                            << " -- Listening on all addresses." << std::endl;
1910         }
1911
1912         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1913                 *error_message = L"Unable to listen on " +
1914                                 narrow_to_wide(bind_addr.serializeString()) +
1915                                 L" because IPv6 is disabled";
1916                 errorstream << wide_to_narrow(*error_message) << std::endl;
1917                 return false;
1918         }
1919
1920         server = new Server(map_dir, gamespec, simple_singleplayer_mode,
1921                             bind_addr.isIPv6());
1922
1923         server->start(bind_addr);
1924
1925         return true;
1926 }
1927
1928 bool Game::createClient(const std::string &playername,
1929                 const std::string &password, std::string *address, u16 port,
1930                 std::wstring *error_message)
1931 {
1932         showOverlayMessage("Creating client...", 0, 50);
1933
1934         draw_control = new MapDrawControl;
1935         if (!draw_control)
1936                 return false;
1937
1938         bool could_connect, connect_aborted;
1939
1940         if (!connectToServer(playername, password, address, port,
1941                         &could_connect, &connect_aborted))
1942                 return false;
1943
1944         if (!could_connect) {
1945                 if (*error_message == L"" && !connect_aborted) {
1946                         // Should not happen if error messages are set properly
1947                         *error_message = L"Connection failed for unknown reason";
1948                         errorstream << wide_to_narrow(*error_message) << std::endl;
1949                 }
1950                 return false;
1951         }
1952
1953         if (!getServerContent(&connect_aborted)) {
1954                 if (*error_message == L"" && !connect_aborted) {
1955                         // Should not happen if error messages are set properly
1956                         *error_message = L"Connection failed for unknown reason";
1957                         errorstream << wide_to_narrow(*error_message) << std::endl;
1958                 }
1959                 return false;
1960         }
1961
1962         // Update cached textures, meshes and materials
1963         client->afterContentReceived(device, g_fontengine->getFont());
1964
1965         /* Camera
1966          */
1967         camera = new Camera(smgr, *draw_control, gamedef);
1968         if (!camera || !camera->successfullyCreated(*error_message))
1969                 return false;
1970
1971         /* Clouds
1972          */
1973         if (m_cache_enable_clouds) {
1974                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1975                 if (!clouds) {
1976                         *error_message = L"Memory allocation error";
1977                         *error_message += narrow_to_wide(" (clouds)");
1978                         errorstream << wide_to_narrow(*error_message) << std::endl;
1979                         return false;
1980                 }
1981         }
1982
1983         /* Skybox
1984          */
1985         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1986         skybox = NULL;  // This is used/set later on in the main run loop
1987
1988         local_inventory = new Inventory(itemdef_manager);
1989
1990         if (!(sky && local_inventory)) {
1991                 *error_message = L"Memory allocation error";
1992                 *error_message += narrow_to_wide(" (sky or local inventory)");
1993                 errorstream << wide_to_narrow(*error_message) << std::endl;
1994                 return false;
1995         }
1996
1997         /* Pre-calculated values
1998          */
1999         video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2000         if (t) {
2001                 v2u32 size = t->getOriginalSize();
2002                 crack_animation_length = size.Y / size.X;
2003         } else {
2004                 crack_animation_length = 5;
2005         }
2006
2007         if (!initGui(error_message))
2008                 return false;
2009
2010         /* Set window caption
2011          */
2012         core::stringw str = L"Minetest [";
2013         str += driver->getName();
2014         str += "]";
2015         device->setWindowCaption(str.c_str());
2016
2017         LocalPlayer *player = client->getEnv().getLocalPlayer();
2018         player->hurt_tilt_timer = 0;
2019         player->hurt_tilt_strength = 0;
2020
2021         hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2022
2023         if (!hud) {
2024                 *error_message = L"Memory error: could not create HUD";
2025                 errorstream << wide_to_narrow(*error_message) << std::endl;
2026                 return false;
2027         }
2028
2029         return true;
2030 }
2031
2032 bool Game::initGui(std::wstring *error_message)
2033 {
2034         // First line of debug text
2035         guitext = guienv->addStaticText(
2036                         L"Minetest",
2037                         core::rect<s32>(0, 0, 0, 0),
2038                         false, false, guiroot);
2039
2040         // Second line of debug text
2041         guitext2 = guienv->addStaticText(
2042                         L"",
2043                         core::rect<s32>(0, 0, 0, 0),
2044                         false, false, guiroot);
2045
2046         // At the middle of the screen
2047         // Object infos are shown in this
2048         guitext_info = guienv->addStaticText(
2049                         L"",
2050                         core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2051                         false, true, guiroot);
2052
2053         // Status text (displays info when showing and hiding GUI stuff, etc.)
2054         guitext_status = guienv->addStaticText(
2055                         L"<Status>",
2056                         core::rect<s32>(0, 0, 0, 0),
2057                         false, false, guiroot);
2058         guitext_status->setVisible(false);
2059
2060         // Chat text
2061         guitext_chat = guienv->addStaticText(
2062                         L"",
2063                         core::rect<s32>(0, 0, 0, 0),
2064                         //false, false); // Disable word wrap as of now
2065                         false, true, guiroot);
2066         // Remove stale "recent" chat messages from previous connections
2067         chat_backend->clearRecentChat();
2068
2069         // Chat backend and console
2070         gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2071                         -1, chat_backend, client);
2072         if (!gui_chat_console) {
2073                 *error_message = L"Could not allocate memory for chat console";
2074                 errorstream << wide_to_narrow(*error_message) << std::endl;
2075                 return false;
2076         }
2077
2078         // Profiler text (size is updated when text is updated)
2079         guitext_profiler = guienv->addStaticText(
2080                         L"<Profiler>",
2081                         core::rect<s32>(0, 0, 0, 0),
2082                         false, false, guiroot);
2083         guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2084         guitext_profiler->setVisible(false);
2085         guitext_profiler->setWordWrap(true);
2086
2087 #ifdef HAVE_TOUCHSCREENGUI
2088
2089         if (g_touchscreengui)
2090                 g_touchscreengui->init(texture_src, porting::getDisplayDensity());
2091
2092 #endif
2093
2094         return true;
2095 }
2096
2097 bool Game::connectToServer(const std::string &playername,
2098                 const std::string &password, std::string *address, u16 port,
2099                 bool *connect_ok, bool *aborted)
2100 {
2101         showOverlayMessage("Resolving address...", 0, 75);
2102
2103         Address connect_address(0, 0, 0, 0, port);
2104
2105         try {
2106                 connect_address.Resolve(address->c_str());
2107
2108                 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2109                         //connect_address.Resolve("localhost");
2110                         if (connect_address.isIPv6()) {
2111                                 IPv6AddressBytes addr_bytes;
2112                                 addr_bytes.bytes[15] = 1;
2113                                 connect_address.setAddress(&addr_bytes);
2114                         } else {
2115                                 connect_address.setAddress(127, 0, 0, 1);
2116                         }
2117                 }
2118         } catch (ResolveError &e) {
2119                 *error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
2120                 errorstream << wide_to_narrow(*error_message) << std::endl;
2121                 return false;
2122         }
2123
2124         if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2125                 *error_message = L"Unable to connect to " +
2126                                 narrow_to_wide(connect_address.serializeString()) +
2127                                 L" because IPv6 is disabled";
2128                 errorstream << wide_to_narrow(*error_message) << std::endl;
2129                 return false;
2130         }
2131
2132         client = new Client(device,
2133                         playername.c_str(), password, simple_singleplayer_mode,
2134                         *draw_control, texture_src, shader_src,
2135                         itemdef_manager, nodedef_manager, sound, eventmgr,
2136                         connect_address.isIPv6());
2137
2138         if (!client)
2139                 return false;
2140
2141         gamedef = client;       // Client acts as our GameDef
2142
2143
2144         infostream << "Connecting to server at ";
2145         connect_address.print(&infostream);
2146         infostream << std::endl;
2147
2148         client->connect(connect_address);
2149
2150
2151         /*
2152                 Wait for server to accept connection
2153         */
2154
2155         try {
2156                 input->clear();
2157
2158                 FpsControl fps_control = { 0 };
2159                 f32 dtime; // in seconds
2160
2161                 while (device->run()) {
2162
2163                         limitFps(&fps_control, &dtime);
2164
2165                         // Update client and server
2166                         client->step(dtime);
2167
2168                         if (server != NULL)
2169                                 server->step(dtime);
2170
2171                         // End condition
2172                         if (client->getState() == LC_Init) {
2173                                 *connect_ok = true;
2174                                 break;
2175                         }
2176
2177                         // Break conditions
2178                         if (client->accessDenied()) {
2179                                 *error_message = L"Access denied. Reason: "
2180                                                 + client->accessDeniedReason();
2181                                 errorstream << wide_to_narrow(*error_message) << std::endl;
2182                                 break;
2183                         }
2184
2185                         if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2186                                 *aborted = true;
2187                                 infostream << "Connect aborted [Escape]" << std::endl;
2188                                 break;
2189                         }
2190
2191                         // Update status
2192                         showOverlayMessage("Connecting to server...", dtime, 100);
2193                 }
2194         } catch (con::PeerNotFoundException &e) {
2195                 // TODO: Should something be done here? At least an info/error
2196                 // message?
2197                 return false;
2198         }
2199
2200         return true;
2201 }
2202
2203 bool Game::getServerContent(bool *aborted)
2204 {
2205         input->clear();
2206
2207         FpsControl fps_control = { 0 };
2208         f32 dtime; // in seconds
2209
2210         while (device->run()) {
2211
2212                 limitFps(&fps_control, &dtime);
2213
2214                 // Update client and server
2215                 client->step(dtime);
2216
2217                 if (server != NULL)
2218                         server->step(dtime);
2219
2220                 // End condition
2221                 if (client->mediaReceived() && client->itemdefReceived() &&
2222                                 client->nodedefReceived()) {
2223                         break;
2224                 }
2225
2226                 // Error conditions
2227                 if (client->accessDenied()) {
2228                         *error_message = L"Access denied. Reason: "
2229                                         + client->accessDeniedReason();
2230                         errorstream << wide_to_narrow(*error_message) << std::endl;
2231                         return false;
2232                 }
2233
2234                 if (client->getState() < LC_Init) {
2235                         *error_message = L"Client disconnected";
2236                         errorstream << wide_to_narrow(*error_message) << std::endl;
2237                         return false;
2238                 }
2239
2240                 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2241                         *aborted = true;
2242                         infostream << "Connect aborted [Escape]" << std::endl;
2243                         return false;
2244                 }
2245
2246                 // Display status
2247                 int progress = 0;
2248
2249                 if (!client->itemdefReceived()) {
2250                         wchar_t *text = wgettext("Item definitions...");
2251                         progress = 0;
2252                         draw_load_screen(text, device, guienv, dtime, progress);
2253                         delete[] text;
2254                 } else if (!client->nodedefReceived()) {
2255                         wchar_t *text = wgettext("Node definitions...");
2256                         progress = 25;
2257                         draw_load_screen(text, device, guienv, dtime, progress);
2258                         delete[] text;
2259                 } else {
2260                         std::stringstream message;
2261                         message.precision(3);
2262                         message << gettext("Media...");
2263
2264                         if ((USE_CURL == 0) ||
2265                                         (!g_settings->getBool("enable_remote_media_server"))) {
2266                                 float cur = client->getCurRate();
2267                                 std::string cur_unit = gettext(" KB/s");
2268
2269                                 if (cur > 900) {
2270                                         cur /= 1024.0;
2271                                         cur_unit = gettext(" MB/s");
2272                                 }
2273
2274                                 message << " ( " << cur << cur_unit << " )";
2275                         }
2276
2277                         progress = 50 + client->mediaReceiveProgress() * 50 + 0.5;
2278                         draw_load_screen(narrow_to_wide(message.str().c_str()), device,
2279                                         guienv, dtime, progress);
2280                 }
2281         }
2282
2283         return true;
2284 }
2285
2286
2287
2288 /****************************************************************************
2289  Run
2290  ****************************************************************************/
2291
2292 inline void Game::updateInteractTimers(GameRunData *args, f32 dtime)
2293 {
2294         if (args->nodig_delay_timer >= 0)
2295                 args->nodig_delay_timer -= dtime;
2296
2297         if (args->object_hit_delay_timer >= 0)
2298                 args->object_hit_delay_timer -= dtime;
2299
2300         args->time_from_last_punch += dtime;
2301 }
2302
2303
2304 /* returns false if game should exit, otherwise true
2305  */
2306 inline bool Game::checkConnection()
2307 {
2308         if (client->accessDenied()) {
2309                 *error_message = L"Access denied. Reason: "
2310                                 + client->accessDeniedReason();
2311                 errorstream << wide_to_narrow(*error_message) << std::endl;
2312                 return false;
2313         }
2314
2315         return true;
2316 }
2317
2318
2319 /* returns false if game should exit, otherwise true
2320  */
2321 inline bool Game::handleCallbacks()
2322 {
2323         if (g_gamecallback->disconnect_requested) {
2324                 g_gamecallback->disconnect_requested = false;
2325                 return false;
2326         }
2327
2328         if (g_gamecallback->changepassword_requested) {
2329                 (new GUIPasswordChange(guienv, guiroot, -1,
2330                                        &g_menumgr, client))->drop();
2331                 g_gamecallback->changepassword_requested = false;
2332         }
2333
2334         if (g_gamecallback->changevolume_requested) {
2335                 (new GUIVolumeChange(guienv, guiroot, -1,
2336                                      &g_menumgr, client))->drop();
2337                 g_gamecallback->changevolume_requested = false;
2338         }
2339
2340         if (g_gamecallback->keyconfig_requested) {
2341                 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2342                                       &g_menumgr))->drop();
2343                 g_gamecallback->keyconfig_requested = false;
2344         }
2345
2346         if (g_gamecallback->keyconfig_changed) {
2347                 keycache.populate(); // update the cache with new settings
2348                 g_gamecallback->keyconfig_changed = false;
2349         }
2350
2351         return true;
2352 }
2353
2354
2355 void Game::processQueues()
2356 {
2357         texture_src->processQueue();
2358         itemdef_manager->processQueue(gamedef);
2359         shader_src->processQueue();
2360 }
2361
2362
2363 void Game::updateProfilers(const GameRunData &run_data, const RunStats &stats,
2364                 const FpsControl &draw_times, f32 dtime)
2365 {
2366         float profiler_print_interval =
2367                         g_settings->getFloat("profiler_print_interval");
2368         bool print_to_log = true;
2369
2370         if (profiler_print_interval == 0) {
2371                 print_to_log = false;
2372                 profiler_print_interval = 5;
2373         }
2374
2375         if (profiler_interval.step(dtime, profiler_print_interval)) {
2376                 if (print_to_log) {
2377                         infostream << "Profiler:" << std::endl;
2378                         g_profiler->print(infostream);
2379                 }
2380
2381                 update_profiler_gui(guitext_profiler, g_fontengine,
2382                                 run_data.profiler_current_page, run_data.profiler_max_page,
2383                                 driver->getScreenSize().Height);
2384
2385                 g_profiler->clear();
2386         }
2387
2388         addProfilerGraphs(stats, draw_times, dtime);
2389 }
2390
2391
2392 void Game::addProfilerGraphs(const RunStats &stats,
2393                 const FpsControl &draw_times, f32 dtime)
2394 {
2395         g_profiler->graphAdd("mainloop_other",
2396                         draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2397
2398         if (draw_times.sleep_time != 0)
2399                 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2400         g_profiler->graphAdd("mainloop_dtime", dtime);
2401
2402         g_profiler->add("Elapsed time", dtime);
2403         g_profiler->avg("FPS", 1. / dtime);
2404 }
2405
2406
2407 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2408                 f32 dtime)
2409 {
2410
2411         f32 jitter;
2412         Jitter *jp;
2413
2414         /* Time average and jitter calculation
2415          */
2416         jp = &stats->dtime_jitter;
2417         jp->avg = jp->avg * 0.96 + dtime * 0.04;
2418
2419         jitter = dtime - jp->avg;
2420
2421         if (jitter > jp->max)
2422                 jp->max = jitter;
2423
2424         jp->counter += dtime;
2425
2426         if (jp->counter > 0.0) {
2427                 jp->counter -= 3.0;
2428                 jp->max_sample = jp->max;
2429                 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2430                 jp->max = 0.0;
2431         }
2432
2433         /* Busytime average and jitter calculation
2434          */
2435         jp = &stats->busy_time_jitter;
2436         jp->avg = jp->avg + draw_times.busy_time * 0.02;
2437
2438         jitter = draw_times.busy_time - jp->avg;
2439
2440         if (jitter > jp->max)
2441                 jp->max = jitter;
2442         if (jitter < jp->min)
2443                 jp->min = jitter;
2444
2445         jp->counter += dtime;
2446
2447         if (jp->counter > 0.0) {
2448                 jp->counter -= 3.0;
2449                 jp->max_sample = jp->max;
2450                 jp->min_sample = jp->min;
2451                 jp->max = 0.0;
2452                 jp->min = 0.0;
2453         }
2454 }
2455
2456
2457
2458 /****************************************************************************
2459  Input handling
2460  ****************************************************************************/
2461
2462 void Game::processUserInput(VolatileRunFlags *flags,
2463                 GameRunData *interact_args, f32 dtime)
2464 {
2465         // Reset input if window not active or some menu is active
2466         if (device->isWindowActive() == false
2467                         || noMenuActive() == false
2468                         || guienv->hasFocus(gui_chat_console)) {
2469                 input->clear();
2470         }
2471
2472         if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2473                 gui_chat_console->closeConsoleAtOnce();
2474         }
2475
2476         // Input handler step() (used by the random input generator)
2477         input->step(dtime);
2478
2479 #ifdef HAVE_TOUCHSCREENGUI
2480
2481         if (g_touchscreengui) {
2482                 g_touchscreengui->step(dtime);
2483         }
2484
2485 #endif
2486 #ifdef __ANDROID__
2487
2488         if (current_formspec != 0)
2489                 current_formspec->getAndroidUIInput();
2490
2491 #endif
2492
2493         // Increase timer for double tap of "keymap_jump"
2494         if (m_cache_doubletap_jump && interact_args->jump_timer <= 0.2)
2495                 interact_args->jump_timer += dtime;
2496
2497         processKeyboardInput(
2498                         flags,
2499                         &interact_args->statustext_time,
2500                         &interact_args->jump_timer,
2501                         &interact_args->reset_jump_timer,
2502                         &interact_args->profiler_current_page,
2503                         interact_args->profiler_max_page);
2504
2505         processItemSelection(&interact_args->new_playeritem);
2506 }
2507
2508
2509 void Game::processKeyboardInput(VolatileRunFlags *flags,
2510                 float *statustext_time,
2511                 float *jump_timer,
2512                 bool *reset_jump_timer,
2513                 u32 *profiler_current_page,
2514                 u32 profiler_max_page)
2515 {
2516
2517         //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2518
2519         if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2520                 dropSelectedItem();
2521         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2522                 openInventory();
2523         } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2524                 show_pause_menu(&current_formspec, client, gamedef, texture_src, device,
2525                                 simple_singleplayer_mode);
2526         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2527                 show_chat_menu(&current_formspec, client, gamedef, texture_src, device,
2528                                 client, "");
2529         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2530                 show_chat_menu(&current_formspec, client, gamedef, texture_src, device,
2531                                 client, "/");
2532         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2533                 openConsole();
2534         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2535                 toggleFreeMove(statustext_time);
2536         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2537                 toggleFreeMoveAlt(statustext_time, jump_timer);
2538                 *reset_jump_timer = true;
2539         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2540                 toggleFast(statustext_time);
2541         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2542                 toggleNoClip(statustext_time);
2543         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2544                 client->makeScreenshot(device);
2545         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2546                 toggleHud(statustext_time, &flags->show_hud);
2547         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2548                 toggleChat(statustext_time, &flags->show_chat);
2549         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2550                 toggleFog(statustext_time, &flags->force_fog_off);
2551         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2552                 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2553         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2554                 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2555         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2556                 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2557         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2558                 increaseViewRange(statustext_time);
2559         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2560                 decreaseViewRange(statustext_time);
2561         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2562                 toggleFullViewRange(statustext_time);
2563         } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2564                 quicktune->next();
2565         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2566                 quicktune->prev();
2567         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2568                 quicktune->inc();
2569         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2570                 quicktune->dec();
2571         else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2572                 // Print debug stacks
2573                 dstream << "-----------------------------------------"
2574                         << std::endl;
2575                 dstream << DTIME << "Printing debug stacks:" << std::endl;
2576                 dstream << "-----------------------------------------"
2577                         << std::endl;
2578                 debug_stacks_print();
2579         }
2580
2581         if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2582                 *reset_jump_timer = false;
2583                 *jump_timer = 0.0;
2584         }
2585
2586         //tt.stop();
2587
2588         if (quicktune->hasMessage()) {
2589                 std::string msg = quicktune->getMessage();
2590                 statustext = narrow_to_wide(msg);
2591                 *statustext_time = 0;
2592         }
2593 }
2594
2595
2596 void Game::processItemSelection(u16 *new_playeritem)
2597 {
2598         LocalPlayer *player = client->getEnv().getLocalPlayer();
2599
2600         /* Item selection using mouse wheel
2601          */
2602         *new_playeritem = client->getPlayerItem();
2603
2604         s32 wheel = input->getMouseWheel();
2605         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2606                                  player->hud_hotbar_itemcount - 1);
2607
2608         if (wheel < 0)
2609                 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2610         else if (wheel > 0)
2611                 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2612         // else wheel == 0
2613
2614
2615         /* Item selection using keyboard
2616          */
2617         for (u16 i = 0; i < 10; i++) {
2618                 static const KeyPress *item_keys[10] = {
2619                         NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2620                         NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2621                         NumberKey + 9, NumberKey + 0,
2622                 };
2623
2624                 if (input->wasKeyDown(*item_keys[i])) {
2625                         if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2626                                 *new_playeritem = i;
2627                                 infostream << "Selected item: " << new_playeritem << std::endl;
2628                         }
2629                         break;
2630                 }
2631         }
2632 }
2633
2634
2635 void Game::dropSelectedItem()
2636 {
2637         IDropAction *a = new IDropAction();
2638         a->count = 0;
2639         a->from_inv.setCurrentPlayer();
2640         a->from_list = "main";
2641         a->from_i = client->getPlayerItem();
2642         client->inventoryAction(a);
2643 }
2644
2645
2646 void Game::openInventory()
2647 {
2648         infostream << "the_game: " << "Launching inventory" << std::endl;
2649
2650         PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2651         TextDest *txt_dst = new TextDestPlayerInventory(client);
2652
2653         create_formspec_menu(&current_formspec, client, gamedef, texture_src,
2654                         device, fs_src, txt_dst, client);
2655
2656         InventoryLocation inventoryloc;
2657         inventoryloc.setCurrentPlayer();
2658         current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2659 }
2660
2661
2662 void Game::openConsole()
2663 {
2664         if (!gui_chat_console->isOpenInhibited()) {
2665                 // Open up to over half of the screen
2666                 gui_chat_console->openConsole(0.6);
2667                 guienv->setFocus(gui_chat_console);
2668         }
2669 }
2670
2671
2672 void Game::toggleFreeMove(float *statustext_time)
2673 {
2674         static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2675
2676         bool free_move = !g_settings->getBool("free_move");
2677         g_settings->set("free_move", bool_to_cstr(free_move));
2678
2679         *statustext_time = 0;
2680         statustext = msg[free_move];
2681         if (free_move && !client->checkPrivilege("fly"))
2682                 statustext += L" (note: no 'fly' privilege)";
2683 }
2684
2685
2686 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2687 {
2688         if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2689                 toggleFreeMove(statustext_time);
2690 }
2691
2692
2693 void Game::toggleFast(float *statustext_time)
2694 {
2695         static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2696         bool fast_move = !g_settings->getBool("fast_move");
2697         g_settings->set("fast_move", bool_to_cstr(fast_move));
2698
2699         *statustext_time = 0;
2700         statustext = msg[fast_move];
2701
2702         if (fast_move && !client->checkPrivilege("fast"))
2703                 statustext += L" (note: no 'fast' privilege)";
2704 }
2705
2706
2707 void Game::toggleNoClip(float *statustext_time)
2708 {
2709         static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2710         bool noclip = !g_settings->getBool("noclip");
2711         g_settings->set("noclip", bool_to_cstr(noclip));
2712
2713         *statustext_time = 0;
2714         statustext = msg[noclip];
2715
2716         if (noclip && !client->checkPrivilege("noclip"))
2717                 statustext += L" (note: no 'noclip' privilege)";
2718 }
2719
2720
2721 void Game::toggleChat(float *statustext_time, bool *flag)
2722 {
2723         static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2724
2725         *flag = !*flag;
2726         *statustext_time = 0;
2727         statustext = msg[*flag];
2728 }
2729
2730
2731 void Game::toggleHud(float *statustext_time, bool *flag)
2732 {
2733         static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2734
2735         *flag = !*flag;
2736         *statustext_time = 0;
2737         statustext = msg[*flag];
2738         if (g_settings->getBool("enable_node_highlighting"))
2739                 client->setHighlighted(client->getHighlighted(), *flag);
2740 }
2741
2742
2743 void Game::toggleFog(float *statustext_time, bool *flag)
2744 {
2745         static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2746
2747         *flag = !*flag;
2748         *statustext_time = 0;
2749         statustext = msg[*flag];
2750 }
2751
2752
2753 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2754                 bool *show_profiler_graph)
2755 {
2756         // Initial / 3x toggle: Chat only
2757         // 1x toggle: Debug text with chat
2758         // 2x toggle: Debug text with profiler graph
2759         if (!*show_debug) {
2760                 *show_debug = true;
2761                 *show_profiler_graph = false;
2762                 statustext = L"Debug info shown";
2763         } else if (*show_profiler_graph) {
2764                 *show_debug = false;
2765                 *show_profiler_graph = false;
2766                 statustext = L"Debug info and profiler graph hidden";
2767         } else {
2768                 *show_profiler_graph = true;
2769                 statustext = L"Profiler graph shown";
2770         }
2771         *statustext_time = 0;
2772 }
2773
2774
2775 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2776 {
2777         static const wchar_t *msg[] = {
2778                 L"Camera update enabled",
2779                 L"Camera update disabled"
2780         };
2781
2782         *flag = !*flag;
2783         *statustext_time = 0;
2784         statustext = msg[*flag];
2785 }
2786
2787
2788 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2789                 u32 profiler_max_page)
2790 {
2791         *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2792
2793         // FIXME: This updates the profiler with incomplete values
2794         update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2795                         profiler_max_page, driver->getScreenSize().Height);
2796
2797         if (*profiler_current_page != 0) {
2798                 std::wstringstream sstr;
2799                 sstr << "Profiler shown (page " << *profiler_current_page
2800                      << " of " << profiler_max_page << ")";
2801                 statustext = sstr.str();
2802         } else {
2803                 statustext = L"Profiler hidden";
2804         }
2805         *statustext_time = 0;
2806 }
2807
2808
2809 void Game::increaseViewRange(float *statustext_time)
2810 {
2811         s16 range = g_settings->getS16("viewing_range_nodes_min");
2812         s16 range_new = range + 10;
2813         g_settings->set("viewing_range_nodes_min", itos(range_new));
2814         statustext = narrow_to_wide("Minimum viewing range changed to "
2815                         + itos(range_new));
2816         *statustext_time = 0;
2817 }
2818
2819
2820 void Game::decreaseViewRange(float *statustext_time)
2821 {
2822         s16 range = g_settings->getS16("viewing_range_nodes_min");
2823         s16 range_new = range - 10;
2824
2825         if (range_new < 0)
2826                 range_new = range;
2827
2828         g_settings->set("viewing_range_nodes_min", itos(range_new));
2829         statustext = narrow_to_wide("Minimum viewing range changed to "
2830                         + itos(range_new));
2831         *statustext_time = 0;
2832 }
2833
2834
2835 void Game::toggleFullViewRange(float *statustext_time)
2836 {
2837         static const wchar_t *msg[] = {
2838                 L"Disabled full viewing range",
2839                 L"Enabled full viewing range"
2840         };
2841
2842         draw_control->range_all = !draw_control->range_all;
2843         infostream << msg[draw_control->range_all] << std::endl;
2844         statustext = msg[draw_control->range_all];
2845         *statustext_time = 0;
2846 }
2847
2848
2849 void Game::updateCameraDirection(CameraOrientation *cam,
2850                 VolatileRunFlags *flags)
2851 {
2852         // float turn_amount = 0;       // Deprecated?
2853
2854         if (!(device->isWindowActive() && noMenuActive()) || random_input) {
2855
2856         // FIXME: Clean this up
2857
2858 #ifndef ANDROID
2859                 // Mac OSX gets upset if this is set every frame
2860                 if (device->getCursorControl()->isVisible() == false)
2861                         device->getCursorControl()->setVisible(true);
2862 #endif
2863
2864                 //infostream<<"window inactive"<<std::endl;
2865                 flags->first_loop_after_window_activation = true;
2866                 return;
2867         }
2868
2869 #ifndef __ANDROID__
2870         if (!random_input) {
2871                 // Mac OSX gets upset if this is set every frame
2872                 if (device->getCursorControl()->isVisible())
2873                         device->getCursorControl()->setVisible(false);
2874         }
2875 #endif
2876
2877         if (flags->first_loop_after_window_activation) {
2878                 //infostream<<"window active, first loop"<<std::endl;
2879                 flags->first_loop_after_window_activation = false;
2880         } else {
2881
2882 #ifdef HAVE_TOUCHSCREENGUI
2883
2884                 if (g_touchscreengui) {
2885                         cam->camera_yaw   = g_touchscreengui->getYaw();
2886                         cam->camera_pitch = g_touchscreengui->getPitch();
2887                 } else {
2888 #endif
2889                         s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
2890                         s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
2891
2892                         if (flags->invert_mouse
2893                                         || (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2894                                 dy = -dy;
2895                         }
2896
2897                         //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2898
2899                         float d = m_cache_mouse_sensitivity;
2900                         d = rangelim(d, 0.01, 100.0);
2901                         cam->camera_yaw -= dx * d;
2902                         cam->camera_pitch += dy * d;
2903                         // turn_amount = v2f(dx, dy).getLength() * d; // deprecated?
2904
2905 #ifdef HAVE_TOUCHSCREENGUI
2906                         }
2907 #endif
2908
2909                 if (cam->camera_pitch < -89.5)
2910                         cam->camera_pitch = -89.5;
2911                 else if (cam->camera_pitch > 89.5)
2912                         cam->camera_pitch = 89.5;
2913         }
2914
2915         input->setMousePos(driver->getScreenSize().Width / 2,
2916                         driver->getScreenSize().Height / 2);
2917
2918         // Deprecated? Not used anywhere else
2919         // recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2920         // std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2921 }
2922
2923
2924 void Game::updatePlayerControl(const CameraOrientation &cam)
2925 {
2926         //TimeTaker tt("update player control", NULL, PRECISION_NANO);
2927
2928         PlayerControl control(
2929                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
2930                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
2931                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
2932                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
2933                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
2934                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
2935                 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
2936                 input->getLeftState(),
2937                 input->getRightState(),
2938                 cam.camera_pitch,
2939                 cam.camera_yaw
2940         );
2941         client->setPlayerControl(control);
2942         LocalPlayer *player = client->getEnv().getLocalPlayer();
2943         player->keyPressed =
2944                 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD])  & 0x1) << 0) |
2945                 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
2946                 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT])     & 0x1) << 2) |
2947                 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT])    & 0x1) << 3) |
2948                 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])     & 0x1) << 4) |
2949                 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
2950                 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK])    & 0x1) << 6) |
2951                 ( (u32)(input->getLeftState()                                        & 0x1) << 7) |
2952                 ( (u32)(input->getRightState()                                       & 0x1) << 8
2953         );
2954
2955         //tt.stop();
2956 }
2957
2958
2959 inline void Game::step(f32 *dtime)
2960 {
2961         bool can_be_and_is_paused =
2962                         (simple_singleplayer_mode && g_menumgr.pausesGame());
2963
2964         if (can_be_and_is_paused) {     // This is for a singleplayer server
2965                 *dtime = 0;             // No time passes
2966         } else {
2967                 if (server != NULL) {
2968                         //TimeTaker timer("server->step(dtime)");
2969                         server->step(*dtime);
2970                 }
2971
2972                 //TimeTaker timer("client.step(dtime)");
2973                 client->step(*dtime);
2974         }
2975 }
2976
2977
2978 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
2979 {
2980         ClientEvent event = client->getClientEvent();
2981
2982         LocalPlayer *player = client->getEnv().getLocalPlayer();
2983
2984         for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
2985
2986                 if (event.type == CE_PLAYER_DAMAGE &&
2987                                 client->getHP() != 0) {
2988                         //u16 damage = event.player_damage.amount;
2989                         //infostream<<"Player damage: "<<damage<<std::endl;
2990
2991                         *damage_flash += 100.0;
2992                         *damage_flash += 8.0 * event.player_damage.amount;
2993
2994                         player->hurt_tilt_timer = 1.5;
2995                         player->hurt_tilt_strength = event.player_damage.amount / 4;
2996                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2997
2998                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2999                         gamedef->event()->put(e);
3000                 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3001                         cam->camera_yaw = event.player_force_move.yaw;
3002                         cam->camera_pitch = event.player_force_move.pitch;
3003                 } else if (event.type == CE_DEATHSCREEN) {
3004                         show_deathscreen(&current_formspec, client, gamedef, texture_src,
3005                                          device, client);
3006
3007                         chat_backend->addMessage(L"", L"You died.");
3008
3009                         /* Handle visualization */
3010                         *damage_flash = 0;
3011                         player->hurt_tilt_timer = 0;
3012                         player->hurt_tilt_strength = 0;
3013
3014                 } else if (event.type == CE_SHOW_FORMSPEC) {
3015                         FormspecFormSource *fs_src =
3016                                 new FormspecFormSource(*(event.show_formspec.formspec));
3017                         TextDestPlayerInventory *txt_dst =
3018                                 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3019
3020                         create_formspec_menu(&current_formspec, client, gamedef,
3021                                              texture_src, device, fs_src, txt_dst, client);
3022
3023                         delete(event.show_formspec.formspec);
3024                         delete(event.show_formspec.formname);
3025                 } else if (event.type == CE_SPAWN_PARTICLE) {
3026                         video::ITexture *texture =
3027                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
3028
3029                         new Particle(gamedef, smgr, player, client->getEnv(),
3030                                         *event.spawn_particle.pos,
3031                                         *event.spawn_particle.vel,
3032                                         *event.spawn_particle.acc,
3033                                         event.spawn_particle.expirationtime,
3034                                         event.spawn_particle.size,
3035                                         event.spawn_particle.collisiondetection,
3036                                         event.spawn_particle.vertical,
3037                                         texture,
3038                                         v2f(0.0, 0.0),
3039                                         v2f(1.0, 1.0));
3040                 } else if (event.type == CE_ADD_PARTICLESPAWNER) {
3041                         video::ITexture *texture =
3042                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
3043
3044                         new ParticleSpawner(gamedef, smgr, player,
3045                                         event.add_particlespawner.amount,
3046                                         event.add_particlespawner.spawntime,
3047                                         *event.add_particlespawner.minpos,
3048                                         *event.add_particlespawner.maxpos,
3049                                         *event.add_particlespawner.minvel,
3050                                         *event.add_particlespawner.maxvel,
3051                                         *event.add_particlespawner.minacc,
3052                                         *event.add_particlespawner.maxacc,
3053                                         event.add_particlespawner.minexptime,
3054                                         event.add_particlespawner.maxexptime,
3055                                         event.add_particlespawner.minsize,
3056                                         event.add_particlespawner.maxsize,
3057                                         event.add_particlespawner.collisiondetection,
3058                                         event.add_particlespawner.vertical,
3059                                         texture,
3060                                         event.add_particlespawner.id);
3061                 } else if (event.type == CE_DELETE_PARTICLESPAWNER) {
3062                         delete_particlespawner(event.delete_particlespawner.id);
3063                 } else if (event.type == CE_HUDADD) {
3064                         u32 id = event.hudadd.id;
3065
3066                         LocalPlayer *player = client->getEnv().getLocalPlayer();
3067                         HudElement *e = player->getHud(id);
3068
3069                         if (e != NULL) {
3070                                 delete event.hudadd.pos;
3071                                 delete event.hudadd.name;
3072                                 delete event.hudadd.scale;
3073                                 delete event.hudadd.text;
3074                                 delete event.hudadd.align;
3075                                 delete event.hudadd.offset;
3076                                 delete event.hudadd.world_pos;
3077                                 delete event.hudadd.size;
3078                                 continue;
3079                         }
3080
3081                         e = new HudElement;
3082                         e->type   = (HudElementType)event.hudadd.type;
3083                         e->pos    = *event.hudadd.pos;
3084                         e->name   = *event.hudadd.name;
3085                         e->scale  = *event.hudadd.scale;
3086                         e->text   = *event.hudadd.text;
3087                         e->number = event.hudadd.number;
3088                         e->item   = event.hudadd.item;
3089                         e->dir    = event.hudadd.dir;
3090                         e->align  = *event.hudadd.align;
3091                         e->offset = *event.hudadd.offset;
3092                         e->world_pos = *event.hudadd.world_pos;
3093                         e->size = *event.hudadd.size;
3094
3095                         u32 new_id = player->addHud(e);
3096                         //if this isn't true our huds aren't consistent
3097                         assert(new_id == id);
3098
3099                         delete event.hudadd.pos;
3100                         delete event.hudadd.name;
3101                         delete event.hudadd.scale;
3102                         delete event.hudadd.text;
3103                         delete event.hudadd.align;
3104                         delete event.hudadd.offset;
3105                         delete event.hudadd.world_pos;
3106                         delete event.hudadd.size;
3107                 } else if (event.type == CE_HUDRM) {
3108                         HudElement *e = player->removeHud(event.hudrm.id);
3109
3110                         if (e != NULL)
3111                                 delete(e);
3112                 } else if (event.type == CE_HUDCHANGE) {
3113                         u32 id = event.hudchange.id;
3114                         HudElement *e = player->getHud(id);
3115
3116                         if (e == NULL) {
3117                                 delete event.hudchange.v3fdata;
3118                                 delete event.hudchange.v2fdata;
3119                                 delete event.hudchange.sdata;
3120                                 delete event.hudchange.v2s32data;
3121                                 continue;
3122                         }
3123
3124                         switch (event.hudchange.stat) {
3125                         case HUD_STAT_POS:
3126                                 e->pos = *event.hudchange.v2fdata;
3127                                 break;
3128
3129                         case HUD_STAT_NAME:
3130                                 e->name = *event.hudchange.sdata;
3131                                 break;
3132
3133                         case HUD_STAT_SCALE:
3134                                 e->scale = *event.hudchange.v2fdata;
3135                                 break;
3136
3137                         case HUD_STAT_TEXT:
3138                                 e->text = *event.hudchange.sdata;
3139                                 break;
3140
3141                         case HUD_STAT_NUMBER:
3142                                 e->number = event.hudchange.data;
3143                                 break;
3144
3145                         case HUD_STAT_ITEM:
3146                                 e->item = event.hudchange.data;
3147                                 break;
3148
3149                         case HUD_STAT_DIR:
3150                                 e->dir = event.hudchange.data;
3151                                 break;
3152
3153                         case HUD_STAT_ALIGN:
3154                                 e->align = *event.hudchange.v2fdata;
3155                                 break;
3156
3157                         case HUD_STAT_OFFSET:
3158                                 e->offset = *event.hudchange.v2fdata;
3159                                 break;
3160
3161                         case HUD_STAT_WORLD_POS:
3162                                 e->world_pos = *event.hudchange.v3fdata;
3163                                 break;
3164
3165                         case HUD_STAT_SIZE:
3166                                 e->size = *event.hudchange.v2s32data;
3167                                 break;
3168                         }
3169
3170                         delete event.hudchange.v3fdata;
3171                         delete event.hudchange.v2fdata;
3172                         delete event.hudchange.sdata;
3173                         delete event.hudchange.v2s32data;
3174                 } else if (event.type == CE_SET_SKY) {
3175                         sky->setVisible(false);
3176
3177                         if (skybox) {
3178                                 skybox->remove();
3179                                 skybox = NULL;
3180                         }
3181
3182                         // Handle according to type
3183                         if (*event.set_sky.type == "regular") {
3184                                 sky->setVisible(true);
3185                         } else if (*event.set_sky.type == "skybox" &&
3186                                         event.set_sky.params->size() == 6) {
3187                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3188                                 skybox = smgr->addSkyBoxSceneNode(
3189                                                  texture_src->getTexture((*event.set_sky.params)[0]),
3190                                                  texture_src->getTexture((*event.set_sky.params)[1]),
3191                                                  texture_src->getTexture((*event.set_sky.params)[2]),
3192                                                  texture_src->getTexture((*event.set_sky.params)[3]),
3193                                                  texture_src->getTexture((*event.set_sky.params)[4]),
3194                                                  texture_src->getTexture((*event.set_sky.params)[5]));
3195                         }
3196                         // Handle everything else as plain color
3197                         else {
3198                                 if (*event.set_sky.type != "plain")
3199                                         infostream << "Unknown sky type: "
3200                                                    << (*event.set_sky.type) << std::endl;
3201
3202                                 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3203                         }
3204
3205                         delete event.set_sky.bgcolor;
3206                         delete event.set_sky.type;
3207                         delete event.set_sky.params;
3208                 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3209                         bool enable = event.override_day_night_ratio.do_override;
3210                         u32 value = event.override_day_night_ratio.ratio_f * 1000;
3211                         client->getEnv().setDayNightRatioOverride(enable, value);
3212                 }
3213         }
3214 }
3215
3216
3217 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3218                 f32 dtime, float time_from_last_punch)
3219 {
3220         LocalPlayer *player = client->getEnv().getLocalPlayer();
3221
3222         /*
3223                 For interaction purposes, get info about the held item
3224                 - What item is it?
3225                 - Is it a usable item?
3226                 - Can it point to liquids?
3227         */
3228         ItemStack playeritem;
3229         {
3230                 InventoryList *mlist = local_inventory->getList("main");
3231
3232                 if (mlist && client->getPlayerItem() < mlist->getSize())
3233                         playeritem = mlist->getItem(client->getPlayerItem());
3234         }
3235
3236         ToolCapabilities playeritem_toolcap =
3237                 playeritem.getToolCapabilities(itemdef_manager);
3238
3239         v3s16 old_camera_offset = camera->getOffset();
3240
3241         if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3242                 camera->toggleCameraMode();
3243                 GenericCAO *playercao = player->getCAO();
3244
3245                 assert(playercao != NULL);
3246
3247                 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3248         }
3249
3250         float full_punch_interval = playeritem_toolcap.full_punch_interval;
3251         float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3252
3253         tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3254         camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3255                       client->getEnv());
3256         camera->step(dtime);
3257
3258         v3f camera_position = camera->getPosition();
3259         v3f camera_direction = camera->getDirection();
3260         f32 camera_fov = camera->getFovMax();
3261         v3s16 camera_offset = camera->getOffset();
3262
3263         flags->camera_offset_changed = (camera_offset != old_camera_offset);
3264
3265         if (!flags->disable_camera_update) {
3266                 client->getEnv().getClientMap().updateCamera(camera_position,
3267                                 camera_direction, camera_fov, camera_offset);
3268
3269                 if (flags->camera_offset_changed) {
3270                         client->updateCameraOffset(camera_offset);
3271                         client->getEnv().updateCameraOffset(camera_offset);
3272
3273                         if (clouds)
3274                                 clouds->updateCameraOffset(camera_offset);
3275                 }
3276         }
3277 }
3278
3279
3280 void Game::updateSound(f32 dtime)
3281 {
3282         // Update sound listener
3283         v3s16 camera_offset = camera->getOffset();
3284         sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3285                               v3f(0, 0, 0), // velocity
3286                               camera->getDirection(),
3287                               camera->getCameraNode()->getUpVector());
3288         sound->setListenerGain(g_settings->getFloat("sound_volume"));
3289
3290
3291         //      Update sound maker
3292         soundmaker->step(dtime);
3293
3294         LocalPlayer *player = client->getEnv().getLocalPlayer();
3295
3296         ClientMap &map = client->getEnv().getClientMap();
3297         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3298         soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3299 }
3300
3301
3302 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3303                 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3304 {
3305         LocalPlayer *player = client->getEnv().getLocalPlayer();
3306
3307         ItemStack playeritem;
3308         {
3309                 InventoryList *mlist = local_inventory->getList("main");
3310
3311                 if (mlist && client->getPlayerItem() < mlist->getSize())
3312                         playeritem = mlist->getItem(client->getPlayerItem());
3313         }
3314
3315         const ItemDefinition &playeritem_def =
3316                         playeritem.getDefinition(itemdef_manager);
3317
3318         v3f player_position  = player->getPosition();
3319         v3f camera_position  = camera->getPosition();
3320         v3f camera_direction = camera->getDirection();
3321         v3s16 camera_offset  = camera->getOffset();
3322
3323
3324         /*
3325                 Calculate what block is the crosshair pointing to
3326         */
3327
3328         f32 d = playeritem_def.range; // max. distance
3329         f32 d_hand = itemdef_manager->get("").range;
3330
3331         if (d < 0 && d_hand >= 0)
3332                 d = d_hand;
3333         else if (d < 0)
3334                 d = 4.0;
3335
3336         core::line3d<f32> shootline;
3337
3338         if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3339
3340                 shootline = core::line3d<f32>(camera_position,
3341                                                 camera_position + camera_direction * BS * (d + 1));
3342
3343         } else {
3344             // prevent player pointing anything in front-view
3345                 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3346                         shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3347         }
3348
3349 #ifdef HAVE_TOUCHSCREENGUI
3350
3351         if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3352                 shootline = g_touchscreengui->getShootline();
3353                 shootline.start += intToFloat(camera_offset, BS);
3354                 shootline.end += intToFloat(camera_offset, BS);
3355         }
3356
3357 #endif
3358
3359         PointedThing pointed = getPointedThing(
3360                         // input
3361                         client, player_position, camera_direction,
3362                         camera_position, shootline, d,
3363                         playeritem_def.liquids_pointable,
3364                         !runData->ldown_for_dig,
3365                         camera_offset,
3366                         // output
3367                         highlight_boxes,
3368                         runData->selected_object);
3369
3370         if (pointed != runData->pointed_old) {
3371                 infostream << "Pointing at " << pointed.dump() << std::endl;
3372
3373                 if (m_cache_enable_node_highlighting) {
3374                         if (pointed.type == POINTEDTHING_NODE) {
3375                                 client->setHighlighted(pointed.node_undersurface, show_hud);
3376                         } else {
3377                                 client->setHighlighted(pointed.node_undersurface, false);
3378                         }
3379                 }
3380         }
3381
3382         /*
3383                 Stop digging when
3384                 - releasing left mouse button
3385                 - pointing away from node
3386         */
3387         if (runData->digging) {
3388                 if (input->getLeftReleased()) {
3389                         infostream << "Left button released"
3390                                    << " (stopped digging)" << std::endl;
3391                         runData->digging = false;
3392                 } else if (pointed != runData->pointed_old) {
3393                         if (pointed.type == POINTEDTHING_NODE
3394                                         && runData->pointed_old.type == POINTEDTHING_NODE
3395                                         && pointed.node_undersurface
3396                                                         == runData->pointed_old.node_undersurface) {
3397                                 // Still pointing to the same node, but a different face.
3398                                 // Don't reset.
3399                         } else {
3400                                 infostream << "Pointing away from node"
3401                                            << " (stopped digging)" << std::endl;
3402                                 runData->digging = false;
3403                         }
3404                 }
3405
3406                 if (!runData->digging) {
3407                         client->interact(1, runData->pointed_old);
3408                         client->setCrack(-1, v3s16(0, 0, 0));
3409                         runData->dig_time = 0.0;
3410                 }
3411         }
3412
3413         if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3414                 runData->ldown_for_dig = false;
3415         }
3416
3417         runData->left_punch = false;
3418
3419         soundmaker->m_player_leftpunch_sound.name = "";
3420
3421         if (input->getRightState())
3422                 runData->repeat_rightclick_timer += dtime;
3423         else
3424                 runData->repeat_rightclick_timer = 0;
3425
3426         if (playeritem_def.usable && input->getLeftState()) {
3427                 if (input->getLeftClicked())
3428                         client->interact(4, pointed);
3429         } else if (pointed.type == POINTEDTHING_NODE) {
3430                 ToolCapabilities playeritem_toolcap =
3431                                 playeritem.getToolCapabilities(itemdef_manager);
3432                 handlePointingAtNode(runData, pointed, playeritem_def,
3433                                 playeritem_toolcap, dtime);
3434         } else if (pointed.type == POINTEDTHING_OBJECT) {
3435                 handlePointingAtObject(runData, pointed, playeritem,
3436                                 player_position, show_debug);
3437         } else if (input->getLeftState()) {
3438                 // When button is held down in air, show continuous animation
3439                 runData->left_punch = true;
3440         }
3441
3442         runData->pointed_old = pointed;
3443
3444         if (runData->left_punch || input->getLeftClicked())
3445                 camera->setDigging(0); // left click animation
3446
3447         input->resetLeftClicked();
3448         input->resetRightClicked();
3449
3450         input->resetLeftReleased();
3451         input->resetRightReleased();
3452 }
3453
3454
3455 void Game::handlePointingAtNode(GameRunData *runData,
3456                 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3457                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3458 {
3459         v3s16 nodepos = pointed.node_undersurface;
3460         v3s16 neighbourpos = pointed.node_abovesurface;
3461
3462         /*
3463                 Check information text of node
3464         */
3465
3466         ClientMap &map = client->getEnv().getClientMap();
3467         NodeMetadata *meta = map.getNodeMetadata(nodepos);
3468
3469         if (meta) {
3470                 infotext = narrow_to_wide(meta->getString("infotext"));
3471         } else {
3472                 MapNode n = map.getNodeNoEx(nodepos);
3473
3474                 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3475                         infotext = L"Unknown node: ";
3476                         infotext += narrow_to_wide(nodedef_manager->get(n).name);
3477                 }
3478         }
3479
3480         if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3481                         && client->checkPrivilege("interact")) {
3482                 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3483         }
3484
3485         if ((input->getRightClicked() ||
3486                         runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3487                         client->checkPrivilege("interact")) {
3488                 runData->repeat_rightclick_timer = 0;
3489                 infostream << "Ground right-clicked" << std::endl;
3490
3491                 if (meta && meta->getString("formspec") != "" && !random_input
3492                                 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3493                         infostream << "Launching custom inventory view" << std::endl;
3494
3495                         InventoryLocation inventoryloc;
3496                         inventoryloc.setNodeMeta(nodepos);
3497
3498                         NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3499                                 &client->getEnv().getClientMap(), nodepos);
3500                         TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3501
3502                         create_formspec_menu(&current_formspec, client, gamedef,
3503                                              texture_src, device, fs_src, txt_dst, client);
3504
3505                         current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3506                 } else {
3507                         // Report right click to server
3508
3509                         camera->setDigging(1);  // right click animation (always shown for feedback)
3510
3511                         // If the wielded item has node placement prediction,
3512                         // make that happen
3513                         bool placed = nodePlacementPrediction(*client,
3514                                         playeritem_def,
3515                                         nodepos, neighbourpos);
3516
3517                         if (placed) {
3518                                 // Report to server
3519                                 client->interact(3, pointed);
3520                                 // Read the sound
3521                                 soundmaker->m_player_rightpunch_sound =
3522                                                 playeritem_def.sound_place;
3523                         } else {
3524                                 soundmaker->m_player_rightpunch_sound =
3525                                                 SimpleSoundSpec();
3526                         }
3527
3528                         if (playeritem_def.node_placement_prediction == "" ||
3529                                         nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable)
3530                                 client->interact(3, pointed); // Report to server
3531                 }
3532         }
3533 }
3534
3535
3536 void Game::handlePointingAtObject(GameRunData *runData,
3537                 const PointedThing &pointed,
3538                 const ItemStack &playeritem,
3539                 const v3f &player_position,
3540                 bool show_debug)
3541 {
3542         infotext = narrow_to_wide(runData->selected_object->infoText());
3543
3544         if (infotext == L"" && show_debug) {
3545                 infotext = narrow_to_wide(runData->selected_object->debugInfoText());
3546         }
3547
3548         if (input->getLeftState()) {
3549                 bool do_punch = false;
3550                 bool do_punch_damage = false;
3551
3552                 if (runData->object_hit_delay_timer <= 0.0) {
3553                         do_punch = true;
3554                         do_punch_damage = true;
3555                         runData->object_hit_delay_timer = object_hit_delay;
3556                 }
3557
3558                 if (input->getLeftClicked())
3559                         do_punch = true;
3560
3561                 if (do_punch) {
3562                         infostream << "Left-clicked object" << std::endl;
3563                         runData->left_punch = true;
3564                 }
3565
3566                 if (do_punch_damage) {
3567                         // Report direct punch
3568                         v3f objpos = runData->selected_object->getPosition();
3569                         v3f dir = (objpos - player_position).normalize();
3570
3571                         bool disable_send = runData->selected_object->directReportPunch(
3572                                         dir, &playeritem, runData->time_from_last_punch);
3573                         runData->time_from_last_punch = 0;
3574
3575                         if (!disable_send)
3576                                 client->interact(0, pointed);
3577                 }
3578         } else if (input->getRightClicked()) {
3579                 infostream << "Right-clicked object" << std::endl;
3580                 client->interact(3, pointed);  // place
3581         }
3582 }
3583
3584
3585 void Game::handleDigging(GameRunData *runData,
3586                 const PointedThing &pointed, const v3s16 &nodepos,
3587                 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3588 {
3589         if (!runData->digging) {
3590                 infostream << "Started digging" << std::endl;
3591                 client->interact(0, pointed);
3592                 runData->digging = true;
3593                 runData->ldown_for_dig = true;
3594         }
3595
3596         LocalPlayer *player = client->getEnv().getLocalPlayer();
3597         ClientMap &map = client->getEnv().getClientMap();
3598         MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3599
3600         // NOTE: Similar piece of code exists on the server side for
3601         // cheat detection.
3602         // Get digging parameters
3603         DigParams params = getDigParams(nodedef_manager->get(n).groups,
3604                         &playeritem_toolcap);
3605
3606         // If can't dig, try hand
3607         if (!params.diggable) {
3608                 const ItemDefinition &hand = itemdef_manager->get("");
3609                 const ToolCapabilities *tp = hand.tool_capabilities;
3610
3611                 if (tp)
3612                         params = getDigParams(nodedef_manager->get(n).groups, tp);
3613         }
3614
3615         if (params.diggable == false) {
3616                 // I guess nobody will wait for this long
3617                 runData->dig_time_complete = 10000000.0;
3618         } else {
3619                 runData->dig_time_complete = params.time;
3620
3621                 if (m_cache_enable_particles) {
3622                         const ContentFeatures &features =
3623                                         client->getNodeDefManager()->get(n);
3624                         addPunchingParticles(gamedef, smgr, player,
3625                                         client->getEnv(), nodepos, features.tiles);
3626                 }
3627         }
3628
3629         if (runData->dig_time_complete >= 0.001) {
3630                 runData->dig_index = (float)crack_animation_length
3631                                 * runData->dig_time
3632                                 / runData->dig_time_complete;
3633         } else {
3634                 // This is for torches
3635                 runData->dig_index = crack_animation_length;
3636         }
3637
3638         SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3639
3640         if (sound_dig.exists() && params.diggable) {
3641                 if (sound_dig.name == "__group") {
3642                         if (params.main_group != "") {
3643                                 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3644                                 soundmaker->m_player_leftpunch_sound.name =
3645                                                 std::string("default_dig_") +
3646                                                 params.main_group;
3647                         }
3648                 } else {
3649                         soundmaker->m_player_leftpunch_sound = sound_dig;
3650                 }
3651         }
3652
3653         // Don't show cracks if not diggable
3654         if (runData->dig_time_complete >= 100000.0) {
3655         } else if (runData->dig_index < crack_animation_length) {
3656                 //TimeTaker timer("client.setTempMod");
3657                 //infostream<<"dig_index="<<dig_index<<std::endl;
3658                 client->setCrack(runData->dig_index, nodepos);
3659         } else {
3660                 infostream << "Digging completed" << std::endl;
3661                 client->interact(2, pointed);
3662                 client->setCrack(-1, v3s16(0, 0, 0));
3663                 bool is_valid_position;
3664                 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3665                 if (is_valid_position)
3666                         client->removeNode(nodepos);
3667
3668                 if (m_cache_enable_particles) {
3669                         const ContentFeatures &features =
3670                                 client->getNodeDefManager()->get(wasnode);
3671                         addDiggingParticles
3672                         (gamedef, smgr, player, client->getEnv(),
3673                          nodepos, features.tiles);
3674                 }
3675
3676                 runData->dig_time = 0;
3677                 runData->digging = false;
3678
3679                 runData->nodig_delay_timer =
3680                                 runData->dig_time_complete / (float)crack_animation_length;
3681
3682                 // We don't want a corresponding delay to
3683                 // very time consuming nodes
3684                 if (runData->nodig_delay_timer > 0.3)
3685                         runData->nodig_delay_timer = 0.3;
3686
3687                 // We want a slight delay to very little
3688                 // time consuming nodes
3689                 const float mindelay = 0.15;
3690
3691                 if (runData->nodig_delay_timer < mindelay)
3692                         runData->nodig_delay_timer = mindelay;
3693
3694                 // Send event to trigger sound
3695                 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3696                 gamedef->event()->put(e);
3697         }
3698
3699         if (runData->dig_time_complete < 100000.0) {
3700                 runData->dig_time += dtime;
3701         } else {
3702                 runData->dig_time = 0;
3703                 client->setCrack(-1, nodepos);
3704         }
3705
3706         camera->setDigging(0);  // left click animation
3707 }
3708
3709
3710 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3711                 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3712                 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3713 {
3714         LocalPlayer *player = client->getEnv().getLocalPlayer();
3715
3716         /*
3717                 Fog range
3718         */
3719
3720         if (draw_control->range_all) {
3721                 runData->fog_range = 100000 * BS;
3722         } else {
3723                 runData->fog_range = draw_control->wanted_range * BS
3724                                 + 0.0 * MAP_BLOCKSIZE * BS;
3725                 runData->fog_range = MYMIN(
3726                                 runData->fog_range,
3727                                 (draw_control->farthest_drawn + 20) * BS);
3728                 runData->fog_range *= 0.9;
3729         }
3730
3731         /*
3732                 Calculate general brightness
3733         */
3734         u32 daynight_ratio = client->getEnv().getDayNightRatio();
3735         float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3736         float direct_brightness;
3737         bool sunlight_seen;
3738
3739         if (g_settings->getBool("free_move")) {
3740                 direct_brightness = time_brightness;
3741                 sunlight_seen = true;
3742         } else {
3743                 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3744                 float old_brightness = sky->getBrightness();
3745                 direct_brightness = client->getEnv().getClientMap()
3746                                 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3747                                         daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3748                                     / 255.0;
3749         }
3750
3751         float time_of_day = runData->time_of_day;
3752         float time_of_day_smooth = runData->time_of_day_smooth;
3753
3754         time_of_day = client->getEnv().getTimeOfDayF();
3755
3756         const float maxsm = 0.05;
3757         const float todsm = 0.05;
3758
3759         if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3760                         fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3761                         fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3762                 time_of_day_smooth = time_of_day;
3763
3764         if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3765                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3766                                 + (time_of_day + 1.0) * todsm;
3767         else
3768                 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3769                                 + time_of_day * todsm;
3770
3771         runData->time_of_day = time_of_day;
3772         runData->time_of_day_smooth = time_of_day_smooth;
3773
3774         sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3775                         sunlight_seen, camera->getCameraMode(), player->getYaw(),
3776                         player->getPitch());
3777
3778         /*
3779                 Update clouds
3780         */
3781         if (clouds) {
3782                 v3f player_position = player->getPosition();
3783                 if (sky->getCloudsVisible()) {
3784                         clouds->setVisible(true);
3785                         clouds->step(dtime);
3786                         clouds->update(v2f(player_position.X, player_position.Z),
3787                                        sky->getCloudColor());
3788                 } else {
3789                         clouds->setVisible(false);
3790                 }
3791         }
3792
3793         /*
3794                 Update particles
3795         */
3796
3797         allparticles_step(dtime);
3798         allparticlespawners_step(dtime, client->getEnv());
3799
3800         /*
3801                 Fog
3802         */
3803
3804         if (m_cache_enable_fog && !flags.force_fog_off) {
3805                 driver->setFog(
3806                                 sky->getBgColor(),
3807                                 video::EFT_FOG_LINEAR,
3808                                 runData->fog_range * 0.4,
3809                                 runData->fog_range * 1.0,
3810                                 0.01,
3811                                 false, // pixel fog
3812                                 false // range fog
3813                 );
3814         } else {
3815                 driver->setFog(
3816                                 sky->getBgColor(),
3817                                 video::EFT_FOG_LINEAR,
3818                                 100000 * BS,
3819                                 110000 * BS,
3820                                 0.01,
3821                                 false, // pixel fog
3822                                 false // range fog
3823                 );
3824         }
3825
3826         /*
3827                 Get chat messages from client
3828         */
3829
3830         v2u32 screensize = driver->getScreenSize();
3831
3832         updateChat(*client, dtime, flags.show_debug, screensize,
3833                         flags.show_chat, runData->profiler_current_page,
3834                         *chat_backend, guitext_chat);
3835
3836         /*
3837                 Inventory
3838         */
3839
3840         if (client->getPlayerItem() != runData->new_playeritem)
3841                 client->selectPlayerItem(runData->new_playeritem);
3842
3843         // Update local inventory if it has changed
3844         if (client->getLocalInventoryUpdated()) {
3845                 //infostream<<"Updating local inventory"<<std::endl;
3846                 client->getLocalInventory(*local_inventory);
3847                 runData->update_wielded_item_trigger = true;
3848         }
3849
3850         if (runData->update_wielded_item_trigger) {
3851                 // Update wielded tool
3852                 InventoryList *mlist = local_inventory->getList("main");
3853
3854                 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
3855                         ItemStack item = mlist->getItem(client->getPlayerItem());
3856                         camera->wield(item);
3857                 }
3858                 runData->update_wielded_item_trigger = false;
3859         }
3860
3861         /*
3862                 Update block draw list every 200ms or when camera direction has
3863                 changed much
3864         */
3865         runData->update_draw_list_timer += dtime;
3866
3867         v3f camera_direction = camera->getDirection();
3868         if (runData->update_draw_list_timer >= 0.2
3869                         || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
3870                         || flags.camera_offset_changed) {
3871                 runData->update_draw_list_timer = 0;
3872                 client->getEnv().getClientMap().updateDrawList(driver);
3873                 runData->update_draw_list_last_cam_dir = camera_direction;
3874         }
3875
3876         updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
3877
3878         /*
3879            make sure menu is on top
3880            1. Delete formspec menu reference if menu was removed
3881            2. Else, make sure formspec menu is on top
3882         */
3883         if (current_formspec) {
3884                 if (current_formspec->getReferenceCount() == 1) {
3885                         current_formspec->drop();
3886                         current_formspec = NULL;
3887                 } else if (!noMenuActive()) {
3888                         guiroot->bringToFront(current_formspec);
3889                 }
3890         }
3891
3892         /*
3893                 Drawing begins
3894         */
3895
3896         video::SColor skycolor = sky->getSkyColor();
3897
3898         TimeTaker tt_draw("mainloop: draw");
3899         {
3900                 TimeTaker timer("beginScene");
3901                 driver->beginScene(true, true, skycolor);
3902                 stats->beginscenetime = timer.stop(true);
3903         }
3904
3905         draw_scene(driver, smgr, *camera, *client, player, *hud, guienv,
3906                         highlight_boxes, screensize, skycolor, flags.show_hud);
3907
3908         /*
3909                 Profiler graph
3910         */
3911         if (flags.show_profiler_graph)
3912                 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
3913
3914         /*
3915                 Damage flash
3916         */
3917         if (runData->damage_flash > 0.0) {
3918                 video::SColor color(std::min(runData->damage_flash, 180.0f),
3919                                 180,
3920                                 0,
3921                                 0);
3922                 driver->draw2DRectangle(color,
3923                                         core::rect<s32>(0, 0, screensize.X, screensize.Y),
3924                                         NULL);
3925
3926                 runData->damage_flash -= 100.0 * dtime;
3927         }
3928
3929         /*
3930                 Damage camera tilt
3931         */
3932         if (player->hurt_tilt_timer > 0.0) {
3933                 player->hurt_tilt_timer -= dtime * 5;
3934
3935                 if (player->hurt_tilt_timer < 0)
3936                         player->hurt_tilt_strength = 0;
3937         }
3938
3939         /*
3940                 End scene
3941         */
3942         {
3943                 TimeTaker timer("endScene");
3944                 driver->endScene();
3945                 stats->endscenetime = timer.stop(true);
3946         }
3947
3948         stats->drawtime = tt_draw.stop(true);
3949         g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
3950 }
3951
3952
3953 void Game::updateGui(float *statustext_time, const RunStats &stats,
3954                 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
3955                 const CameraOrientation &cam)
3956 {
3957         v2u32 screensize = driver->getScreenSize();
3958         LocalPlayer *player = client->getEnv().getLocalPlayer();
3959         v3f player_position = player->getPosition();
3960
3961         if (flags.show_debug) {
3962                 static float drawtime_avg = 0;
3963                 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
3964
3965                 u16 fps = 1.0 / stats.dtime_jitter.avg;
3966                 //s32 fps = driver->getFPS();
3967
3968                 std::ostringstream os(std::ios_base::binary);
3969                 os << std::fixed
3970                    << "Minetest " << minetest_version_hash
3971                    << " FPS = " << fps
3972                    << " (R: range_all=" << draw_control->range_all << ")"
3973                    << std::setprecision(0)
3974                    << " drawtime = " << drawtime_avg
3975                    << std::setprecision(1)
3976                    << ", dtime_jitter = "
3977                    << (stats.dtime_jitter.max_fraction * 100.0) << " %"
3978                    << std::setprecision(1)
3979                    << ", v_range = " << draw_control->wanted_range
3980                    << std::setprecision(3)
3981                    << ", RTT = " << client->getRTT();
3982                 guitext->setText(narrow_to_wide(os.str()).c_str());
3983                 guitext->setVisible(true);
3984         } else if (flags.show_hud || flags.show_chat) {
3985                 std::ostringstream os(std::ios_base::binary);
3986                 os << "Minetest " << minetest_version_hash;
3987                 guitext->setText(narrow_to_wide(os.str()).c_str());
3988                 guitext->setVisible(true);
3989         } else {
3990                 guitext->setVisible(false);
3991         }
3992
3993         if (guitext->isVisible()) {
3994                 core::rect<s32> rect(
3995                                 5,              5,
3996                                 screensize.X,   5 + g_fontengine->getTextHeight()
3997                 );
3998                 guitext->setRelativePosition(rect);
3999         }
4000
4001         if (flags.show_debug) {
4002                 std::ostringstream os(std::ios_base::binary);
4003                 os << std::setprecision(1) << std::fixed
4004                    << "(" << (player_position.X / BS)
4005                    << ", " << (player_position.Y / BS)
4006                    << ", " << (player_position.Z / BS)
4007                    << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4008                    << ") (seed = " << ((u64)client->getMapSeed())
4009                    << ")";
4010
4011                 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4012                         ClientMap &map = client->getEnv().getClientMap();
4013                         const INodeDefManager *nodedef = client->getNodeDefManager();
4014                         MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4015                         if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4016                                 const ContentFeatures &features = nodedef->get(n);
4017                                 os << " (pointing_at = " << nodedef->get(n).name
4018                                    << " - " << features.tiledef[0].name.c_str()
4019                                    << ")";
4020                         }
4021                 }
4022
4023                 guitext2->setText(narrow_to_wide(os.str()).c_str());
4024                 guitext2->setVisible(true);
4025
4026                 core::rect<s32> rect(
4027                                 5,             5 + g_fontengine->getTextHeight(),
4028                                 screensize.X,  5 + g_fontengine->getTextHeight() * 2
4029                 );
4030                 guitext2->setRelativePosition(rect);
4031         } else {
4032                 guitext2->setVisible(false);
4033         }
4034
4035         guitext_info->setText(infotext.c_str());
4036         guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4037
4038         float statustext_time_max = 1.5;
4039
4040         if (!statustext.empty()) {
4041                 *statustext_time += dtime;
4042
4043                 if (*statustext_time >= statustext_time_max) {
4044                         statustext = L"";
4045                         *statustext_time = 0;
4046                 }
4047         }
4048
4049         guitext_status->setText(statustext.c_str());
4050         guitext_status->setVisible(!statustext.empty());
4051
4052         if (!statustext.empty()) {
4053                 s32 status_width  = guitext_status->getTextWidth();
4054                 s32 status_height = guitext_status->getTextHeight();
4055                 s32 status_y = screensize.Y - 150;
4056                 s32 status_x = (screensize.X - status_width) / 2;
4057                 core::rect<s32> rect(
4058                                 status_x , status_y - status_height,
4059                                 status_x + status_width, status_y
4060                 );
4061                 guitext_status->setRelativePosition(rect);
4062
4063                 // Fade out
4064                 video::SColor initial_color(255, 0, 0, 0);
4065
4066                 if (guienv->getSkin())
4067                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4068
4069                 video::SColor final_color = initial_color;
4070                 final_color.setAlpha(0);
4071                 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4072                                 initial_color, final_color,
4073                                 pow(*statustext_time / statustext_time_max, 2.0f));
4074                 guitext_status->setOverrideColor(fade_color);
4075                 guitext_status->enableOverrideColor(true);
4076         }
4077 }
4078
4079
4080 /* Log times and stuff for visualization */
4081 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4082 {
4083         Profiler::GraphValues values;
4084         g_profiler->graphGet(values);
4085         graph->put(values);
4086 }
4087
4088
4089
4090 /****************************************************************************
4091  Misc
4092  ****************************************************************************/
4093
4094 /* On some computers framerate doesn't seem to be automatically limited
4095  */
4096 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4097 {
4098         // not using getRealTime is necessary for wine
4099         device->getTimer()->tick(); // Maker sure device time is up-to-date
4100         u32 time = device->getTimer()->getTime();
4101
4102         u32 last_time = fps_timings->last_time;
4103
4104         if (time > last_time)  // Make sure time hasn't overflowed
4105                 fps_timings->busy_time = time - last_time;
4106         else
4107                 fps_timings->busy_time = 0;
4108
4109         u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4110                         ? g_settings->getFloat("pause_fps_max")
4111                         : g_settings->getFloat("fps_max"));
4112
4113         if (fps_timings->busy_time < frametime_min) {
4114                 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4115                 device->sleep(fps_timings->sleep_time);
4116         } else {
4117                 fps_timings->sleep_time = 0;
4118         }
4119
4120         /* Get the new value of the device timer. Note that device->sleep() may
4121          * not sleep for the entire requested time as sleep may be interrupted and
4122          * therefore it is arguably more accurate to get the new time from the
4123          * device rather than calculating it by adding sleep_time to time.
4124          */
4125
4126         device->getTimer()->tick(); // Update device timer
4127         time = device->getTimer()->getTime();
4128
4129         if (time > last_time)  // Make sure last_time hasn't overflowed
4130                 *dtime = (time - last_time) / 1000.0;
4131         else
4132                 *dtime = 0;
4133
4134         fps_timings->last_time = time;
4135 }
4136
4137
4138 void Game::showOverlayMessage(const char *msg, float dtime,
4139                 int percent, bool draw_clouds)
4140 {
4141         wchar_t *text = wgettext(msg);
4142         draw_load_screen(text, device, guienv, dtime, percent, draw_clouds);
4143         delete[] text;
4144 }
4145
4146
4147 /****************************************************************************
4148  Shutdown / cleanup
4149  ****************************************************************************/
4150
4151 void Game::extendedResourceCleanup()
4152 {
4153         // Extended resource accounting
4154         infostream << "Irrlicht resources after cleanup:" << std::endl;
4155         infostream << "\tRemaining meshes   : "
4156                    << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4157         infostream << "\tRemaining textures : "
4158                    << driver->getTextureCount() << std::endl;
4159
4160         for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4161                 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4162                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4163                            << std::endl;
4164         }
4165
4166         clearTextureNameCache();
4167         infostream << "\tRemaining materials: "
4168                << driver-> getMaterialRendererCount()
4169                        << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4170 }
4171
4172
4173
4174 /****************************************************************************
4175  extern function for launching the game
4176  ****************************************************************************/
4177
4178 void the_game(bool *kill,
4179                 bool random_input,
4180                 InputHandler *input,
4181                 IrrlichtDevice *device,
4182
4183                 const std::string &map_dir,
4184                 const std::string &playername,
4185                 const std::string &password,
4186                 const std::string &address,         // If empty local server is created
4187                 u16 port,
4188
4189                 std::wstring &error_message,
4190                 ChatBackend &chat_backend,
4191                 const SubgameSpec &gamespec,        // Used for local game
4192                 bool simple_singleplayer_mode)
4193 {
4194         Game game;
4195
4196         /* Make a copy of the server address because if a local singleplayer server
4197          * is created then this is updated and we don't want to change the value
4198          * passed to us by the calling function
4199          */
4200         std::string server_address = address;
4201
4202         try {
4203
4204                 if (game.startup(kill, random_input, input, device, map_dir,
4205                                         playername, password, &server_address, port,
4206                                         &error_message, &chat_backend, gamespec,
4207                                         simple_singleplayer_mode)) {
4208
4209                         game.run();
4210                         game.shutdown();
4211                 }
4212
4213         } catch (SerializationError &e) {
4214                 error_message = L"A serialization error occurred:\n"
4215                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
4216                                 L" running a different version of Minetest.";
4217                 errorstream << wide_to_narrow(error_message) << std::endl;
4218         } catch (ServerError &e) {
4219                 error_message = narrow_to_wide(e.what());
4220                 errorstream << "ServerError: " << e.what() << std::endl;
4221         } catch (ModError &e) {
4222                 errorstream << "ModError: " << e.what() << std::endl;
4223                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
4224         }
4225 }