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