Add texture bumpmapping feature.
[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                 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer, 1);
811         }
812 };
813
814 bool nodePlacementPrediction(Client &client,
815                 const ItemDefinition &playeritem_def,
816                 v3s16 nodepos, v3s16 neighbourpos)
817 {
818         std::string prediction = playeritem_def.node_placement_prediction;
819         INodeDefManager *nodedef = client.ndef();
820         ClientMap &map = client.getEnv().getClientMap();
821
822         if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
823         {
824                 verbosestream<<"Node placement prediction for "
825                                 <<playeritem_def.name<<" is "
826                                 <<prediction<<std::endl;
827                 v3s16 p = neighbourpos;
828                 // Place inside node itself if buildable_to
829                 try{
830                         MapNode n_under = map.getNode(nodepos);
831                         if(nodedef->get(n_under).buildable_to)
832                                 p = nodepos;
833                         else if (!nodedef->get(map.getNode(p)).buildable_to)
834                                 return false;
835                 }catch(InvalidPositionException &e){}
836                 // Find id of predicted node
837                 content_t id;
838                 bool found = nodedef->getId(prediction, id);
839                 if(!found){
840                         errorstream<<"Node placement prediction failed for "
841                                         <<playeritem_def.name<<" (places "
842                                         <<prediction
843                                         <<") - Name not known"<<std::endl;
844                         return false;
845                 }
846                 // Predict param2 for facedir and wallmounted nodes
847                 u8 param2 = 0;
848                 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
849                         v3s16 dir = nodepos - neighbourpos;
850                         if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
851                                 param2 = dir.Y < 0 ? 1 : 0;
852                         } else if(abs(dir.X) > abs(dir.Z)){
853                                 param2 = dir.X < 0 ? 3 : 2;
854                         } else {
855                                 param2 = dir.Z < 0 ? 5 : 4;
856                         }
857                 }
858                 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
859                         v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
860                         if(abs(dir.X) > abs(dir.Z)){
861                                 param2 = dir.X < 0 ? 3 : 1;
862                         } else {
863                                 param2 = dir.Z < 0 ? 2 : 0;
864                         }
865                 }
866                 assert(param2 >= 0 && param2 <= 5);
867                 //Check attachment if node is in group attached_node
868                 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
869                         static v3s16 wallmounted_dirs[8] = {
870                                 v3s16(0,1,0),
871                                 v3s16(0,-1,0),
872                                 v3s16(1,0,0),
873                                 v3s16(-1,0,0),
874                                 v3s16(0,0,1),
875                                 v3s16(0,0,-1),
876                         };
877                         v3s16 pp;
878                         if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
879                                 pp = p + wallmounted_dirs[param2];
880                         else
881                                 pp = p + v3s16(0,-1,0);
882                         if(!nodedef->get(map.getNode(pp)).walkable)
883                                 return false;
884                 }
885                 // Add node to client map
886                 MapNode n(id, 0, param2);
887                 try{
888                         // This triggers the required mesh update too
889                         client.addNode(p, n);
890                         return true;
891                 }catch(InvalidPositionException &e){
892                         errorstream<<"Node placement prediction failed for "
893                                         <<playeritem_def.name<<" (places "
894                                         <<prediction
895                                         <<") - Position not loaded"<<std::endl;
896                 }
897         }
898         return false;
899 }
900
901
902 void the_game(
903         bool &kill,
904         bool random_input,
905         InputHandler *input,
906         IrrlichtDevice *device,
907         gui::IGUIFont* font,
908         std::string map_dir,
909         std::string playername,
910         std::string password,
911         std::string address, // If "", local server is used
912         u16 port,
913         std::wstring &error_message,
914         std::string configpath,
915         ChatBackend &chat_backend,
916         const SubgameSpec &gamespec, // Used for local game,
917         bool simple_singleplayer_mode
918 )
919 {
920         FormspecFormSource* current_formspec = 0;
921         TextDestPlayerInventory* current_textdest = 0;
922         video::IVideoDriver* driver = device->getVideoDriver();
923         scene::ISceneManager* smgr = device->getSceneManager();
924         
925         // Calculate text height using the font
926         u32 text_height = font->getDimension(L"Random test string").Height;
927
928         v2u32 last_screensize(0,0);
929         v2u32 screensize = driver->getScreenSize();
930         
931         /*
932                 Draw "Loading" screen
933         */
934
935         {
936                 wchar_t* text = wgettext("Loading...");
937                 draw_load_screen(text, device, font,0,0);
938                 delete[] text;
939         }
940         
941         // Create texture source
942         IWritableTextureSource *tsrc = createTextureSource(device);
943         
944         // Create shader source
945         IWritableShaderSource *shsrc = createShaderSource(device);
946         
947         // These will be filled by data received from the server
948         // Create item definition manager
949         IWritableItemDefManager *itemdef = createItemDefManager();
950         // Create node definition manager
951         IWritableNodeDefManager *nodedef = createNodeDefManager();
952         
953         // Sound fetcher (useful when testing)
954         GameOnDemandSoundFetcher soundfetcher;
955
956         // Sound manager
957         ISoundManager *sound = NULL;
958         bool sound_is_dummy = false;
959 #if USE_SOUND
960         if(g_settings->getBool("enable_sound")){
961                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
962                 sound = createOpenALSoundManager(&soundfetcher);
963                 if(!sound)
964                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
965         } else {
966                 infostream<<"Sound disabled."<<std::endl;
967         }
968 #endif
969         if(!sound){
970                 infostream<<"Using dummy audio."<<std::endl;
971                 sound = &dummySoundManager;
972                 sound_is_dummy = true;
973         }
974
975         Server *server = NULL;
976
977         try{
978         // Event manager
979         EventManager eventmgr;
980
981         // Sound maker
982         SoundMaker soundmaker(sound, nodedef);
983         soundmaker.registerReceiver(&eventmgr);
984         
985         // Add chat log output for errors to be shown in chat
986         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
987
988         // Create UI for modifying quicktune values
989         QuicktuneShortcutter quicktune;
990
991         /*
992                 Create server.
993         */
994
995         if(address == ""){
996                 wchar_t* text = wgettext("Creating server....");
997                 draw_load_screen(text, device, font,0,25);
998                 delete[] text;
999                 infostream<<"Creating server"<<std::endl;
1000                 server = new Server(map_dir, configpath, gamespec,
1001                                 simple_singleplayer_mode);
1002                 server->start(port);
1003         }
1004
1005         do{ // Client scope (breakable do-while(0))
1006         
1007         /*
1008                 Create client
1009         */
1010
1011         {
1012                 wchar_t* text = wgettext("Creating client...");
1013                 draw_load_screen(text, device, font,0,50);
1014                 delete[] text;
1015         }
1016         infostream<<"Creating client"<<std::endl;
1017         
1018         MapDrawControl draw_control;
1019         
1020         {
1021                 wchar_t* text = wgettext("Resolving address...");
1022                 draw_load_screen(text, device, font,0,75);
1023                 delete[] text;
1024         }
1025         Address connect_address(0,0,0,0, port);
1026         try{
1027                 if(address == "")
1028                 {
1029                         //connect_address.Resolve("localhost");
1030                         if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
1031                         {
1032                                 IPv6AddressBytes addr_bytes;
1033                                 addr_bytes.bytes[15] = 1;
1034                                 connect_address.setAddress(&addr_bytes);
1035                         }
1036                         else
1037                         {
1038                                 connect_address.setAddress(127,0,0,1);
1039                         }
1040                 }
1041                 else
1042                         connect_address.Resolve(address.c_str());
1043         }
1044         catch(ResolveError &e)
1045         {
1046                 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1047                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1048                 // Break out of client scope
1049                 break;
1050         }
1051         
1052         /*
1053                 Create client
1054         */
1055         Client client(device, playername.c_str(), password, draw_control,
1056                 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1057                 connect_address.isIPv6());
1058         
1059         // Client acts as our GameDef
1060         IGameDef *gamedef = &client;
1061
1062         /*
1063                 Attempt to connect to the server
1064         */
1065         
1066         infostream<<"Connecting to server at ";
1067         connect_address.print(&infostream);
1068         infostream<<std::endl;
1069         client.connect(connect_address);
1070         
1071         /*
1072                 Wait for server to accept connection
1073         */
1074         bool could_connect = false;
1075         bool connect_aborted = false;
1076         try{
1077                 float time_counter = 0.0;
1078                 input->clear();
1079                 float fps_max = g_settings->getFloat("fps_max");
1080                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1081                 u32 lasttime = device->getTimer()->getTime();
1082                 while(device->run())
1083                 {
1084                         f32 dtime = 0.033; // in seconds
1085                         if (cloud_menu_background) {
1086                                 u32 time = device->getTimer()->getTime();
1087                                 if(time > lasttime)
1088                                         dtime = (time - lasttime) / 1000.0;
1089                                 else
1090                                         dtime = 0;
1091                                 lasttime = time;
1092                         }
1093                         // Update client and server
1094                         client.step(dtime);
1095                         if(server != NULL)
1096                                 server->step(dtime);
1097                         
1098                         // End condition
1099                         if(client.connectedAndInitialized()){
1100                                 could_connect = true;
1101                                 break;
1102                         }
1103                         // Break conditions
1104                         if(client.accessDenied()){
1105                                 error_message = L"Access denied. Reason: "
1106                                                 +client.accessDeniedReason();
1107                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1108                                 break;
1109                         }
1110                         if(input->wasKeyDown(EscapeKey)){
1111                                 connect_aborted = true;
1112                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1113                                 break;
1114                         }
1115                         
1116                         // Display status
1117                         {
1118                                 wchar_t* text = wgettext("Connecting to server...");
1119                                 draw_load_screen(text, device, font, dtime, 100);
1120                                 delete[] text;
1121                         }
1122                         
1123                         // On some computers framerate doesn't seem to be
1124                         // automatically limited
1125                         if (cloud_menu_background) {
1126                                 // Time of frame without fps limit
1127                                 float busytime;
1128                                 u32 busytime_u32;
1129                                 // not using getRealTime is necessary for wine
1130                                 u32 time = device->getTimer()->getTime();
1131                                 if(time > lasttime)
1132                                         busytime_u32 = time - lasttime;
1133                                 else
1134                                         busytime_u32 = 0;
1135                                 busytime = busytime_u32 / 1000.0;
1136
1137                                 // FPS limiter
1138                                 u32 frametime_min = 1000./fps_max;
1139
1140                                 if(busytime_u32 < frametime_min) {
1141                                         u32 sleeptime = frametime_min - busytime_u32;
1142                                         device->sleep(sleeptime);
1143                                 }
1144                         } else {
1145                                 sleep_ms(25);
1146                         }
1147                         time_counter += dtime;
1148                 }
1149         }
1150         catch(con::PeerNotFoundException &e)
1151         {}
1152         
1153         /*
1154                 Handle failure to connect
1155         */
1156         if(!could_connect){
1157                 if(error_message == L"" && !connect_aborted){
1158                         error_message = L"Connection failed";
1159                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1160                 }
1161                 // Break out of client scope
1162                 break;
1163         }
1164         
1165         /*
1166                 Wait until content has been received
1167         */
1168         bool got_content = false;
1169         bool content_aborted = false;
1170         {
1171                 float time_counter = 0.0;
1172                 input->clear();
1173                 float fps_max = g_settings->getFloat("fps_max");
1174                 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1175                 u32 lasttime = device->getTimer()->getTime();
1176                 while(device->run())
1177                 {
1178                         f32 dtime = 0.033; // in seconds
1179                         if (cloud_menu_background) {
1180                                 u32 time = device->getTimer()->getTime();
1181                                 if(time > lasttime)
1182                                         dtime = (time - lasttime) / 1000.0;
1183                                 else
1184                                         dtime = 0;
1185                                 lasttime = time;
1186                         }
1187                         // Update client and server
1188                         client.step(dtime);
1189                         if(server != NULL)
1190                                 server->step(dtime);
1191                         
1192                         // End condition
1193                         if(client.texturesReceived() &&
1194                                         client.itemdefReceived() &&
1195                                         client.nodedefReceived()){
1196                                 got_content = true;
1197                                 break;
1198                         }
1199                         // Break conditions
1200                         if(!client.connectedAndInitialized()){
1201                                 error_message = L"Client disconnected";
1202                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1203                                 break;
1204                         }
1205                         if(input->wasKeyDown(EscapeKey)){
1206                                 content_aborted = true;
1207                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1208                                 break;
1209                         }
1210                         
1211                         // Display status
1212                         int progress=0;
1213                         if (!client.itemdefReceived())
1214                         {
1215                                 wchar_t* text = wgettext("Item definitions...");
1216                                 progress = 0;
1217                                 draw_load_screen(text, device, font, dtime, progress);
1218                                 delete[] text;
1219                         }
1220                         else if (!client.nodedefReceived())
1221                         {
1222                                 wchar_t* text = wgettext("Node definitions...");
1223                                 progress = 25;
1224                                 draw_load_screen(text, device, font, dtime, progress);
1225                                 delete[] text;
1226                         }
1227                         else
1228                         {
1229                                 wchar_t* text = wgettext("Media...");
1230                                 progress = 50+client.mediaReceiveProgress()*50+0.5;
1231                                 draw_load_screen(text, device, font, dtime, progress);
1232                                 delete[] text;
1233                         }
1234                         
1235                         // On some computers framerate doesn't seem to be
1236                         // automatically limited
1237                         if (cloud_menu_background) {
1238                                 // Time of frame without fps limit
1239                                 float busytime;
1240                                 u32 busytime_u32;
1241                                 // not using getRealTime is necessary for wine
1242                                 u32 time = device->getTimer()->getTime();
1243                                 if(time > lasttime)
1244                                         busytime_u32 = time - lasttime;
1245                                 else
1246                                         busytime_u32 = 0;
1247                                 busytime = busytime_u32 / 1000.0;
1248
1249                                 // FPS limiter
1250                                 u32 frametime_min = 1000./fps_max;
1251
1252                                 if(busytime_u32 < frametime_min) {
1253                                         u32 sleeptime = frametime_min - busytime_u32;
1254                                         device->sleep(sleeptime);
1255                                 }
1256                         } else {
1257                                 sleep_ms(25);
1258                         }
1259                         time_counter += dtime;
1260                 }
1261         }
1262
1263         if(!got_content){
1264                 if(error_message == L"" && !content_aborted){
1265                         error_message = L"Something failed";
1266                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1267                 }
1268                 // Break out of client scope
1269                 break;
1270         }
1271
1272         /*
1273                 After all content has been received:
1274                 Update cached textures, meshes and materials
1275         */
1276         client.afterContentReceived(device,font);
1277
1278         /*
1279                 Create the camera node
1280         */
1281         Camera camera(smgr, draw_control, gamedef);
1282         if (!camera.successfullyCreated(error_message))
1283                 return;
1284
1285         f32 camera_yaw = 0; // "right/left"
1286         f32 camera_pitch = 0; // "up/down"
1287
1288         /*
1289                 Clouds
1290         */
1291         
1292         Clouds *clouds = NULL;
1293         if(g_settings->getBool("enable_clouds"))
1294         {
1295                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1296         }
1297
1298         /*
1299                 Skybox thingy
1300         */
1301
1302         Sky *sky = NULL;
1303         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1304         
1305         /*
1306                 FarMesh
1307         */
1308
1309         FarMesh *farmesh = NULL;
1310         if(g_settings->getBool("enable_farmesh"))
1311         {
1312                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1313         }
1314
1315         /*
1316                 A copy of the local inventory
1317         */
1318         Inventory local_inventory(itemdef);
1319
1320         /*
1321                 Find out size of crack animation
1322         */
1323         int crack_animation_length = 5;
1324         {
1325                 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1326                 v2u32 size = t->getOriginalSize();
1327                 crack_animation_length = size.Y / size.X;
1328         }
1329
1330         /*
1331                 Add some gui stuff
1332         */
1333
1334         // First line of debug text
1335         gui::IGUIStaticText *guitext = guienv->addStaticText(
1336                         L"Minetest",
1337                         core::rect<s32>(5, 5, 795, 5+text_height),
1338                         false, false);
1339         // Second line of debug text
1340         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1341                         L"",
1342                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1343                         false, false);
1344         // At the middle of the screen
1345         // Object infos are shown in this
1346         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1347                         L"",
1348                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1349                         false, true);
1350         
1351         // Status text (displays info when showing and hiding GUI stuff, etc.)
1352         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1353                         L"<Status>",
1354                         core::rect<s32>(0,0,0,0),
1355                         false, false);
1356         guitext_status->setVisible(false);
1357         
1358         std::wstring statustext;
1359         float statustext_time = 0;
1360         
1361         // Chat text
1362         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1363                         L"",
1364                         core::rect<s32>(0,0,0,0),
1365                         //false, false); // Disable word wrap as of now
1366                         false, true);
1367         // Remove stale "recent" chat messages from previous connections
1368         chat_backend.clearRecentChat();
1369         // Chat backend and console
1370         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1371         
1372         // Profiler text (size is updated when text is updated)
1373         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1374                         L"<Profiler>",
1375                         core::rect<s32>(0,0,0,0),
1376                         false, false);
1377         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1378         guitext_profiler->setVisible(false);
1379         guitext_profiler->setWordWrap(true);
1380         
1381         /*
1382                 Some statistics are collected in these
1383         */
1384         u32 drawtime = 0;
1385         u32 beginscenetime = 0;
1386         u32 scenetime = 0;
1387         u32 endscenetime = 0;
1388         
1389         float recent_turn_speed = 0.0;
1390         
1391         ProfilerGraph graph;
1392         // Initially clear the profiler
1393         Profiler::GraphValues dummyvalues;
1394         g_profiler->graphGet(dummyvalues);
1395
1396         float nodig_delay_timer = 0.0;
1397         float dig_time = 0.0;
1398         u16 dig_index = 0;
1399         PointedThing pointed_old;
1400         bool digging = false;
1401         bool ldown_for_dig = false;
1402
1403         float damage_flash = 0;
1404         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1405
1406         float jump_timer = 0;
1407         bool reset_jump_timer = false;
1408
1409         const float object_hit_delay = 0.2;
1410         float object_hit_delay_timer = 0.0;
1411         float time_from_last_punch = 10;
1412
1413         float update_draw_list_timer = 0.0;
1414         v3f update_draw_list_last_cam_dir;
1415
1416         bool invert_mouse = g_settings->getBool("invert_mouse");
1417
1418         bool respawn_menu_active = false;
1419         bool update_wielded_item_trigger = false;
1420
1421         bool show_hud = true;
1422         bool show_chat = true;
1423         bool force_fog_off = false;
1424         f32 fog_range = 100*BS;
1425         bool disable_camera_update = false;
1426         bool show_debug = g_settings->getBool("show_debug");
1427         bool show_profiler_graph = false;
1428         u32 show_profiler = 0;
1429         u32 show_profiler_max = 3;  // Number of pages
1430
1431         float time_of_day = 0;
1432         float time_of_day_smooth = 0;
1433
1434         float repeat_rightclick_timer = 0;
1435
1436         /*
1437                 Shader constants
1438         */
1439         shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1440                         sky, &force_fog_off, &fog_range, &client));
1441
1442         /*
1443                 Main loop
1444         */
1445
1446         bool first_loop_after_window_activation = true;
1447
1448         // TODO: Convert the static interval timers to these
1449         // Interval limiter for profiler
1450         IntervalLimiter m_profiler_interval;
1451
1452         // Time is in milliseconds
1453         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1454         // NOTE: So we have to use getTime() and call run()s between them
1455         u32 lasttime = device->getTimer()->getTime();
1456
1457         LocalPlayer* player = client.getEnv().getLocalPlayer();
1458         player->hurt_tilt_timer = 0;
1459         player->hurt_tilt_strength = 0;
1460         
1461         /*
1462                 HUD object
1463         */
1464         Hud hud(driver, guienv, font, text_height,
1465                         gamedef, player, &local_inventory);
1466
1467         for(;;)
1468         {
1469                 if(device->run() == false || kill == true)
1470                         break;
1471
1472                 // Time of frame without fps limit
1473                 float busytime;
1474                 u32 busytime_u32;
1475                 {
1476                         // not using getRealTime is necessary for wine
1477                         u32 time = device->getTimer()->getTime();
1478                         if(time > lasttime)
1479                                 busytime_u32 = time - lasttime;
1480                         else
1481                                 busytime_u32 = 0;
1482                         busytime = busytime_u32 / 1000.0;
1483                 }
1484                 
1485                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1486
1487                 // Necessary for device->getTimer()->getTime()
1488                 device->run();
1489
1490                 /*
1491                         FPS limiter
1492                 */
1493
1494                 {
1495                         float fps_max = g_settings->getFloat("fps_max");
1496                         u32 frametime_min = 1000./fps_max;
1497                         
1498                         if(busytime_u32 < frametime_min)
1499                         {
1500                                 u32 sleeptime = frametime_min - busytime_u32;
1501                                 device->sleep(sleeptime);
1502                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1503                         }
1504                 }
1505
1506                 // Necessary for device->getTimer()->getTime()
1507                 device->run();
1508
1509                 /*
1510                         Time difference calculation
1511                 */
1512                 f32 dtime; // in seconds
1513                 
1514                 u32 time = device->getTimer()->getTime();
1515                 if(time > lasttime)
1516                         dtime = (time - lasttime) / 1000.0;
1517                 else
1518                         dtime = 0;
1519                 lasttime = time;
1520
1521                 g_profiler->graphAdd("mainloop_dtime", dtime);
1522
1523                 /* Run timers */
1524
1525                 if(nodig_delay_timer >= 0)
1526                         nodig_delay_timer -= dtime;
1527                 if(object_hit_delay_timer >= 0)
1528                         object_hit_delay_timer -= dtime;
1529                 time_from_last_punch += dtime;
1530                 
1531                 g_profiler->add("Elapsed time", dtime);
1532                 g_profiler->avg("FPS", 1./dtime);
1533
1534                 /*
1535                         Time average and jitter calculation
1536                 */
1537
1538                 static f32 dtime_avg1 = 0.0;
1539                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1540                 f32 dtime_jitter1 = dtime - dtime_avg1;
1541
1542                 static f32 dtime_jitter1_max_sample = 0.0;
1543                 static f32 dtime_jitter1_max_fraction = 0.0;
1544                 {
1545                         static f32 jitter1_max = 0.0;
1546                         static f32 counter = 0.0;
1547                         if(dtime_jitter1 > jitter1_max)
1548                                 jitter1_max = dtime_jitter1;
1549                         counter += dtime;
1550                         if(counter > 0.0)
1551                         {
1552                                 counter -= 3.0;
1553                                 dtime_jitter1_max_sample = jitter1_max;
1554                                 dtime_jitter1_max_fraction
1555                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1556                                 jitter1_max = 0.0;
1557                         }
1558                 }
1559                 
1560                 /*
1561                         Busytime average and jitter calculation
1562                 */
1563
1564                 static f32 busytime_avg1 = 0.0;
1565                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1566                 f32 busytime_jitter1 = busytime - busytime_avg1;
1567                 
1568                 static f32 busytime_jitter1_max_sample = 0.0;
1569                 static f32 busytime_jitter1_min_sample = 0.0;
1570                 {
1571                         static f32 jitter1_max = 0.0;
1572                         static f32 jitter1_min = 0.0;
1573                         static f32 counter = 0.0;
1574                         if(busytime_jitter1 > jitter1_max)
1575                                 jitter1_max = busytime_jitter1;
1576                         if(busytime_jitter1 < jitter1_min)
1577                                 jitter1_min = busytime_jitter1;
1578                         counter += dtime;
1579                         if(counter > 0.0){
1580                                 counter -= 3.0;
1581                                 busytime_jitter1_max_sample = jitter1_max;
1582                                 busytime_jitter1_min_sample = jitter1_min;
1583                                 jitter1_max = 0.0;
1584                                 jitter1_min = 0.0;
1585                         }
1586                 }
1587
1588                 /*
1589                         Handle miscellaneous stuff
1590                 */
1591                 
1592                 if(client.accessDenied())
1593                 {
1594                         error_message = L"Access denied. Reason: "
1595                                         +client.accessDeniedReason();
1596                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1597                         break;
1598                 }
1599
1600                 if(g_gamecallback->disconnect_requested)
1601                 {
1602                         g_gamecallback->disconnect_requested = false;
1603                         break;
1604                 }
1605
1606                 if(g_gamecallback->changepassword_requested)
1607                 {
1608                         (new GUIPasswordChange(guienv, guiroot, -1,
1609                                 &g_menumgr, &client))->drop();
1610                         g_gamecallback->changepassword_requested = false;
1611                 }
1612
1613                 if(g_gamecallback->changevolume_requested)
1614                 {
1615                         (new GUIVolumeChange(guienv, guiroot, -1,
1616                                 &g_menumgr, &client))->drop();
1617                         g_gamecallback->changevolume_requested = false;
1618                 }
1619
1620                 /* Process TextureSource's queue */
1621                 tsrc->processQueue();
1622
1623                 /* Process ItemDefManager's queue */
1624                 itemdef->processQueue(gamedef);
1625
1626                 /*
1627                         Process ShaderSource's queue
1628                 */
1629                 shsrc->processQueue();
1630
1631                 /*
1632                         Random calculations
1633                 */
1634                 last_screensize = screensize;
1635                 screensize = driver->getScreenSize();
1636                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1637                 //bool screensize_changed = screensize != last_screensize;
1638
1639                         
1640                 // Update HUD values
1641                 hud.screensize    = screensize;
1642                 hud.displaycenter = displaycenter;
1643                 hud.resizeHotbar();
1644                 
1645                 // Hilight boxes collected during the loop and displayed
1646                 std::vector<aabb3f> hilightboxes;
1647                 
1648                 // Info text
1649                 std::wstring infotext;
1650
1651                 /*
1652                         Debug info for client
1653                 */
1654                 {
1655                         static float counter = 0.0;
1656                         counter -= dtime;
1657                         if(counter < 0)
1658                         {
1659                                 counter = 30.0;
1660                                 client.printDebugInfo(infostream);
1661                         }
1662                 }
1663
1664                 /*
1665                         Profiler
1666                 */
1667                 float profiler_print_interval =
1668                                 g_settings->getFloat("profiler_print_interval");
1669                 bool print_to_log = true;
1670                 if(profiler_print_interval == 0){
1671                         print_to_log = false;
1672                         profiler_print_interval = 5;
1673                 }
1674                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1675                 {
1676                         if(print_to_log){
1677                                 infostream<<"Profiler:"<<std::endl;
1678                                 g_profiler->print(infostream);
1679                         }
1680
1681                         update_profiler_gui(guitext_profiler, font, text_height,
1682                                         show_profiler, show_profiler_max);
1683
1684                         g_profiler->clear();
1685                 }
1686
1687                 /*
1688                         Direct handling of user input
1689                 */
1690                 
1691                 // Reset input if window not active or some menu is active
1692                 if(device->isWindowActive() == false
1693                                 || noMenuActive() == false
1694                                 || guienv->hasFocus(gui_chat_console))
1695                 {
1696                         input->clear();
1697                 }
1698                 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1699                 {
1700                         gui_chat_console->closeConsoleAtOnce();
1701                 }
1702
1703                 // Input handler step() (used by the random input generator)
1704                 input->step(dtime);
1705
1706                 // Increase timer for doubleclick of "jump"
1707                 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1708                         jump_timer += dtime;
1709
1710                 /*
1711                         Launch menus and trigger stuff according to keys
1712                 */
1713                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1714                 {
1715                         // drop selected item
1716                         IDropAction *a = new IDropAction();
1717                         a->count = 0;
1718                         a->from_inv.setCurrentPlayer();
1719                         a->from_list = "main";
1720                         a->from_i = client.getPlayerItem();
1721                         client.inventoryAction(a);
1722                 }
1723                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1724                 {
1725                         infostream<<"the_game: "
1726                                         <<"Launching inventory"<<std::endl;
1727                         
1728                         GUIFormSpecMenu *menu =
1729                                 new GUIFormSpecMenu(device, guiroot, -1,
1730                                         &g_menumgr,
1731                                         &client, gamedef);
1732
1733                         InventoryLocation inventoryloc;
1734                         inventoryloc.setCurrentPlayer();
1735
1736                         PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1737                         assert(src);
1738                         menu->setFormSpec(src->getForm(), inventoryloc);
1739                         menu->setFormSource(src);
1740                         menu->setTextDest(new TextDestPlayerInventory(&client));
1741                         menu->drop();
1742                 }
1743                 else if(input->wasKeyDown(EscapeKey))
1744                 {
1745                         infostream<<"the_game: "
1746                                         <<"Launching pause menu"<<std::endl;
1747                         // It will delete itself by itself
1748                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1749                                         &g_menumgr, simple_singleplayer_mode))->drop();
1750
1751                         // Move mouse cursor on top of the disconnect button
1752                         if(simple_singleplayer_mode)
1753                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1754                         else
1755                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1756                 }
1757                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1758                 {
1759                         TextDest *dest = new TextDestChat(&client);
1760
1761                         (new GUITextInputMenu(guienv, guiroot, -1,
1762                                         &g_menumgr, dest,
1763                                         L""))->drop();
1764                 }
1765                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1766                 {
1767                         TextDest *dest = new TextDestChat(&client);
1768
1769                         (new GUITextInputMenu(guienv, guiroot, -1,
1770                                         &g_menumgr, dest,
1771                                         L"/"))->drop();
1772                 }
1773                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1774                 {
1775                         if (!gui_chat_console->isOpenInhibited())
1776                         {
1777                                 // Open up to over half of the screen
1778                                 gui_chat_console->openConsole(0.6);
1779                                 guienv->setFocus(gui_chat_console);
1780                         }
1781                 }
1782                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1783                 {
1784                         if(g_settings->getBool("free_move"))
1785                         {
1786                                 g_settings->set("free_move","false");
1787                                 statustext = L"free_move disabled";
1788                                 statustext_time = 0;
1789                         }
1790                         else
1791                         {
1792                                 g_settings->set("free_move","true");
1793                                 statustext = L"free_move enabled";
1794                                 statustext_time = 0;
1795                                 if(!client.checkPrivilege("fly"))
1796                                         statustext += L" (note: no 'fly' privilege)";
1797                         }
1798                 }
1799                 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1800                 {
1801                         if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1802                         {
1803                                 if(g_settings->getBool("free_move"))
1804                                 {
1805                                         g_settings->set("free_move","false");
1806                                         statustext = L"free_move disabled";
1807                                         statustext_time = 0;
1808                                 }
1809                                 else
1810                                 {
1811                                         g_settings->set("free_move","true");
1812                                         statustext = L"free_move enabled";
1813                                         statustext_time = 0;
1814                                         if(!client.checkPrivilege("fly"))
1815                                                 statustext += L" (note: no 'fly' privilege)";
1816                                 }
1817                         }
1818                         reset_jump_timer = true;
1819                 }
1820                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1821                 {
1822                         if(g_settings->getBool("fast_move"))
1823                         {
1824                                 g_settings->set("fast_move","false");
1825                                 statustext = L"fast_move disabled";
1826                                 statustext_time = 0;
1827                         }
1828                         else
1829                         {
1830                                 g_settings->set("fast_move","true");
1831                                 statustext = L"fast_move enabled";
1832                                 statustext_time = 0;
1833                                 if(!client.checkPrivilege("fast"))
1834                                         statustext += L" (note: no 'fast' privilege)";
1835                         }
1836                 }
1837                 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1838                 {
1839                         if(g_settings->getBool("noclip"))
1840                         {
1841                                 g_settings->set("noclip","false");
1842                                 statustext = L"noclip disabled";
1843                                 statustext_time = 0;
1844                         }
1845                         else
1846                         {
1847                                 g_settings->set("noclip","true");
1848                                 statustext = L"noclip enabled";
1849                                 statustext_time = 0;
1850                                 if(!client.checkPrivilege("noclip"))
1851                                         statustext += L" (note: no 'noclip' privilege)";
1852                         }
1853                 }
1854                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1855                 {
1856                         irr::video::IImage* const image = driver->createScreenShot(); 
1857                         if (image) { 
1858                                 irr::c8 filename[256]; 
1859                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1860                                                  g_settings->get("screenshot_path").c_str(),
1861                                                  device->getTimer()->getRealTime()); 
1862                                 if (driver->writeImageToFile(image, filename)) {
1863                                         std::wstringstream sstr;
1864                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1865                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1866                                         statustext = sstr.str();
1867                                         statustext_time = 0;
1868                                 } else{
1869                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1870                                 }
1871                                 image->drop(); 
1872                         }                        
1873                 }
1874                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1875                 {
1876                         show_hud = !show_hud;
1877                         if(show_hud)
1878                                 statustext = L"HUD shown";
1879                         else
1880                                 statustext = L"HUD hidden";
1881                         statustext_time = 0;
1882                 }
1883                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1884                 {
1885                         show_chat = !show_chat;
1886                         if(show_chat)
1887                                 statustext = L"Chat shown";
1888                         else
1889                                 statustext = L"Chat hidden";
1890                         statustext_time = 0;
1891                 }
1892                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1893                 {
1894                         force_fog_off = !force_fog_off;
1895                         if(force_fog_off)
1896                                 statustext = L"Fog disabled";
1897                         else
1898                                 statustext = L"Fog enabled";
1899                         statustext_time = 0;
1900                 }
1901                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1902                 {
1903                         disable_camera_update = !disable_camera_update;
1904                         if(disable_camera_update)
1905                                 statustext = L"Camera update disabled";
1906                         else
1907                                 statustext = L"Camera update enabled";
1908                         statustext_time = 0;
1909                 }
1910                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1911                 {
1912                         // Initial / 3x toggle: Chat only
1913                         // 1x toggle: Debug text with chat
1914                         // 2x toggle: Debug text with profiler graph
1915                         if(!show_debug)
1916                         {
1917                                 show_debug = true;
1918                                 show_profiler_graph = false;
1919                                 statustext = L"Debug info shown";
1920                                 statustext_time = 0;
1921                         }
1922                         else if(show_profiler_graph)
1923                         {
1924                                 show_debug = false;
1925                                 show_profiler_graph = false;
1926                                 statustext = L"Debug info and profiler graph hidden";
1927                                 statustext_time = 0;
1928                         }
1929                         else
1930                         {
1931                                 show_profiler_graph = true;
1932                                 statustext = L"Profiler graph shown";
1933                                 statustext_time = 0;
1934                         }
1935                 }
1936                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1937                 {
1938                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1939
1940                         // FIXME: This updates the profiler with incomplete values
1941                         update_profiler_gui(guitext_profiler, font, text_height,
1942                                         show_profiler, show_profiler_max);
1943
1944                         if(show_profiler != 0)
1945                         {
1946                                 std::wstringstream sstr;
1947                                 sstr<<"Profiler shown (page "<<show_profiler
1948                                         <<" of "<<show_profiler_max<<")";
1949                                 statustext = sstr.str();
1950                                 statustext_time = 0;
1951                         }
1952                         else
1953                         {
1954                                 statustext = L"Profiler hidden";
1955                                 statustext_time = 0;
1956                         }
1957                 }
1958                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1959                 {
1960                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1961                         s16 range_new = range + 10;
1962                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1963                         statustext = narrow_to_wide(
1964                                         "Minimum viewing range changed to "
1965                                         + itos(range_new));
1966                         statustext_time = 0;
1967                 }
1968                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1969                 {
1970                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1971                         s16 range_new = range - 10;
1972                         if(range_new < 0)
1973                                 range_new = range;
1974                         g_settings->set("viewing_range_nodes_min",
1975                                         itos(range_new));
1976                         statustext = narrow_to_wide(
1977                                         "Minimum viewing range changed to "
1978                                         + itos(range_new));
1979                         statustext_time = 0;
1980                 }
1981                 
1982                 // Reset jump_timer
1983                 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1984                 {
1985                         reset_jump_timer = false;
1986                         jump_timer = 0.0;
1987                 }
1988
1989                 // Handle QuicktuneShortcutter
1990                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1991                         quicktune.next();
1992                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1993                         quicktune.prev();
1994                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1995                         quicktune.inc();
1996                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1997                         quicktune.dec();
1998                 {
1999                         std::string msg = quicktune.getMessage();
2000                         if(msg != ""){
2001                                 statustext = narrow_to_wide(msg);
2002                                 statustext_time = 0;
2003                         }
2004                 }
2005
2006                 // Item selection with mouse wheel
2007                 u16 new_playeritem = client.getPlayerItem();
2008                 {
2009                         s32 wheel = input->getMouseWheel();
2010                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2011                                         player->hud_hotbar_itemcount-1);
2012
2013                         if(wheel < 0)
2014                         {
2015                                 if(new_playeritem < max_item)
2016                                         new_playeritem++;
2017                                 else
2018                                         new_playeritem = 0;
2019                         }
2020                         else if(wheel > 0)
2021                         {
2022                                 if(new_playeritem > 0)
2023                                         new_playeritem--;
2024                                 else
2025                                         new_playeritem = max_item;
2026                         }
2027                 }
2028                 
2029                 // Item selection
2030                 for(u16 i=0; i<10; i++)
2031                 {
2032                         const KeyPress *kp = NumberKey + (i + 1) % 10;
2033                         if(input->wasKeyDown(*kp))
2034                         {
2035                                 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2036                                 {
2037                                         new_playeritem = i;
2038
2039                                         infostream<<"Selected item: "
2040                                                         <<new_playeritem<<std::endl;
2041                                 }
2042                         }
2043                 }
2044
2045                 // Viewing range selection
2046                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2047                 {
2048                         draw_control.range_all = !draw_control.range_all;
2049                         if(draw_control.range_all)
2050                         {
2051                                 infostream<<"Enabled full viewing range"<<std::endl;
2052                                 statustext = L"Enabled full viewing range";
2053                                 statustext_time = 0;
2054                         }
2055                         else
2056                         {
2057                                 infostream<<"Disabled full viewing range"<<std::endl;
2058                                 statustext = L"Disabled full viewing range";
2059                                 statustext_time = 0;
2060                         }
2061                 }
2062
2063                 // Print debug stacks
2064                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2065                 {
2066                         dstream<<"-----------------------------------------"
2067                                         <<std::endl;
2068                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2069                         dstream<<"-----------------------------------------"
2070                                         <<std::endl;
2071                         debug_stacks_print();
2072                 }
2073
2074                 /*
2075                         Mouse and camera control
2076                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2077                 */
2078                 
2079                 float turn_amount = 0;
2080                 if((device->isWindowActive() && noMenuActive()) || random_input)
2081                 {
2082                         if(!random_input)
2083                         {
2084                                 // Mac OSX gets upset if this is set every frame
2085                                 if(device->getCursorControl()->isVisible())
2086                                         device->getCursorControl()->setVisible(false);
2087                         }
2088
2089                         if(first_loop_after_window_activation){
2090                                 //infostream<<"window active, first loop"<<std::endl;
2091                                 first_loop_after_window_activation = false;
2092                         }
2093                         else{
2094                                 s32 dx = input->getMousePos().X - displaycenter.X;
2095                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
2096                                 if(invert_mouse)
2097                                         dy = -dy;
2098                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2099                                 
2100                                 /*const float keyspeed = 500;
2101                                 if(input->isKeyDown(irr::KEY_UP))
2102                                         dy -= dtime * keyspeed;
2103                                 if(input->isKeyDown(irr::KEY_DOWN))
2104                                         dy += dtime * keyspeed;
2105                                 if(input->isKeyDown(irr::KEY_LEFT))
2106                                         dx -= dtime * keyspeed;
2107                                 if(input->isKeyDown(irr::KEY_RIGHT))
2108                                         dx += dtime * keyspeed;*/
2109                                 
2110                                 float d = g_settings->getFloat("mouse_sensitivity");
2111                                 d = rangelim(d, 0.01, 100.0);
2112                                 camera_yaw -= dx*d;
2113                                 camera_pitch += dy*d;
2114                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
2115                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
2116                                 
2117                                 turn_amount = v2f(dx, dy).getLength() * d;
2118                         }
2119                         input->setMousePos(displaycenter.X, displaycenter.Y);
2120                 }
2121                 else{
2122                         // Mac OSX gets upset if this is set every frame
2123                         if(device->getCursorControl()->isVisible() == false)
2124                                 device->getCursorControl()->setVisible(true);
2125
2126                         //infostream<<"window inactive"<<std::endl;
2127                         first_loop_after_window_activation = true;
2128                 }
2129                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2130                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2131
2132                 /*
2133                         Player speed control
2134                 */
2135                 {
2136                         /*bool a_up,
2137                         bool a_down,
2138                         bool a_left,
2139                         bool a_right,
2140                         bool a_jump,
2141                         bool a_superspeed,
2142                         bool a_sneak,
2143                         bool a_LMB,
2144                         bool a_RMB,
2145                         float a_pitch,
2146                         float a_yaw*/
2147                         PlayerControl control(
2148                                 input->isKeyDown(getKeySetting("keymap_forward")),
2149                                 input->isKeyDown(getKeySetting("keymap_backward")),
2150                                 input->isKeyDown(getKeySetting("keymap_left")),
2151                                 input->isKeyDown(getKeySetting("keymap_right")),
2152                                 input->isKeyDown(getKeySetting("keymap_jump")),
2153                                 input->isKeyDown(getKeySetting("keymap_special1")),
2154                                 input->isKeyDown(getKeySetting("keymap_sneak")),
2155                                 input->getLeftState(),
2156                                 input->getRightState(),
2157                                 camera_pitch,
2158                                 camera_yaw
2159                         );
2160                         client.setPlayerControl(control);
2161                         u32 keyPressed=
2162                         1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2163                         2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2164                         4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2165                         8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2166                         16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2167                         32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2168                         64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2169                         128*(int)input->getLeftState()+
2170                         256*(int)input->getRightState();
2171                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2172                         player->keyPressed=keyPressed;
2173                 }
2174                 
2175                 /*
2176                         Run server
2177                 */
2178
2179                 if(server != NULL)
2180                 {
2181                         //TimeTaker timer("server->step(dtime)");
2182                         server->step(dtime);
2183                 }
2184
2185                 /*
2186                         Process environment
2187                 */
2188                 
2189                 {
2190                         //TimeTaker timer("client.step(dtime)");
2191                         client.step(dtime);
2192                         //client.step(dtime_avg1);
2193                 }
2194
2195                 {
2196                         // Read client events
2197                         for(;;)
2198                         {
2199                                 ClientEvent event = client.getClientEvent();
2200                                 if(event.type == CE_NONE)
2201                                 {
2202                                         break;
2203                                 }
2204                                 else if(event.type == CE_PLAYER_DAMAGE &&
2205                                                 client.getHP() != 0)
2206                                 {
2207                                         //u16 damage = event.player_damage.amount;
2208                                         //infostream<<"Player damage: "<<damage<<std::endl;
2209
2210                                         damage_flash += 100.0;
2211                                         damage_flash += 8.0 * event.player_damage.amount;
2212
2213                                         player->hurt_tilt_timer = 1.5;
2214                                         player->hurt_tilt_strength = event.player_damage.amount/2;
2215                                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2216
2217                                         MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2218                                         gamedef->event()->put(e);
2219                                 }
2220                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
2221                                 {
2222                                         camera_yaw = event.player_force_move.yaw;
2223                                         camera_pitch = event.player_force_move.pitch;
2224                                 }
2225                                 else if(event.type == CE_DEATHSCREEN)
2226                                 {
2227                                         if(respawn_menu_active)
2228                                                 continue;
2229
2230                                         /*bool set_camera_point_target =
2231                                                         event.deathscreen.set_camera_point_target;
2232                                         v3f camera_point_target;
2233                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
2234                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
2235                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2236                                         MainRespawnInitiator *respawner =
2237                                                         new MainRespawnInitiator(
2238                                                                         &respawn_menu_active, &client);
2239                                         GUIDeathScreen *menu =
2240                                                         new GUIDeathScreen(guienv, guiroot, -1, 
2241                                                                 &g_menumgr, respawner);
2242                                         menu->drop();
2243                                         
2244                                         chat_backend.addMessage(L"", L"You died.");
2245
2246                                         /* Handle visualization */
2247
2248                                         damage_flash = 0;
2249
2250                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2251                                         player->hurt_tilt_timer = 0;
2252                                         player->hurt_tilt_strength = 0;
2253
2254                                         /*LocalPlayer* player = client.getLocalPlayer();
2255                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
2256                                         camera.update(player, busytime, screensize);*/
2257                                 }
2258                                 else if (event.type == CE_SHOW_FORMSPEC)
2259                                 {
2260                                         if (current_formspec == 0)
2261                                         {
2262                                                 /* Create menu */
2263                                                 /* Note: FormspecFormSource and TextDestPlayerInventory
2264                                                  * are deleted by guiFormSpecMenu                     */
2265                                                 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),&current_formspec);
2266                                                 current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2267                                                 GUIFormSpecMenu *menu =
2268                                                                 new GUIFormSpecMenu(device, guiroot, -1,
2269                                                                                 &g_menumgr,
2270                                                                                 &client, gamedef);
2271                                                 menu->setFormSource(current_formspec);
2272                                                 menu->setTextDest(current_textdest);
2273                                                 menu->drop();
2274                                         }
2275                                         else
2276                                         {
2277                                                 assert(current_textdest != 0);
2278                                                 /* update menu */
2279                                                 current_textdest->setFormName(*(event.show_formspec.formname));
2280                                                 current_formspec->setForm(*(event.show_formspec.formspec));
2281                                         }
2282                                         delete(event.show_formspec.formspec);
2283                                         delete(event.show_formspec.formname);
2284                                 }
2285                                 else if(event.type == CE_TEXTURES_UPDATED)
2286                                 {
2287                                         update_wielded_item_trigger = true;
2288                                 }
2289                                 else if(event.type == CE_SPAWN_PARTICLE)
2290                                 {
2291                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2292                                         video::ITexture *texture =
2293                                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2294
2295                                         new Particle(gamedef, smgr, player, client.getEnv(),
2296                                                 *event.spawn_particle.pos,
2297                                                 *event.spawn_particle.vel,
2298                                                 *event.spawn_particle.acc,
2299                                                  event.spawn_particle.expirationtime,
2300                                                  event.spawn_particle.size,
2301                                                  event.spawn_particle.collisiondetection,
2302                                                  texture,
2303                                                  v2f(0.0, 0.0),
2304                                                  v2f(1.0, 1.0));
2305                                 }
2306                                 else if(event.type == CE_ADD_PARTICLESPAWNER)
2307                                 {
2308                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2309                                         video::ITexture *texture =
2310                                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2311
2312                                         new ParticleSpawner(gamedef, smgr, player,
2313                                                  event.add_particlespawner.amount,
2314                                                  event.add_particlespawner.spawntime,
2315                                                 *event.add_particlespawner.minpos,
2316                                                 *event.add_particlespawner.maxpos,
2317                                                 *event.add_particlespawner.minvel,
2318                                                 *event.add_particlespawner.maxvel,
2319                                                 *event.add_particlespawner.minacc,
2320                                                 *event.add_particlespawner.maxacc,
2321                                                  event.add_particlespawner.minexptime,
2322                                                  event.add_particlespawner.maxexptime,
2323                                                  event.add_particlespawner.minsize,
2324                                                  event.add_particlespawner.maxsize,
2325                                                  event.add_particlespawner.collisiondetection,
2326                                                  texture,
2327                                                  event.add_particlespawner.id);
2328                                 }
2329                                 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2330                                 {
2331                                         delete_particlespawner (event.delete_particlespawner.id);
2332                                 }
2333                                 else if (event.type == CE_HUDADD)
2334                                 {
2335                                         u32 id = event.hudadd.id;
2336                                         size_t nhudelem = player->hud.size();
2337                                         if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2338                                                 delete event.hudadd.pos;
2339                                                 delete event.hudadd.name;
2340                                                 delete event.hudadd.scale;
2341                                                 delete event.hudadd.text;
2342                                                 delete event.hudadd.align;
2343                                                 delete event.hudadd.offset;
2344                                                 continue;
2345                                         }
2346                                         
2347                                         HudElement *e = new HudElement;
2348                                         e->type   = (HudElementType)event.hudadd.type;
2349                                         e->pos    = *event.hudadd.pos;
2350                                         e->name   = *event.hudadd.name;
2351                                         e->scale  = *event.hudadd.scale;
2352                                         e->text   = *event.hudadd.text;
2353                                         e->number = event.hudadd.number;
2354                                         e->item   = event.hudadd.item;
2355                                         e->dir    = event.hudadd.dir;
2356                                         e->align  = *event.hudadd.align;
2357                                         e->offset = *event.hudadd.offset;
2358                                         
2359                                         if (id == nhudelem)
2360                                                 player->hud.push_back(e);
2361                                         else
2362                                                 player->hud[id] = e;
2363
2364                                         delete event.hudadd.pos;
2365                                         delete event.hudadd.name;
2366                                         delete event.hudadd.scale;
2367                                         delete event.hudadd.text;
2368                                         delete event.hudadd.align;
2369                                         delete event.hudadd.offset;
2370                                 }
2371                                 else if (event.type == CE_HUDRM)
2372                                 {
2373                                         u32 id = event.hudrm.id;
2374                                         if (id < player->hud.size() && player->hud[id]) {
2375                                                 delete player->hud[id];
2376                                                 player->hud[id] = NULL;
2377                                         }
2378                                 }
2379                                 else if (event.type == CE_HUDCHANGE)
2380                                 {
2381                                         u32 id = event.hudchange.id;
2382                                         if (id >= player->hud.size() || !player->hud[id]) {
2383                                                 delete event.hudchange.v2fdata;
2384                                                 delete event.hudchange.sdata;
2385                                                 continue;
2386                                         }
2387                                                 
2388                                         HudElement* e = player->hud[id];
2389                                         switch (event.hudchange.stat) {
2390                                                 case HUD_STAT_POS:
2391                                                         e->pos = *event.hudchange.v2fdata;
2392                                                         break;
2393                                                 case HUD_STAT_NAME:
2394                                                         e->name = *event.hudchange.sdata;
2395                                                         break;
2396                                                 case HUD_STAT_SCALE:
2397                                                         e->scale = *event.hudchange.v2fdata;
2398                                                         break;
2399                                                 case HUD_STAT_TEXT:
2400                                                         e->text = *event.hudchange.sdata;
2401                                                         break;
2402                                                 case HUD_STAT_NUMBER:
2403                                                         e->number = event.hudchange.data;
2404                                                         break;
2405                                                 case HUD_STAT_ITEM:
2406                                                         e->item = event.hudchange.data;
2407                                                         break;
2408                                                 case HUD_STAT_DIR:
2409                                                         e->dir = event.hudchange.data;
2410                                                         break;
2411                                                 case HUD_STAT_ALIGN:
2412                                                         e->align = *event.hudchange.v2fdata;
2413                                                         break;
2414                                                 case HUD_STAT_OFFSET:
2415                                                         e->offset = *event.hudchange.v2fdata;
2416                                                         break;
2417                                         }
2418                                         
2419                                         delete event.hudchange.v2fdata;
2420                                         delete event.hudchange.sdata;
2421                                 }
2422                         }
2423                 }
2424                 
2425                 //TimeTaker //timer2("//timer2");
2426
2427                 /*
2428                         For interaction purposes, get info about the held item
2429                         - What item is it?
2430                         - Is it a usable item?
2431                         - Can it point to liquids?
2432                 */
2433                 ItemStack playeritem;
2434                 {
2435                         InventoryList *mlist = local_inventory.getList("main");
2436                         if(mlist != NULL)
2437                         {
2438                                 playeritem = mlist->getItem(client.getPlayerItem());
2439                         }
2440                 }
2441                 const ItemDefinition &playeritem_def =
2442                                 playeritem.getDefinition(itemdef);
2443                 ToolCapabilities playeritem_toolcap =
2444                                 playeritem.getToolCapabilities(itemdef);
2445                 
2446                 /*
2447                         Update camera
2448                 */
2449
2450                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2451                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2452                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2453                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2454                 camera.update(player, busytime, screensize, tool_reload_ratio);
2455                 camera.step(dtime);
2456
2457                 v3f player_position = player->getPosition();
2458                 v3f camera_position = camera.getPosition();
2459                 v3f camera_direction = camera.getDirection();
2460                 f32 camera_fov = camera.getFovMax();
2461                 
2462                 if(!disable_camera_update){
2463                         client.getEnv().getClientMap().updateCamera(camera_position,
2464                                 camera_direction, camera_fov);
2465                 }
2466                 
2467                 // Update sound listener
2468                 sound->updateListener(camera.getCameraNode()->getPosition(),
2469                                 v3f(0,0,0), // velocity
2470                                 camera.getDirection(),
2471                                 camera.getCameraNode()->getUpVector());
2472                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2473
2474                 /*
2475                         Update sound maker
2476                 */
2477                 {
2478                         soundmaker.step(dtime);
2479                         
2480                         ClientMap &map = client.getEnv().getClientMap();
2481                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2482                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2483                 }
2484
2485                 /*
2486                         Calculate what block is the crosshair pointing to
2487                 */
2488                 
2489                 //u32 t1 = device->getTimer()->getRealTime();
2490                 
2491                 f32 d = 4; // max. distance
2492                 core::line3d<f32> shootline(camera_position,
2493                                 camera_position + camera_direction * BS * (d+1));
2494
2495                 ClientActiveObject *selected_object = NULL;
2496
2497                 PointedThing pointed = getPointedThing(
2498                                 // input
2499                                 &client, player_position, camera_direction,
2500                                 camera_position, shootline, d,
2501                                 playeritem_def.liquids_pointable, !ldown_for_dig,
2502                                 // output
2503                                 hilightboxes,
2504                                 selected_object);
2505
2506                 if(pointed != pointed_old)
2507                 {
2508                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2509                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2510                 }
2511
2512                 /*
2513                         Stop digging when
2514                         - releasing left mouse button
2515                         - pointing away from node
2516                 */
2517                 if(digging)
2518                 {
2519                         if(input->getLeftReleased())
2520                         {
2521                                 infostream<<"Left button released"
2522                                         <<" (stopped digging)"<<std::endl;
2523                                 digging = false;
2524                         }
2525                         else if(pointed != pointed_old)
2526                         {
2527                                 if (pointed.type == POINTEDTHING_NODE
2528                                         && pointed_old.type == POINTEDTHING_NODE
2529                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2530                                 {
2531                                         // Still pointing to the same node,
2532                                         // but a different face. Don't reset.
2533                                 }
2534                                 else
2535                                 {
2536                                         infostream<<"Pointing away from node"
2537                                                 <<" (stopped digging)"<<std::endl;
2538                                         digging = false;
2539                                 }
2540                         }
2541                         if(!digging)
2542                         {
2543                                 client.interact(1, pointed_old);
2544                                 client.setCrack(-1, v3s16(0,0,0));
2545                                 dig_time = 0.0;
2546                         }
2547                 }
2548                 if(!digging && ldown_for_dig && !input->getLeftState())
2549                 {
2550                         ldown_for_dig = false;
2551                 }
2552
2553                 bool left_punch = false;
2554                 soundmaker.m_player_leftpunch_sound.name = "";
2555
2556                 if(input->getRightState())
2557                         repeat_rightclick_timer += dtime;
2558                 else
2559                         repeat_rightclick_timer = 0;
2560
2561                 if(playeritem_def.usable && input->getLeftState())
2562                 {
2563                         if(input->getLeftClicked())
2564                                 client.interact(4, pointed);
2565                 }
2566                 else if(pointed.type == POINTEDTHING_NODE)
2567                 {
2568                         v3s16 nodepos = pointed.node_undersurface;
2569                         v3s16 neighbourpos = pointed.node_abovesurface;
2570
2571                         /*
2572                                 Check information text of node
2573                         */
2574                         
2575                         ClientMap &map = client.getEnv().getClientMap();
2576                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2577                         if(meta){
2578                                 infotext = narrow_to_wide(meta->getString("infotext"));
2579                         } else {
2580                                 MapNode n = map.getNode(nodepos);
2581                                 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2582                                         infotext = L"Unknown node: ";
2583                                         infotext += narrow_to_wide(nodedef->get(n).name);
2584                                 }
2585                         }
2586                         
2587                         /*
2588                                 Handle digging
2589                         */
2590                         
2591                         if(nodig_delay_timer <= 0.0 && input->getLeftState()
2592                                         && client.checkPrivilege("interact"))
2593                         {
2594                                 if(!digging)
2595                                 {
2596                                         infostream<<"Started digging"<<std::endl;
2597                                         client.interact(0, pointed);
2598                                         digging = true;
2599                                         ldown_for_dig = true;
2600                                 }
2601                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2602                                 
2603                                 // NOTE: Similar piece of code exists on the server side for
2604                                 // cheat detection.
2605                                 // Get digging parameters
2606                                 DigParams params = getDigParams(nodedef->get(n).groups,
2607                                                 &playeritem_toolcap);
2608                                 // If can't dig, try hand
2609                                 if(!params.diggable){
2610                                         const ItemDefinition &hand = itemdef->get("");
2611                                         const ToolCapabilities *tp = hand.tool_capabilities;
2612                                         if(tp)
2613                                                 params = getDigParams(nodedef->get(n).groups, tp);
2614                                 }
2615                                 
2616                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2617                                 if(sound_dig.exists()){
2618                                         if(sound_dig.name == "__group"){
2619                                                 if(params.main_group != ""){
2620                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2621                                                         soundmaker.m_player_leftpunch_sound.name =
2622                                                                         std::string("default_dig_") +
2623                                                                                         params.main_group;
2624                                                 }
2625                                         } else{
2626                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2627                                         }
2628                                 }
2629
2630                                 float dig_time_complete = 0.0;
2631
2632                                 if(params.diggable == false)
2633                                 {
2634                                         // I guess nobody will wait for this long
2635                                         dig_time_complete = 10000000.0;
2636                                 }
2637                                 else
2638                                 {
2639                                         dig_time_complete = params.time;
2640                                         if (g_settings->getBool("enable_particles"))
2641                                         {
2642                                                 const ContentFeatures &features =
2643                                                         client.getNodeDefManager()->get(n);
2644                                                 addPunchingParticles
2645                                                         (gamedef, smgr, player, client.getEnv(),
2646                                                          nodepos, features.tiles);
2647                                         }
2648                                 }
2649
2650                                 if(dig_time_complete >= 0.001)
2651                                 {
2652                                         dig_index = (u16)((float)crack_animation_length
2653                                                         * dig_time/dig_time_complete);
2654                                 }
2655                                 // This is for torches
2656                                 else
2657                                 {
2658                                         dig_index = crack_animation_length;
2659                                 }
2660
2661                                 // Don't show cracks if not diggable
2662                                 if(dig_time_complete >= 100000.0)
2663                                 {
2664                                 }
2665                                 else if(dig_index < crack_animation_length)
2666                                 {
2667                                         //TimeTaker timer("client.setTempMod");
2668                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2669                                         client.setCrack(dig_index, nodepos);
2670                                 }
2671                                 else
2672                                 {
2673                                         infostream<<"Digging completed"<<std::endl;
2674                                         client.interact(2, pointed);
2675                                         client.setCrack(-1, v3s16(0,0,0));
2676                                         MapNode wasnode = map.getNode(nodepos);
2677                                         client.removeNode(nodepos);
2678
2679                                         if (g_settings->getBool("enable_particles"))
2680                                         {
2681                                                 const ContentFeatures &features =
2682                                                         client.getNodeDefManager()->get(wasnode);
2683                                                 addDiggingParticles
2684                                                         (gamedef, smgr, player, client.getEnv(),
2685                                                          nodepos, features.tiles);
2686                                         }
2687
2688                                         dig_time = 0;
2689                                         digging = false;
2690
2691                                         nodig_delay_timer = dig_time_complete
2692                                                         / (float)crack_animation_length;
2693
2694                                         // We don't want a corresponding delay to
2695                                         // very time consuming nodes
2696                                         if(nodig_delay_timer > 0.3)
2697                                                 nodig_delay_timer = 0.3;
2698                                         // We want a slight delay to very little
2699                                         // time consuming nodes
2700                                         float mindelay = 0.15;
2701                                         if(nodig_delay_timer < mindelay)
2702                                                 nodig_delay_timer = mindelay;
2703                                         
2704                                         // Send event to trigger sound
2705                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2706                                         gamedef->event()->put(e);
2707                                 }
2708
2709                                 if(dig_time_complete < 100000.0)
2710                                         dig_time += dtime;
2711                                 else {
2712                                         dig_time = 0;
2713                                         client.setCrack(-1, nodepos);
2714                                 }
2715
2716                                 camera.setDigging(0);  // left click animation
2717                         }
2718
2719                         if((input->getRightClicked() ||
2720                                         repeat_rightclick_timer >=
2721                                                 g_settings->getFloat("repeat_rightclick_time")) &&
2722                                         client.checkPrivilege("interact"))
2723                         {
2724                                 repeat_rightclick_timer = 0;
2725                                 infostream<<"Ground right-clicked"<<std::endl;
2726                                 
2727                                 // Sign special case, at least until formspec is properly implemented.
2728                                 // Deprecated?
2729                                 if(meta && meta->getString("formspec") == "hack:sign_text_input" 
2730                                                 && !random_input
2731                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2732                                 {
2733                                         infostream<<"Launching metadata text input"<<std::endl;
2734                                         
2735                                         // Get a new text for it
2736
2737                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2738
2739                                         std::wstring wtext = narrow_to_wide(meta->getString("text"));
2740
2741                                         (new GUITextInputMenu(guienv, guiroot, -1,
2742                                                         &g_menumgr, dest,
2743                                                         wtext))->drop();
2744                                 }
2745                                 // If metadata provides an inventory view, activate it
2746                                 else if(meta && meta->getString("formspec") != "" && !random_input
2747                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2748                                 {
2749                                         infostream<<"Launching custom inventory view"<<std::endl;
2750
2751                                         InventoryLocation inventoryloc;
2752                                         inventoryloc.setNodeMeta(nodepos);
2753                                         
2754                                         /* Create menu */
2755
2756                                         GUIFormSpecMenu *menu =
2757                                                 new GUIFormSpecMenu(device, guiroot, -1,
2758                                                         &g_menumgr,
2759                                                         &client, gamedef);
2760                                         menu->setFormSpec(meta->getString("formspec"),
2761                                                         inventoryloc);
2762                                         menu->setFormSource(new NodeMetadataFormSource(
2763                                                         &client.getEnv().getClientMap(), nodepos));
2764                                         menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2765                                         menu->drop();
2766                                 }
2767                                 // Otherwise report right click to server
2768                                 else
2769                                 {
2770                                         // Report to server
2771                                         client.interact(3, pointed);
2772                                         camera.setDigging(1);  // right click animation
2773                                         
2774                                         // If the wielded item has node placement prediction,
2775                                         // make that happen
2776                                         bool placed = nodePlacementPrediction(client,
2777                                                         playeritem_def,
2778                                                         nodepos, neighbourpos);
2779                                         
2780                                         // Read the sound
2781                                         if(placed)
2782                                                 soundmaker.m_player_rightpunch_sound =
2783                                                                 playeritem_def.sound_place;
2784                                         else
2785                                                 soundmaker.m_player_rightpunch_sound =
2786                                                                 SimpleSoundSpec();
2787                                 }
2788                         }
2789                 }
2790                 else if(pointed.type == POINTEDTHING_OBJECT)
2791                 {
2792                         infotext = narrow_to_wide(selected_object->infoText());
2793
2794                         if(infotext == L"" && show_debug){
2795                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2796                         }
2797
2798                         //if(input->getLeftClicked())
2799                         if(input->getLeftState())
2800                         {
2801                                 bool do_punch = false;
2802                                 bool do_punch_damage = false;
2803                                 if(object_hit_delay_timer <= 0.0){
2804                                         do_punch = true;
2805                                         do_punch_damage = true;
2806                                         object_hit_delay_timer = object_hit_delay;
2807                                 }
2808                                 if(input->getLeftClicked()){
2809                                         do_punch = true;
2810                                 }
2811                                 if(do_punch){
2812                                         infostream<<"Left-clicked object"<<std::endl;
2813                                         left_punch = true;
2814                                 }
2815                                 if(do_punch_damage){
2816                                         // Report direct punch
2817                                         v3f objpos = selected_object->getPosition();
2818                                         v3f dir = (objpos - player_position).normalize();
2819                                         
2820                                         bool disable_send = selected_object->directReportPunch(
2821                                                         dir, &playeritem, time_from_last_punch);
2822                                         time_from_last_punch = 0;
2823                                         if(!disable_send)
2824                                                 client.interact(0, pointed);
2825                                 }
2826                         }
2827                         else if(input->getRightClicked())
2828                         {
2829                                 infostream<<"Right-clicked object"<<std::endl;
2830                                 client.interact(3, pointed);  // place
2831                         }
2832                 }
2833                 else if(input->getLeftState())
2834                 {
2835                         // When button is held down in air, show continuous animation
2836                         left_punch = true;
2837                 }
2838
2839                 pointed_old = pointed;
2840                 
2841                 if(left_punch || input->getLeftClicked())
2842                 {
2843                         camera.setDigging(0); // left click animation
2844                 }
2845
2846                 input->resetLeftClicked();
2847                 input->resetRightClicked();
2848
2849                 input->resetLeftReleased();
2850                 input->resetRightReleased();
2851                 
2852                 /*
2853                         Calculate stuff for drawing
2854                 */
2855
2856                 /*
2857                         Fog range
2858                 */
2859         
2860                 if(farmesh)
2861                 {
2862                         fog_range = BS*farmesh_range;
2863                 }
2864                 else
2865                 {
2866                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2867                         fog_range *= 0.9;
2868                         if(draw_control.range_all)
2869                                 fog_range = 100000*BS;
2870                 }
2871
2872                 /*
2873                         Calculate general brightness
2874                 */
2875                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2876                 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2877                 float direct_brightness = 0;
2878                 bool sunlight_seen = false;
2879                 if(g_settings->getBool("free_move")){
2880                         direct_brightness = time_brightness;
2881                         sunlight_seen = true;
2882                 } else {
2883                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2884                         float old_brightness = sky->getBrightness();
2885                         direct_brightness = (float)client.getEnv().getClientMap()
2886                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2887                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2888                                         / 255.0;
2889                 }
2890                 
2891                 time_of_day = client.getEnv().getTimeOfDayF();
2892                 float maxsm = 0.05;
2893                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2894                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2895                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2896                         time_of_day_smooth = time_of_day;
2897                 float todsm = 0.05;
2898                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2899                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2900                                         + (time_of_day+1.0) * todsm;
2901                 else
2902                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2903                                         + time_of_day * todsm;
2904                         
2905                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2906                                 sunlight_seen);
2907                 
2908                 float brightness = sky->getBrightness();
2909                 video::SColor bgcolor = sky->getBgColor();
2910                 video::SColor skycolor = sky->getSkyColor();
2911
2912                 /*
2913                         Update clouds
2914                 */
2915                 if(clouds){
2916                         if(sky->getCloudsVisible()){
2917                                 clouds->setVisible(true);
2918                                 clouds->step(dtime);
2919                                 clouds->update(v2f(player_position.X, player_position.Z),
2920                                                 sky->getCloudColor());
2921                         } else{
2922                                 clouds->setVisible(false);
2923                         }
2924                 }
2925                 
2926                 /*
2927                         Update farmesh
2928                 */
2929                 if(farmesh)
2930                 {
2931                         farmesh_range = draw_control.wanted_range * 10;
2932                         if(draw_control.range_all && farmesh_range < 500)
2933                                 farmesh_range = 500;
2934                         if(farmesh_range > 1000)
2935                                 farmesh_range = 1000;
2936
2937                         farmesh->step(dtime);
2938                         farmesh->update(v2f(player_position.X, player_position.Z),
2939                                         brightness, farmesh_range);
2940                 }
2941
2942                 /*
2943                         Update particles
2944                 */
2945
2946                 allparticles_step(dtime, client.getEnv());
2947                 allparticlespawners_step(dtime, client.getEnv());
2948                 
2949                 /*
2950                         Fog
2951                 */
2952                 
2953                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2954                 {
2955                         driver->setFog(
2956                                 bgcolor,
2957                                 video::EFT_FOG_LINEAR,
2958                                 fog_range*0.4,
2959                                 fog_range*1.0,
2960                                 0.01,
2961                                 false, // pixel fog
2962                                 false // range fog
2963                         );
2964                 }
2965                 else
2966                 {
2967                         driver->setFog(
2968                                 bgcolor,
2969                                 video::EFT_FOG_LINEAR,
2970                                 100000*BS,
2971                                 110000*BS,
2972                                 0.01,
2973                                 false, // pixel fog
2974                                 false // range fog
2975                         );
2976                 }
2977
2978                 /*
2979                         Update gui stuff (0ms)
2980                 */
2981
2982                 //TimeTaker guiupdatetimer("Gui updating");
2983                 
2984                 const char program_name_and_version[] =
2985                         "Minetest " VERSION_STRING;
2986
2987                 if(show_debug)
2988                 {
2989                         static float drawtime_avg = 0;
2990                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2991                         /*static float beginscenetime_avg = 0;
2992                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2993                         static float scenetime_avg = 0;
2994                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2995                         static float endscenetime_avg = 0;
2996                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2997                         
2998                         std::ostringstream os(std::ios_base::binary);
2999                         os<<std::fixed
3000                                 <<program_name_and_version
3001                                 <<" (R: range_all="<<draw_control.range_all<<")"
3002                                 <<std::setprecision(0)
3003                                 <<" drawtime = "<<drawtime_avg
3004                                 <<std::setprecision(1)
3005                                 <<", dtime_jitter = "
3006                                 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3007                                 <<std::setprecision(1)
3008                                 <<", v_range = "<<draw_control.wanted_range
3009                                 <<std::setprecision(3)
3010                                 <<", RTT = "<<client.getRTT();
3011                         guitext->setText(narrow_to_wide(os.str()).c_str());
3012                         guitext->setVisible(true);
3013                 }
3014                 else if(show_hud || show_chat)
3015                 {
3016                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
3017                         guitext->setVisible(true);
3018                 }
3019                 else
3020                 {
3021                         guitext->setVisible(false);
3022                 }
3023                 
3024                 if(show_debug)
3025                 {
3026                         std::ostringstream os(std::ios_base::binary);
3027                         os<<std::setprecision(1)<<std::fixed
3028                                 <<"(" <<(player_position.X/BS)
3029                                 <<", "<<(player_position.Y/BS)
3030                                 <<", "<<(player_position.Z/BS)
3031                                 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3032                                 <<") (seed = "<<((unsigned long long)client.getMapSeed())
3033                                 <<")";
3034                         guitext2->setText(narrow_to_wide(os.str()).c_str());
3035                         guitext2->setVisible(true);
3036                 }
3037                 else
3038                 {
3039                         guitext2->setVisible(false);
3040                 }
3041                 
3042                 {
3043                         guitext_info->setText(infotext.c_str());
3044                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3045                 }
3046
3047                 {
3048                         float statustext_time_max = 1.5;
3049                         if(!statustext.empty())
3050                         {
3051                                 statustext_time += dtime;
3052                                 if(statustext_time >= statustext_time_max)
3053                                 {
3054                                         statustext = L"";
3055                                         statustext_time = 0;
3056                                 }
3057                         }
3058                         guitext_status->setText(statustext.c_str());
3059                         guitext_status->setVisible(!statustext.empty());
3060
3061                         if(!statustext.empty())
3062                         {
3063                                 s32 status_y = screensize.Y - 130;
3064                                 core::rect<s32> rect(
3065                                                 10,
3066                                                 status_y - guitext_status->getTextHeight(),
3067                                                 screensize.X - 10,
3068                                                 status_y
3069                                 );
3070                                 guitext_status->setRelativePosition(rect);
3071
3072                                 // Fade out
3073                                 video::SColor initial_color(255,0,0,0);
3074                                 if(guienv->getSkin())
3075                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3076                                 video::SColor final_color = initial_color;
3077                                 final_color.setAlpha(0);
3078                                 video::SColor fade_color =
3079                                         initial_color.getInterpolated_quadratic(
3080                                                 initial_color,
3081                                                 final_color,
3082                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
3083                                 guitext_status->setOverrideColor(fade_color);
3084                                 guitext_status->enableOverrideColor(true);
3085                         }
3086                 }
3087                 
3088                 /*
3089                         Get chat messages from client
3090                 */
3091                 {
3092                         // Get new messages from error log buffer
3093                         while(!chat_log_error_buf.empty())
3094                         {
3095                                 chat_backend.addMessage(L"", narrow_to_wide(
3096                                                 chat_log_error_buf.get()));
3097                         }
3098                         // Get new messages from client
3099                         std::wstring message;
3100                         while(client.getChatMessage(message))
3101                         {
3102                                 chat_backend.addUnparsedMessage(message);
3103                         }
3104                         // Remove old messages
3105                         chat_backend.step(dtime);
3106
3107                         // Display all messages in a static text element
3108                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3109                         std::wstring recent_chat = chat_backend.getRecentChat();
3110                         guitext_chat->setText(recent_chat.c_str());
3111
3112                         // Update gui element size and position
3113                         s32 chat_y = 5+(text_height+5);
3114                         if(show_debug)
3115                                 chat_y += (text_height+5);
3116                         core::rect<s32> rect(
3117                                 10,
3118                                 chat_y,
3119                                 screensize.X - 10,
3120                                 chat_y + guitext_chat->getTextHeight()
3121                         );
3122                         guitext_chat->setRelativePosition(rect);
3123
3124                         // Don't show chat if disabled or empty or profiler is enabled
3125                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
3126                                         && !show_profiler);
3127                 }
3128
3129                 /*
3130                         Inventory
3131                 */
3132                 
3133                 if(client.getPlayerItem() != new_playeritem)
3134                 {
3135                         client.selectPlayerItem(new_playeritem);
3136                 }
3137                 if(client.getLocalInventoryUpdated())
3138                 {
3139                         //infostream<<"Updating local inventory"<<std::endl;
3140                         client.getLocalInventory(local_inventory);
3141                         
3142                         update_wielded_item_trigger = true;
3143                 }
3144                 if(update_wielded_item_trigger)
3145                 {
3146                         update_wielded_item_trigger = false;
3147                         // Update wielded tool
3148                         InventoryList *mlist = local_inventory.getList("main");
3149                         ItemStack item;
3150                         if(mlist != NULL)
3151                                 item = mlist->getItem(client.getPlayerItem());
3152                         camera.wield(item, client.getPlayerItem());
3153                 }
3154
3155                 /*
3156                         Update block draw list every 200ms or when camera direction has
3157                         changed much
3158                 */
3159                 update_draw_list_timer += dtime;
3160                 if(update_draw_list_timer >= 0.2 ||
3161                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
3162                         update_draw_list_timer = 0;
3163                         client.getEnv().getClientMap().updateDrawList(driver);
3164                         update_draw_list_last_cam_dir = camera_direction;
3165                 }
3166
3167                 /*
3168                         Drawing begins
3169                 */
3170
3171                 TimeTaker tt_draw("mainloop: draw");
3172                 
3173                 {
3174                         TimeTaker timer("beginScene");
3175                         //driver->beginScene(false, true, bgcolor);
3176                         //driver->beginScene(true, true, bgcolor);
3177                         driver->beginScene(true, true, skycolor);
3178                         beginscenetime = timer.stop(true);
3179                 }
3180                 
3181                 //timer3.stop();
3182         
3183                 //infostream<<"smgr->drawAll()"<<std::endl;
3184                 {
3185                         TimeTaker timer("smgr");
3186                         smgr->drawAll();
3187                         
3188                         if(g_settings->getBool("anaglyph"))
3189                         {
3190                                 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3191                                 irr::core::vector3df oldTarget   = camera.getCameraNode()->getTarget();
3192
3193                                 irr::core::matrix4 startMatrix   = camera.getCameraNode()->getAbsoluteTransformation();
3194
3195                                 irr::core::vector3df focusPoint  = (camera.getCameraNode()->getTarget() -
3196                                                                                  camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3197                                                                                  camera.getCameraNode()->getAbsolutePosition() ;
3198
3199                                 //Left eye...
3200                                 irr::core::vector3df leftEye;
3201                                 irr::core::matrix4   leftMove;
3202
3203                                 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3204                                 leftEye=(startMatrix*leftMove).getTranslation();
3205
3206                                 //clear the depth buffer, and color
3207                                 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3208
3209                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3210                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3211                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + 
3212                                                                                                                          irr::scene::ESNRP_SOLID +
3213                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3214                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3215                                                                                                                          irr::scene::ESNRP_SHADOW;
3216
3217                                 camera.getCameraNode()->setPosition( leftEye );
3218                                 camera.getCameraNode()->setTarget( focusPoint );
3219
3220                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3221
3222
3223                                 //Right eye...
3224                                 irr::core::vector3df rightEye;
3225                                 irr::core::matrix4   rightMove;
3226
3227                                 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3228                                 rightEye=(startMatrix*rightMove).getTranslation();
3229
3230                                 //clear the depth buffer
3231                                 driver->clearZBuffer();
3232
3233                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3234                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3235                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3236                                                                                                                          irr::scene::ESNRP_SOLID +
3237                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3238                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3239                                                                                                                          irr::scene::ESNRP_SHADOW;
3240
3241                                 camera.getCameraNode()->setPosition( rightEye );
3242                                 camera.getCameraNode()->setTarget( focusPoint );
3243
3244                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3245
3246
3247                                 //driver->endScene();
3248
3249                                 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3250                                 driver->getOverrideMaterial().EnableFlags=0;
3251                                 driver->getOverrideMaterial().EnablePasses=0;
3252
3253                                 camera.getCameraNode()->setPosition( oldPosition );
3254                                 camera.getCameraNode()->setTarget( oldTarget );
3255                         }
3256
3257                         scenetime = timer.stop(true);
3258                 }
3259                 
3260                 {
3261                 //TimeTaker timer9("auxiliary drawings");
3262                 // 0ms
3263                 
3264                 //timer9.stop();
3265                 //TimeTaker //timer10("//timer10");
3266                 
3267                 video::SMaterial m;
3268                 //m.Thickness = 10;
3269                 m.Thickness = 3;
3270                 m.Lighting = false;
3271                 driver->setMaterial(m);
3272
3273                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3274
3275                 if (show_hud)
3276                         hud.drawSelectionBoxes(hilightboxes);
3277                 /*
3278                         Wielded tool
3279                 */
3280                 if(show_hud && (player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE))
3281                 {
3282                         // Warning: This clears the Z buffer.
3283                         camera.drawWieldedTool();
3284                 }
3285
3286                 /*
3287                         Post effects
3288                 */
3289                 {
3290                         client.getEnv().getClientMap().renderPostFx();
3291                 }
3292
3293                 /*
3294                         Profiler graph
3295                 */
3296                 if(show_profiler_graph)
3297                 {
3298                         graph.draw(10, screensize.Y - 10, driver, font);
3299                 }
3300
3301                 /*
3302                         Draw crosshair
3303                 */
3304                 if (show_hud)
3305                         hud.drawCrosshair();
3306                         
3307                 } // timer
3308
3309                 //timer10.stop();
3310                 //TimeTaker //timer11("//timer11");
3311
3312
3313                 /*
3314                         Draw hotbar
3315                 */
3316                 if (show_hud)
3317                 {
3318                         hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
3319                                         client.getHP(), client.getPlayerItem(), client.getBreath());
3320                 }
3321
3322                 /*
3323                         Damage flash
3324                 */
3325                 if(damage_flash > 0.0)
3326                 {
3327                         video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3328                         driver->draw2DRectangle(color,
3329                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
3330                                         NULL);
3331                         
3332                         damage_flash -= 100.0*dtime;
3333                 }
3334
3335                 /*
3336                         Damage camera tilt
3337                 */
3338                 if(player->hurt_tilt_timer > 0.0)
3339                 {
3340                         player->hurt_tilt_timer -= dtime*5;
3341                         if(player->hurt_tilt_timer < 0)
3342                                 player->hurt_tilt_strength = 0;
3343                 }
3344
3345                 /*
3346                         Draw lua hud items
3347                 */
3348                 if (show_hud)
3349                         hud.drawLuaElements();
3350
3351                 /*
3352                         Draw gui
3353                 */
3354                 // 0-1ms
3355                 guienv->drawAll();
3356
3357                 /*
3358                         End scene
3359                 */
3360                 {
3361                         TimeTaker timer("endScene");
3362                         endSceneX(driver);
3363                         endscenetime = timer.stop(true);
3364                 }
3365
3366                 drawtime = tt_draw.stop(true);
3367                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3368
3369                 /*
3370                         End of drawing
3371                 */
3372
3373                 static s16 lastFPS = 0;
3374                 //u16 fps = driver->getFPS();
3375                 u16 fps = (1.0/dtime_avg1);
3376
3377                 if (lastFPS != fps)
3378                 {
3379                         core::stringw str = L"Minetest [";
3380                         str += driver->getName();
3381                         str += "] FPS=";
3382                         str += fps;
3383
3384                         device->setWindowCaption(str.c_str());
3385                         lastFPS = fps;
3386                 }
3387
3388                 /*
3389                         Log times and stuff for visualization
3390                 */
3391                 Profiler::GraphValues values;
3392                 g_profiler->graphGet(values);
3393                 graph.put(values);
3394         }
3395
3396         /*
3397                 Drop stuff
3398         */
3399         if (clouds)
3400                 clouds->drop();
3401         if (gui_chat_console)
3402                 gui_chat_console->drop();
3403         if (sky)
3404                 sky->drop();
3405         clear_particles();
3406         
3407         /*
3408                 Draw a "shutting down" screen, which will be shown while the map
3409                 generator and other stuff quits
3410         */
3411         {
3412                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3413                 wchar_t* text = wgettext("Shutting down stuff...");
3414                 draw_load_screen(text, device, font, 0, -1, false);
3415                 delete[] text;
3416                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3417                 guienv->drawAll();
3418                 driver->endScene();
3419                 gui_shuttingdowntext->remove();*/
3420         }
3421
3422         chat_backend.addMessage(L"", L"# Disconnected.");
3423         chat_backend.addMessage(L"", L"");
3424
3425         // Client scope (client is destructed before destructing *def and tsrc)
3426         }while(0);
3427         } // try-catch
3428         catch(SerializationError &e)
3429         {
3430                 error_message = L"A serialization error occurred:\n"
3431                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3432                                 L" running a different version of Minetest.";
3433                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3434         }
3435         catch(ServerError &e)
3436         {
3437                 error_message = narrow_to_wide(e.what());
3438                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3439         }
3440         catch(ModError &e)
3441         {
3442                 errorstream<<e.what()<<std::endl;
3443                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3444         }
3445
3446
3447         
3448         if(!sound_is_dummy)
3449                 delete sound;
3450
3451         //has to be deleted first to stop all server threads
3452         delete server;
3453
3454         delete tsrc;
3455         delete shsrc;
3456         delete nodedef;
3457         delete itemdef;
3458
3459         //extended resource accounting
3460         infostream << "Irrlicht resources after cleanup:" << std::endl;
3461         infostream << "\tRemaining meshes   : "
3462                 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3463         infostream << "\tRemaining textures : "
3464                 << driver->getTextureCount() << std::endl;
3465         for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3466                 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3467                 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3468                                 << std::endl;
3469         }
3470         infostream << "\tRemaining materials: "
3471                 << driver-> getMaterialRendererCount ()
3472                 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;
3473 }
3474
3475