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