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