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