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