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