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