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