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