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