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