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