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