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