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