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