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