98ffac3d56a30c94855cd6857a26eb453852edfc
[oweals/minetest.git] / src / game.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 "client.h"
28 #include "server.h"
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
34 #include "tool.h"
35 #include "guiChatConsole.h"
36 #include "config.h"
37 #include "clouds.h"
38 #include "camera.h"
39 #include "farmesh.h"
40 #include "mapblock.h"
41 #include "settings.h"
42 #include "profiler.h"
43 #include "mainmenumanager.h"
44 #include "gettext.h"
45 #include "log.h"
46 #include "filesys.h"
47 // Needed for determining pointing to nodes
48 #include "nodedef.h"
49 #include "nodemetadata.h"
50 #include "main.h" // For g_settings
51 #include "itemdef.h"
52 #include "tile.h" // For TextureSource
53 #include "logoutputbuffer.h"
54 #include "subgame.h"
55 #include "quicktune_shortcutter.h"
56 #include "clientmap.h"
57 #include "sky.h"
58 #include "sound.h"
59 #if USE_SOUND
60         #include "sound_openal.h"
61 #endif
62 #include "event_manager.h"
63 #include <list>
64 #include "util/directiontables.h"
65
66 /*
67         Text input system
68 */
69
70 struct TextDestChat : public TextDest
71 {
72         TextDestChat(Client *client)
73         {
74                 m_client = client;
75         }
76         void gotText(std::wstring text)
77         {
78                 m_client->typeChatMessage(text);
79         }
80
81         Client *m_client;
82 };
83
84 struct TextDestNodeMetadata : public TextDest
85 {
86         TextDestNodeMetadata(v3s16 p, Client *client)
87         {
88                 m_p = p;
89                 m_client = client;
90         }
91         void gotText(std::wstring text)
92         {
93                 std::string ntext = wide_to_narrow(text);
94                 infostream<<"Changing text of a sign node: "
95                                 <<ntext<<std::endl;
96                 std::map<std::string, std::string> fields;
97                 fields["text"] = ntext;
98                 m_client->sendNodemetaFields(m_p, "", fields);
99         }
100
101         v3s16 m_p;
102         Client *m_client;
103 };
104
105 /* Respawn menu callback */
106
107 class MainRespawnInitiator: public IRespawnInitiator
108 {
109 public:
110         MainRespawnInitiator(bool *active, Client *client):
111                 m_active(active), m_client(client)
112         {
113                 *m_active = true;
114         }
115         void respawn()
116         {
117                 *m_active = false;
118                 m_client->sendRespawn();
119         }
120 private:
121         bool *m_active;
122         Client *m_client;
123 };
124
125 /* Form update callback */
126
127 class NodeMetadataFormSource: public IFormSource
128 {
129 public:
130         NodeMetadataFormSource(ClientMap *map, v3s16 p):
131                 m_map(map),
132                 m_p(p)
133         {
134         }
135         std::string getForm()
136         {
137                 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
138                 if(!meta)
139                         return "";
140                 return meta->getString("formspec");
141         }
142
143         ClientMap *m_map;
144         v3s16 m_p;
145 };
146
147 /*
148         Hotbar draw routine
149 */
150 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
151                 IGameDef *gamedef,
152                 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
153                 Inventory *inventory, s32 halfheartcount, u16 playeritem)
154 {
155         InventoryList *mainlist = inventory->getList("main");
156         if(mainlist == NULL)
157         {
158                 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
159                 return;
160         }
161         
162         s32 padding = imgsize/12;
163         //s32 height = imgsize + padding*2;
164         s32 width = itemcount*(imgsize+padding*2);
165         
166         // Position of upper left corner of bar
167         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
168         
169         // Draw background color
170         /*core::rect<s32> barrect(0,0,width,height);
171         barrect += pos;
172         video::SColor bgcolor(255,128,128,128);
173         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
174
175         core::rect<s32> imgrect(0,0,imgsize,imgsize);
176
177         for(s32 i=0; i<itemcount; i++)
178         {
179                 const ItemStack &item = mainlist->getItem(i);
180                 
181                 core::rect<s32> rect = imgrect + pos
182                                 + v2s32(padding+i*(imgsize+padding*2), padding);
183                 
184                 if(playeritem == i)
185                 {
186                         video::SColor c_outside(255,255,0,0);
187                         //video::SColor c_outside(255,0,0,0);
188                         //video::SColor c_inside(255,192,192,192);
189                         s32 x1 = rect.UpperLeftCorner.X;
190                         s32 y1 = rect.UpperLeftCorner.Y;
191                         s32 x2 = rect.LowerRightCorner.X;
192                         s32 y2 = rect.LowerRightCorner.Y;
193                         // Black base borders
194                         driver->draw2DRectangle(c_outside,
195                                         core::rect<s32>(
196                                                 v2s32(x1 - padding, y1 - padding),
197                                                 v2s32(x2 + padding, y1)
198                                         ), NULL);
199                         driver->draw2DRectangle(c_outside,
200                                         core::rect<s32>(
201                                                 v2s32(x1 - padding, y2),
202                                                 v2s32(x2 + padding, y2 + padding)
203                                         ), NULL);
204                         driver->draw2DRectangle(c_outside,
205                                         core::rect<s32>(
206                                                 v2s32(x1 - padding, y1),
207                                                 v2s32(x1, y2)
208                                         ), NULL);
209                         driver->draw2DRectangle(c_outside,
210                                         core::rect<s32>(
211                                                 v2s32(x2, y1),
212                                                 v2s32(x2 + padding, y2)
213                                         ), NULL);
214                         /*// Light inside borders
215                         driver->draw2DRectangle(c_inside,
216                                         core::rect<s32>(
217                                                 v2s32(x1 - padding/2, y1 - padding/2),
218                                                 v2s32(x2 + padding/2, y1)
219                                         ), NULL);
220                         driver->draw2DRectangle(c_inside,
221                                         core::rect<s32>(
222                                                 v2s32(x1 - padding/2, y2),
223                                                 v2s32(x2 + padding/2, y2 + padding/2)
224                                         ), NULL);
225                         driver->draw2DRectangle(c_inside,
226                                         core::rect<s32>(
227                                                 v2s32(x1 - padding/2, y1),
228                                                 v2s32(x1, y2)
229                                         ), NULL);
230                         driver->draw2DRectangle(c_inside,
231                                         core::rect<s32>(
232                                                 v2s32(x2, y1),
233                                                 v2s32(x2 + padding/2, y2)
234                                         ), NULL);
235                         */
236                 }
237
238                 video::SColor bgcolor2(128,0,0,0);
239                 driver->draw2DRectangle(bgcolor2, rect, NULL);
240                 drawItemStack(driver, font, item, rect, NULL, gamedef);
241         }
242         
243         /*
244                 Draw hearts
245         */
246         video::ITexture *heart_texture =
247                 gamedef->getTextureSource()->getTextureRaw("heart.png");
248         if(heart_texture)
249         {
250                 v2s32 p = pos + v2s32(0, -20);
251                 for(s32 i=0; i<halfheartcount/2; i++)
252                 {
253                         const video::SColor color(255,255,255,255);
254                         const video::SColor colors[] = {color,color,color,color};
255                         core::rect<s32> rect(0,0,16,16);
256                         rect += p;
257                         driver->draw2DImage(heart_texture, rect,
258                                 core::rect<s32>(core::position2d<s32>(0,0),
259                                 core::dimension2di(heart_texture->getOriginalSize())),
260                                 NULL, colors, true);
261                         p += v2s32(16,0);
262                 }
263                 if(halfheartcount % 2 == 1)
264                 {
265                         const video::SColor color(255,255,255,255);
266                         const video::SColor colors[] = {color,color,color,color};
267                         core::rect<s32> rect(0,0,16/2,16);
268                         rect += p;
269                         core::dimension2di srcd(heart_texture->getOriginalSize());
270                         srcd.Width /= 2;
271                         driver->draw2DImage(heart_texture, rect,
272                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
273                                 NULL, colors, true);
274                         p += v2s32(16,0);
275                 }
276         }
277 }
278
279 /*
280         Check if a node is pointable
281 */
282 inline bool isPointableNode(const MapNode& n,
283                 Client *client, bool liquids_pointable)
284 {
285         const ContentFeatures &features = client->getNodeDefManager()->get(n);
286         return features.pointable ||
287                 (liquids_pointable && features.isLiquid());
288 }
289
290 /*
291         Find what the player is pointing at
292 */
293 PointedThing getPointedThing(Client *client, v3f player_position,
294                 v3f camera_direction, v3f camera_position,
295                 core::line3d<f32> shootline, f32 d,
296                 bool liquids_pointable,
297                 bool look_for_object,
298                 std::vector<aabb3f> &hilightboxes,
299                 ClientActiveObject *&selected_object)
300 {
301         PointedThing result;
302
303         hilightboxes.clear();
304         selected_object = NULL;
305
306         INodeDefManager *nodedef = client->getNodeDefManager();
307         ClientMap &map = client->getEnv().getClientMap();
308
309         // First try to find a pointed at active object
310         if(look_for_object)
311         {
312                 selected_object = client->getSelectedActiveObject(d*BS,
313                                 camera_position, shootline);
314
315                 if(selected_object != NULL)
316                 {
317                         if(selected_object->doShowSelectionBox())
318                         {
319                                 aabb3f *selection_box = selected_object->getSelectionBox();
320                                 // Box should exist because object was
321                                 // returned in the first place
322                                 assert(selection_box);
323
324                                 v3f pos = selected_object->getPosition();
325                                 hilightboxes.push_back(aabb3f(
326                                                 selection_box->MinEdge + pos,
327                                                 selection_box->MaxEdge + pos));
328                         }
329
330
331                         result.type = POINTEDTHING_OBJECT;
332                         result.object_id = selected_object->getId();
333                         return result;
334                 }
335         }
336
337         // That didn't work, try to find a pointed at node
338
339         f32 mindistance = BS * 1001;
340         
341         v3s16 pos_i = floatToInt(player_position, BS);
342
343         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
344                         <<std::endl;*/
345
346         s16 a = d;
347         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
348         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
349         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
350         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
351         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
352         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
353         
354         for(s16 y = ystart; y <= yend; y++)
355         for(s16 z = zstart; z <= zend; z++)
356         for(s16 x = xstart; x <= xend; x++)
357         {
358                 MapNode n;
359                 try
360                 {
361                         n = map.getNode(v3s16(x,y,z));
362                 }
363                 catch(InvalidPositionException &e)
364                 {
365                         continue;
366                 }
367                 if(!isPointableNode(n, client, liquids_pointable))
368                         continue;
369
370                 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
371
372                 v3s16 np(x,y,z);
373                 v3f npf = intToFloat(np, BS);
374
375                 for(std::vector<aabb3f>::const_iterator
376                                 i = boxes.begin();
377                                 i != boxes.end(); i++)
378                 {
379                         aabb3f box = *i;
380                         box.MinEdge += npf;
381                         box.MaxEdge += npf;
382
383                         for(u16 j=0; j<6; j++)
384                         {
385                                 v3s16 facedir = g_6dirs[j];
386                                 aabb3f facebox = box;
387
388                                 f32 d = 0.001*BS;
389                                 if(facedir.X > 0)
390                                         facebox.MinEdge.X = facebox.MaxEdge.X-d;
391                                 else if(facedir.X < 0)
392                                         facebox.MaxEdge.X = facebox.MinEdge.X+d;
393                                 else if(facedir.Y > 0)
394                                         facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
395                                 else if(facedir.Y < 0)
396                                         facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
397                                 else if(facedir.Z > 0)
398                                         facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
399                                 else if(facedir.Z < 0)
400                                         facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
401
402                                 v3f centerpoint = facebox.getCenter();
403                                 f32 distance = (centerpoint - camera_position).getLength();
404                                 if(distance >= mindistance)
405                                         continue;
406                                 if(!facebox.intersectsWithLine(shootline))
407                                         continue;
408
409                                 v3s16 np_above = np + facedir;
410
411                                 result.type = POINTEDTHING_NODE;
412                                 result.node_undersurface = np;
413                                 result.node_abovesurface = np_above;
414                                 mindistance = distance;
415
416                                 hilightboxes.clear();
417                                 for(std::vector<aabb3f>::const_iterator
418                                                 i2 = boxes.begin();
419                                                 i2 != boxes.end(); i2++)
420                                 {
421                                         aabb3f box = *i2;
422                                         box.MinEdge += npf + v3f(-d,-d,-d);
423                                         box.MaxEdge += npf + v3f(d,d,d);
424                                         hilightboxes.push_back(box);
425                                 }
426                         }
427                 }
428         } // for coords
429
430         return result;
431 }
432
433 /*
434         Draws a screen with a single text on it.
435         Text will be removed when the screen is drawn the next time.
436 */
437 /*gui::IGUIStaticText **/
438 void draw_load_screen(const std::wstring &text,
439                 video::IVideoDriver* driver, gui::IGUIFont* font)
440 {
441         v2u32 screensize = driver->getScreenSize();
442         const wchar_t *loadingtext = text.c_str();
443         core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
444         core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
445         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
446         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
447
448         gui::IGUIStaticText *guitext = guienv->addStaticText(
449                         loadingtext, textrect, false, false);
450         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
451
452         driver->beginScene(true, true, video::SColor(255,0,0,0));
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,
465                 u32 show_profiler, 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         void registerReceiver(MtEventManager *mgr)
740         {
741                 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
742                 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
743                 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
744                 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
745                 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
746                 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
747         }
748
749         void step(float dtime)
750         {
751                 m_player_step_timer -= dtime;
752         }
753 };
754
755 // Locally stored sounds don't need to be preloaded because of this
756 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
757 {
758         std::set<std::string> m_fetched;
759 public:
760
761         void fetchSounds(const std::string &name,
762                         std::set<std::string> &dst_paths,
763                         std::set<std::string> &dst_datas)
764         {
765                 if(m_fetched.count(name))
766                         return;
767                 m_fetched.insert(name);
768                 std::string base = porting::path_share + DIR_DELIM + "testsounds";
769                 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
770                 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
771                 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
772                 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
773                 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
774                 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
775                 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
776                 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
777                 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
778                 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
779                 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
780         }
781 };
782
783 void the_game(
784         bool &kill,
785         bool random_input,
786         InputHandler *input,
787         IrrlichtDevice *device,
788         gui::IGUIFont* font,
789         std::string map_dir,
790         std::string playername,
791         std::string password,
792         std::string address, // If "", local server is used
793         u16 port,
794         std::wstring &error_message,
795         std::string configpath,
796         ChatBackend &chat_backend,
797         const SubgameSpec &gamespec, // Used for local game,
798         bool simple_singleplayer_mode
799 )
800 {
801         video::IVideoDriver* driver = device->getVideoDriver();
802         scene::ISceneManager* smgr = device->getSceneManager();
803         
804         // Calculate text height using the font
805         u32 text_height = font->getDimension(L"Random test string").Height;
806
807         v2u32 screensize(0,0);
808         v2u32 last_screensize(0,0);
809         screensize = driver->getScreenSize();
810
811         const s32 hotbar_itemcount = 8;
812         //const s32 hotbar_imagesize = 36;
813         //const s32 hotbar_imagesize = 64;
814         s32 hotbar_imagesize = 48;
815         
816         /*
817                 Draw "Loading" screen
818         */
819
820         draw_load_screen(L"Loading...", driver, font);
821         
822         // Create texture source
823         IWritableTextureSource *tsrc = createTextureSource(device);
824         
825         // These will be filled by data received from the server
826         // Create item definition manager
827         IWritableItemDefManager *itemdef = createItemDefManager();
828         // Create node definition manager
829         IWritableNodeDefManager *nodedef = createNodeDefManager();
830         
831         // Sound fetcher (useful when testing)
832         GameOnDemandSoundFetcher soundfetcher;
833
834         // Sound manager
835         ISoundManager *sound = NULL;
836         bool sound_is_dummy = false;
837 #if USE_SOUND
838         if(g_settings->getBool("enable_sound")){
839                 infostream<<"Attempting to use OpenAL audio"<<std::endl;
840                 sound = createOpenALSoundManager(&soundfetcher);
841                 if(!sound)
842                         infostream<<"Failed to initialize OpenAL audio"<<std::endl;
843         } else {
844                 infostream<<"Sound disabled."<<std::endl;
845         }
846 #endif
847         if(!sound){
848                 infostream<<"Using dummy audio."<<std::endl;
849                 sound = &dummySoundManager;
850                 sound_is_dummy = true;
851         }
852
853         // Event manager
854         EventManager eventmgr;
855
856         // Sound maker
857         SoundMaker soundmaker(sound, nodedef);
858         soundmaker.registerReceiver(&eventmgr);
859         
860         // Add chat log output for errors to be shown in chat
861         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
862
863         // Create UI for modifying quicktune values
864         QuicktuneShortcutter quicktune;
865
866         /*
867                 Create server.
868                 SharedPtr will delete it when it goes out of scope.
869         */
870         SharedPtr<Server> server;
871         if(address == ""){
872                 draw_load_screen(L"Creating server...", driver, font);
873                 infostream<<"Creating server"<<std::endl;
874                 server = new Server(map_dir, configpath, gamespec,
875                                 simple_singleplayer_mode);
876                 server->start(port);
877         }
878
879         try{
880         do{ // Client scope (breakable do-while(0))
881         
882         /*
883                 Create client
884         */
885
886         draw_load_screen(L"Creating client...", driver, font);
887         infostream<<"Creating client"<<std::endl;
888         
889         MapDrawControl draw_control;
890
891         Client client(device, playername.c_str(), password, draw_control,
892                         tsrc, itemdef, nodedef, sound, &eventmgr);
893         
894         // Client acts as our GameDef
895         IGameDef *gamedef = &client;
896                         
897         draw_load_screen(L"Resolving address...", driver, font);
898         Address connect_address(0,0,0,0, port);
899         try{
900                 if(address == "")
901                         //connect_address.Resolve("localhost");
902                         connect_address.setAddress(127,0,0,1);
903                 else
904                         connect_address.Resolve(address.c_str());
905         }
906         catch(ResolveError &e)
907         {
908                 error_message = L"Couldn't resolve address";
909                 errorstream<<wide_to_narrow(error_message)<<std::endl;
910                 // Break out of client scope
911                 break;
912         }
913
914         /*
915                 Attempt to connect to the server
916         */
917         
918         infostream<<"Connecting to server at ";
919         connect_address.print(&infostream);
920         infostream<<std::endl;
921         client.connect(connect_address);
922         
923         /*
924                 Wait for server to accept connection
925         */
926         bool could_connect = false;
927         bool connect_aborted = false;
928         try{
929                 float frametime = 0.033;
930                 float time_counter = 0.0;
931                 input->clear();
932                 while(device->run())
933                 {
934                         // Update client and server
935                         client.step(frametime);
936                         if(server != NULL)
937                                 server->step(frametime);
938                         
939                         // End condition
940                         if(client.connectedAndInitialized()){
941                                 could_connect = true;
942                                 break;
943                         }
944                         // Break conditions
945                         if(client.accessDenied()){
946                                 error_message = L"Access denied. Reason: "
947                                                 +client.accessDeniedReason();
948                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
949                                 break;
950                         }
951                         if(input->wasKeyDown(EscapeKey)){
952                                 connect_aborted = true;
953                                 infostream<<"Connect aborted [Escape]"<<std::endl;
954                                 break;
955                         }
956                         
957                         // Display status
958                         std::wostringstream ss;
959                         ss<<L"Connecting to server... (press Escape to cancel)\n";
960                         std::wstring animation = L"/-\\|";
961                         ss<<animation[(int)(time_counter/0.2)%4];
962                         draw_load_screen(ss.str(), driver, font);
963                         
964                         // Delay a bit
965                         sleep_ms(1000*frametime);
966                         time_counter += frametime;
967                 }
968         }
969         catch(con::PeerNotFoundException &e)
970         {}
971         
972         /*
973                 Handle failure to connect
974         */
975         if(!could_connect){
976                 if(error_message == L"" && !connect_aborted){
977                         error_message = L"Connection failed";
978                         errorstream<<wide_to_narrow(error_message)<<std::endl;
979                 }
980                 // Break out of client scope
981                 break;
982         }
983         
984         /*
985                 Wait until content has been received
986         */
987         bool got_content = false;
988         bool content_aborted = false;
989         {
990                 float frametime = 0.033;
991                 float time_counter = 0.0;
992                 input->clear();
993                 while(device->run())
994                 {
995                         // Update client and server
996                         client.step(frametime);
997                         if(server != NULL)
998                                 server->step(frametime);
999                         
1000                         // End condition
1001                         if(client.texturesReceived() &&
1002                                         client.itemdefReceived() &&
1003                                         client.nodedefReceived()){
1004                                 got_content = true;
1005                                 break;
1006                         }
1007                         // Break conditions
1008                         if(!client.connectedAndInitialized()){
1009                                 error_message = L"Client disconnected";
1010                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1011                                 break;
1012                         }
1013                         if(input->wasKeyDown(EscapeKey)){
1014                                 content_aborted = true;
1015                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1016                                 break;
1017                         }
1018                         
1019                         // Display status
1020                         std::wostringstream ss;
1021                         ss<<L"Waiting content... (press Escape to cancel)\n";
1022
1023                         ss<<(client.itemdefReceived()?L"[X]":L"[  ]");
1024                         ss<<L" Item definitions\n";
1025                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
1026                         ss<<L" Node definitions\n";
1027                         ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1028                         ss<<L" Media\n";
1029
1030                         draw_load_screen(ss.str(), driver, font);
1031                         
1032                         // Delay a bit
1033                         sleep_ms(1000*frametime);
1034                         time_counter += frametime;
1035                 }
1036         }
1037
1038         if(!got_content){
1039                 if(error_message == L"" && !content_aborted){
1040                         error_message = L"Something failed";
1041                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1042                 }
1043                 // Break out of client scope
1044                 break;
1045         }
1046
1047         /*
1048                 After all content has been received:
1049                 Update cached textures, meshes and materials
1050         */
1051         client.afterContentReceived();
1052
1053         /*
1054                 Create the camera node
1055         */
1056         Camera camera(smgr, draw_control, gamedef);
1057         if (!camera.successfullyCreated(error_message))
1058                 return;
1059
1060         f32 camera_yaw = 0; // "right/left"
1061         f32 camera_pitch = 0; // "up/down"
1062
1063         /*
1064                 Clouds
1065         */
1066         
1067         Clouds *clouds = NULL;
1068         if(g_settings->getBool("enable_clouds"))
1069         {
1070                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1071         }
1072
1073         /*
1074                 Skybox thingy
1075         */
1076
1077         Sky *sky = NULL;
1078         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1079         
1080         /*
1081                 FarMesh
1082         */
1083
1084         FarMesh *farmesh = NULL;
1085         if(g_settings->getBool("enable_farmesh"))
1086         {
1087                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1088         }
1089
1090         /*
1091                 A copy of the local inventory
1092         */
1093         Inventory local_inventory(itemdef);
1094
1095         /*
1096                 Find out size of crack animation
1097         */
1098         int crack_animation_length = 5;
1099         {
1100                 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1101                 v2u32 size = t->getOriginalSize();
1102                 crack_animation_length = size.Y / size.X;
1103         }
1104
1105         /*
1106                 Add some gui stuff
1107         */
1108
1109         // First line of debug text
1110         gui::IGUIStaticText *guitext = guienv->addStaticText(
1111                         L"Minetest-c55",
1112                         core::rect<s32>(5, 5, 795, 5+text_height),
1113                         false, false);
1114         // Second line of debug text
1115         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1116                         L"",
1117                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1118                         false, false);
1119         // At the middle of the screen
1120         // Object infos are shown in this
1121         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1122                         L"",
1123                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1124                         false, false);
1125         
1126         // Status text (displays info when showing and hiding GUI stuff, etc.)
1127         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1128                         L"<Status>",
1129                         core::rect<s32>(0,0,0,0),
1130                         false, false);
1131         guitext_status->setVisible(false);
1132         
1133         std::wstring statustext;
1134         float statustext_time = 0;
1135         
1136         // Chat text
1137         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1138                         L"",
1139                         core::rect<s32>(0,0,0,0),
1140                         //false, false); // Disable word wrap as of now
1141                         false, true);
1142         // Remove stale "recent" chat messages from previous connections
1143         chat_backend.clearRecentChat();
1144         // Chat backend and console
1145         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1146         
1147         // Profiler text (size is updated when text is updated)
1148         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1149                         L"<Profiler>",
1150                         core::rect<s32>(0,0,0,0),
1151                         false, false);
1152         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1153         guitext_profiler->setVisible(false);
1154         
1155         /*
1156                 Some statistics are collected in these
1157         */
1158         u32 drawtime = 0;
1159         u32 beginscenetime = 0;
1160         u32 scenetime = 0;
1161         u32 endscenetime = 0;
1162         
1163         float recent_turn_speed = 0.0;
1164         
1165         ProfilerGraph graph;
1166         // Initially clear the profiler
1167         Profiler::GraphValues dummyvalues;
1168         g_profiler->graphGet(dummyvalues);
1169
1170         float nodig_delay_timer = 0.0;
1171         float dig_time = 0.0;
1172         u16 dig_index = 0;
1173         PointedThing pointed_old;
1174         bool digging = false;
1175         bool ldown_for_dig = false;
1176
1177         float damage_flash_timer = 0;
1178         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1179
1180         const float object_hit_delay = 0.2;
1181         float object_hit_delay_timer = 0.0;
1182         float time_from_last_punch = 10;
1183
1184         bool invert_mouse = g_settings->getBool("invert_mouse");
1185
1186         bool respawn_menu_active = false;
1187         bool update_wielded_item_trigger = false;
1188
1189         bool show_hud = true;
1190         bool show_chat = true;
1191         bool force_fog_off = false;
1192         bool disable_camera_update = false;
1193         bool show_debug = g_settings->getBool("show_debug");
1194         bool show_profiler_graph = false;
1195         u32 show_profiler = 0;
1196         u32 show_profiler_max = 3;  // Number of pages
1197
1198         float time_of_day = 0;
1199         float time_of_day_smooth = 0;
1200
1201         /*
1202                 Main loop
1203         */
1204
1205         bool first_loop_after_window_activation = true;
1206
1207         // TODO: Convert the static interval timers to these
1208         // Interval limiter for profiler
1209         IntervalLimiter m_profiler_interval;
1210
1211         // Time is in milliseconds
1212         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1213         // NOTE: So we have to use getTime() and call run()s between them
1214         u32 lasttime = device->getTimer()->getTime();
1215
1216         for(;;)
1217         {
1218                 if(device->run() == false || kill == true)
1219                         break;
1220
1221                 // Time of frame without fps limit
1222                 float busytime;
1223                 u32 busytime_u32;
1224                 {
1225                         // not using getRealTime is necessary for wine
1226                         u32 time = device->getTimer()->getTime();
1227                         if(time > lasttime)
1228                                 busytime_u32 = time - lasttime;
1229                         else
1230                                 busytime_u32 = 0;
1231                         busytime = busytime_u32 / 1000.0;
1232                 }
1233                 
1234                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1235
1236                 // Necessary for device->getTimer()->getTime()
1237                 device->run();
1238
1239                 /*
1240                         FPS limiter
1241                 */
1242
1243                 {
1244                         float fps_max = g_settings->getFloat("fps_max");
1245                         u32 frametime_min = 1000./fps_max;
1246                         
1247                         if(busytime_u32 < frametime_min)
1248                         {
1249                                 u32 sleeptime = frametime_min - busytime_u32;
1250                                 device->sleep(sleeptime);
1251                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1252                         }
1253                 }
1254
1255                 // Necessary for device->getTimer()->getTime()
1256                 device->run();
1257
1258                 /*
1259                         Time difference calculation
1260                 */
1261                 f32 dtime; // in seconds
1262                 
1263                 u32 time = device->getTimer()->getTime();
1264                 if(time > lasttime)
1265                         dtime = (time - lasttime) / 1000.0;
1266                 else
1267                         dtime = 0;
1268                 lasttime = time;
1269
1270                 g_profiler->graphAdd("mainloop_dtime", dtime);
1271
1272                 /* Run timers */
1273
1274                 if(nodig_delay_timer >= 0)
1275                         nodig_delay_timer -= dtime;
1276                 if(object_hit_delay_timer >= 0)
1277                         object_hit_delay_timer -= dtime;
1278                 time_from_last_punch += dtime;
1279                 
1280                 g_profiler->add("Elapsed time", dtime);
1281                 g_profiler->avg("FPS", 1./dtime);
1282
1283                 /*
1284                         Time average and jitter calculation
1285                 */
1286
1287                 static f32 dtime_avg1 = 0.0;
1288                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1289                 f32 dtime_jitter1 = dtime - dtime_avg1;
1290
1291                 static f32 dtime_jitter1_max_sample = 0.0;
1292                 static f32 dtime_jitter1_max_fraction = 0.0;
1293                 {
1294                         static f32 jitter1_max = 0.0;
1295                         static f32 counter = 0.0;
1296                         if(dtime_jitter1 > jitter1_max)
1297                                 jitter1_max = dtime_jitter1;
1298                         counter += dtime;
1299                         if(counter > 0.0)
1300                         {
1301                                 counter -= 3.0;
1302                                 dtime_jitter1_max_sample = jitter1_max;
1303                                 dtime_jitter1_max_fraction
1304                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1305                                 jitter1_max = 0.0;
1306                         }
1307                 }
1308                 
1309                 /*
1310                         Busytime average and jitter calculation
1311                 */
1312
1313                 static f32 busytime_avg1 = 0.0;
1314                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1315                 f32 busytime_jitter1 = busytime - busytime_avg1;
1316                 
1317                 static f32 busytime_jitter1_max_sample = 0.0;
1318                 static f32 busytime_jitter1_min_sample = 0.0;
1319                 {
1320                         static f32 jitter1_max = 0.0;
1321                         static f32 jitter1_min = 0.0;
1322                         static f32 counter = 0.0;
1323                         if(busytime_jitter1 > jitter1_max)
1324                                 jitter1_max = busytime_jitter1;
1325                         if(busytime_jitter1 < jitter1_min)
1326                                 jitter1_min = busytime_jitter1;
1327                         counter += dtime;
1328                         if(counter > 0.0){
1329                                 counter -= 3.0;
1330                                 busytime_jitter1_max_sample = jitter1_max;
1331                                 busytime_jitter1_min_sample = jitter1_min;
1332                                 jitter1_max = 0.0;
1333                                 jitter1_min = 0.0;
1334                         }
1335                 }
1336
1337                 /*
1338                         Handle miscellaneous stuff
1339                 */
1340                 
1341                 if(client.accessDenied())
1342                 {
1343                         error_message = L"Access denied. Reason: "
1344                                         +client.accessDeniedReason();
1345                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1346                         break;
1347                 }
1348
1349                 if(g_gamecallback->disconnect_requested)
1350                 {
1351                         g_gamecallback->disconnect_requested = false;
1352                         break;
1353                 }
1354
1355                 if(g_gamecallback->changepassword_requested)
1356                 {
1357                         (new GUIPasswordChange(guienv, guiroot, -1,
1358                                 &g_menumgr, &client))->drop();
1359                         g_gamecallback->changepassword_requested = false;
1360                 }
1361
1362                 /*
1363                         Process TextureSource's queue
1364                 */
1365                 tsrc->processQueue();
1366
1367                 /*
1368                         Random calculations
1369                 */
1370                 last_screensize = screensize;
1371                 screensize = driver->getScreenSize();
1372                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1373                 //bool screensize_changed = screensize != last_screensize;
1374
1375                 // Resize hotbar
1376                 if(screensize.Y <= 800)
1377                         hotbar_imagesize = 32;
1378                 else if(screensize.Y <= 1280)
1379                         hotbar_imagesize = 48;
1380                 else
1381                         hotbar_imagesize = 64;
1382                 
1383                 // Hilight boxes collected during the loop and displayed
1384                 std::vector<aabb3f> hilightboxes;
1385                 
1386                 // Info text
1387                 std::wstring infotext;
1388
1389                 /*
1390                         Debug info for client
1391                 */
1392                 {
1393                         static float counter = 0.0;
1394                         counter -= dtime;
1395                         if(counter < 0)
1396                         {
1397                                 counter = 30.0;
1398                                 client.printDebugInfo(infostream);
1399                         }
1400                 }
1401
1402                 /*
1403                         Profiler
1404                 */
1405                 float profiler_print_interval =
1406                                 g_settings->getFloat("profiler_print_interval");
1407                 bool print_to_log = true;
1408                 if(profiler_print_interval == 0){
1409                         print_to_log = false;
1410                         profiler_print_interval = 5;
1411                 }
1412                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1413                 {
1414                         if(print_to_log){
1415                                 infostream<<"Profiler:"<<std::endl;
1416                                 g_profiler->print(infostream);
1417                         }
1418
1419                         update_profiler_gui(guitext_profiler, font, text_height,
1420                                         show_profiler, show_profiler_max);
1421
1422                         g_profiler->clear();
1423                 }
1424
1425                 /*
1426                         Direct handling of user input
1427                 */
1428                 
1429                 // Reset input if window not active or some menu is active
1430                 if(device->isWindowActive() == false
1431                                 || noMenuActive() == false
1432                                 || guienv->hasFocus(gui_chat_console))
1433                 {
1434                         input->clear();
1435                 }
1436
1437                 // Input handler step() (used by the random input generator)
1438                 input->step(dtime);
1439
1440                 /*
1441                         Launch menus and trigger stuff according to keys
1442                 */
1443                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1444                 {
1445                         // drop selected item
1446                         IDropAction *a = new IDropAction();
1447                         a->count = 0;
1448                         a->from_inv.setCurrentPlayer();
1449                         a->from_list = "main";
1450                         a->from_i = client.getPlayerItem();
1451                         client.inventoryAction(a);
1452                 }
1453                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1454                 {
1455                         infostream<<"the_game: "
1456                                         <<"Launching inventory"<<std::endl;
1457                         
1458                         GUIInventoryMenu *menu =
1459                                 new GUIInventoryMenu(guienv, guiroot, -1,
1460                                         &g_menumgr,
1461                                         &client, gamedef);
1462
1463                         InventoryLocation inventoryloc;
1464                         inventoryloc.setCurrentPlayer();
1465
1466                         menu->setFormSpec(
1467                                 "invsize[8,7.5;]"
1468                                 //"image[1,0.6;1,2;player.png]"
1469                                 "list[current_player;main;0,3.5;8,4;]"
1470                                 "list[current_player;craft;3,0;3,3;]"
1471                                 "list[current_player;craftpreview;7,1;1,1;]"
1472                                 , inventoryloc);
1473
1474                         menu->drop();
1475                 }
1476                 else if(input->wasKeyDown(EscapeKey))
1477                 {
1478                         infostream<<"the_game: "
1479                                         <<"Launching pause menu"<<std::endl;
1480                         // It will delete itself by itself
1481                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1482                                         &g_menumgr, simple_singleplayer_mode))->drop();
1483
1484                         // Move mouse cursor on top of the disconnect button
1485                         if(simple_singleplayer_mode)
1486                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1487                         else
1488                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1489                 }
1490                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1491                 {
1492                         TextDest *dest = new TextDestChat(&client);
1493
1494                         (new GUITextInputMenu(guienv, guiroot, -1,
1495                                         &g_menumgr, dest,
1496                                         L""))->drop();
1497                 }
1498                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1499                 {
1500                         TextDest *dest = new TextDestChat(&client);
1501
1502                         (new GUITextInputMenu(guienv, guiroot, -1,
1503                                         &g_menumgr, dest,
1504                                         L"/"))->drop();
1505                 }
1506                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1507                 {
1508                         if (!gui_chat_console->isOpenInhibited())
1509                         {
1510                                 // Open up to over half of the screen
1511                                 gui_chat_console->openConsole(0.6);
1512                                 guienv->setFocus(gui_chat_console);
1513                         }
1514                 }
1515                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1516                 {
1517                         if(g_settings->getBool("free_move"))
1518                         {
1519                                 g_settings->set("free_move","false");
1520                                 statustext = L"free_move disabled";
1521                                 statustext_time = 0;
1522                         }
1523                         else
1524                         {
1525                                 g_settings->set("free_move","true");
1526                                 statustext = L"free_move enabled";
1527                                 statustext_time = 0;
1528                                 if(!client.checkPrivilege("fly"))
1529                                         statustext += L" (note: no 'fly' privilege)";
1530                         }
1531                 }
1532                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1533                 {
1534                         if(g_settings->getBool("fast_move"))
1535                         {
1536                                 g_settings->set("fast_move","false");
1537                                 statustext = L"fast_move disabled";
1538                                 statustext_time = 0;
1539                         }
1540                         else
1541                         {
1542                                 g_settings->set("fast_move","true");
1543                                 statustext = L"fast_move enabled";
1544                                 statustext_time = 0;
1545                                 if(!client.checkPrivilege("fast"))
1546                                         statustext += L" (note: no 'fast' privilege)";
1547                         }
1548                 }
1549                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1550                 {
1551                         irr::video::IImage* const image = driver->createScreenShot(); 
1552                         if (image) { 
1553                                 irr::c8 filename[256]; 
1554                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1555                                                  g_settings->get("screenshot_path").c_str(),
1556                                                  device->getTimer()->getRealTime()); 
1557                                 if (driver->writeImageToFile(image, filename)) {
1558                                         std::wstringstream sstr;
1559                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1560                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1561                                         statustext = sstr.str();
1562                                         statustext_time = 0;
1563                                 } else{
1564                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1565                                 }
1566                                 image->drop(); 
1567                         }                        
1568                 }
1569                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1570                 {
1571                         show_hud = !show_hud;
1572                         if(show_hud)
1573                                 statustext = L"HUD shown";
1574                         else
1575                                 statustext = L"HUD hidden";
1576                         statustext_time = 0;
1577                 }
1578                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1579                 {
1580                         show_chat = !show_chat;
1581                         if(show_chat)
1582                                 statustext = L"Chat shown";
1583                         else
1584                                 statustext = L"Chat hidden";
1585                         statustext_time = 0;
1586                 }
1587                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1588                 {
1589                         force_fog_off = !force_fog_off;
1590                         if(force_fog_off)
1591                                 statustext = L"Fog disabled";
1592                         else
1593                                 statustext = L"Fog enabled";
1594                         statustext_time = 0;
1595                 }
1596                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1597                 {
1598                         disable_camera_update = !disable_camera_update;
1599                         if(disable_camera_update)
1600                                 statustext = L"Camera update disabled";
1601                         else
1602                                 statustext = L"Camera update enabled";
1603                         statustext_time = 0;
1604                 }
1605                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1606                 {
1607                         // Initial / 3x toggle: Chat only
1608                         // 1x toggle: Debug text with chat
1609                         // 2x toggle: Debug text with profiler graph
1610                         if(!show_debug)
1611                         {
1612                                 show_debug = true;
1613                                 show_profiler_graph = false;
1614                                 statustext = L"Debug info shown";
1615                                 statustext_time = 0;
1616                         }
1617                         else if(show_profiler_graph)
1618                         {
1619                                 show_debug = false;
1620                                 show_profiler_graph = false;
1621                                 statustext = L"Debug info and profiler graph hidden";
1622                                 statustext_time = 0;
1623                         }
1624                         else
1625                         {
1626                                 show_profiler_graph = true;
1627                                 statustext = L"Profiler graph shown";
1628                                 statustext_time = 0;
1629                         }
1630                 }
1631                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1632                 {
1633                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1634
1635                         // FIXME: This updates the profiler with incomplete values
1636                         update_profiler_gui(guitext_profiler, font, text_height,
1637                                         show_profiler, show_profiler_max);
1638
1639                         if(show_profiler != 0)
1640                         {
1641                                 std::wstringstream sstr;
1642                                 sstr<<"Profiler shown (page "<<show_profiler
1643                                         <<" of "<<show_profiler_max<<")";
1644                                 statustext = sstr.str();
1645                                 statustext_time = 0;
1646                         }
1647                         else
1648                         {
1649                                 statustext = L"Profiler hidden";
1650                                 statustext_time = 0;
1651                         }
1652                 }
1653                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1654                 {
1655                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1656                         s16 range_new = range + 10;
1657                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1658                         statustext = narrow_to_wide(
1659                                         "Minimum viewing range changed to "
1660                                         + itos(range_new));
1661                         statustext_time = 0;
1662                 }
1663                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1664                 {
1665                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1666                         s16 range_new = range - 10;
1667                         if(range_new < 0)
1668                                 range_new = range;
1669                         g_settings->set("viewing_range_nodes_min",
1670                                         itos(range_new));
1671                         statustext = narrow_to_wide(
1672                                         "Minimum viewing range changed to "
1673                                         + itos(range_new));
1674                         statustext_time = 0;
1675                 }
1676                 
1677                 // Handle QuicktuneShortcutter
1678                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1679                         quicktune.next();
1680                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1681                         quicktune.prev();
1682                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1683                         quicktune.inc();
1684                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1685                         quicktune.dec();
1686                 {
1687                         std::string msg = quicktune.getMessage();
1688                         if(msg != ""){
1689                                 statustext = narrow_to_wide(msg);
1690                                 statustext_time = 0;
1691                         }
1692                 }
1693
1694                 // Item selection with mouse wheel
1695                 u16 new_playeritem = client.getPlayerItem();
1696                 {
1697                         s32 wheel = input->getMouseWheel();
1698                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1699                                         hotbar_itemcount-1);
1700
1701                         if(wheel < 0)
1702                         {
1703                                 if(new_playeritem < max_item)
1704                                         new_playeritem++;
1705                                 else
1706                                         new_playeritem = 0;
1707                         }
1708                         else if(wheel > 0)
1709                         {
1710                                 if(new_playeritem > 0)
1711                                         new_playeritem--;
1712                                 else
1713                                         new_playeritem = max_item;
1714                         }
1715                 }
1716                 
1717                 // Item selection
1718                 for(u16 i=0; i<10; i++)
1719                 {
1720                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1721                         if(input->wasKeyDown(*kp))
1722                         {
1723                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1724                                 {
1725                                         new_playeritem = i;
1726
1727                                         infostream<<"Selected item: "
1728                                                         <<new_playeritem<<std::endl;
1729                                 }
1730                         }
1731                 }
1732
1733                 // Viewing range selection
1734                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1735                 {
1736                         draw_control.range_all = !draw_control.range_all;
1737                         if(draw_control.range_all)
1738                         {
1739                                 infostream<<"Enabled full viewing range"<<std::endl;
1740                                 statustext = L"Enabled full viewing range";
1741                                 statustext_time = 0;
1742                         }
1743                         else
1744                         {
1745                                 infostream<<"Disabled full viewing range"<<std::endl;
1746                                 statustext = L"Disabled full viewing range";
1747                                 statustext_time = 0;
1748                         }
1749                 }
1750
1751                 // Print debug stacks
1752                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1753                 {
1754                         dstream<<"-----------------------------------------"
1755                                         <<std::endl;
1756                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1757                         dstream<<"-----------------------------------------"
1758                                         <<std::endl;
1759                         debug_stacks_print();
1760                 }
1761
1762                 /*
1763                         Mouse and camera control
1764                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1765                 */
1766                 
1767                 float turn_amount = 0;
1768                 if((device->isWindowActive() && noMenuActive()) || random_input)
1769                 {
1770                         if(!random_input)
1771                         {
1772                                 // Mac OSX gets upset if this is set every frame
1773                                 if(device->getCursorControl()->isVisible())
1774                                         device->getCursorControl()->setVisible(false);
1775                         }
1776
1777                         if(first_loop_after_window_activation){
1778                                 //infostream<<"window active, first loop"<<std::endl;
1779                                 first_loop_after_window_activation = false;
1780                         }
1781                         else{
1782                                 s32 dx = input->getMousePos().X - displaycenter.X;
1783                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1784                                 if(invert_mouse)
1785                                         dy = -dy;
1786                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1787                                 
1788                                 /*const float keyspeed = 500;
1789                                 if(input->isKeyDown(irr::KEY_UP))
1790                                         dy -= dtime * keyspeed;
1791                                 if(input->isKeyDown(irr::KEY_DOWN))
1792                                         dy += dtime * keyspeed;
1793                                 if(input->isKeyDown(irr::KEY_LEFT))
1794                                         dx -= dtime * keyspeed;
1795                                 if(input->isKeyDown(irr::KEY_RIGHT))
1796                                         dx += dtime * keyspeed;*/
1797                                 
1798                                 float d = 0.2;
1799                                 camera_yaw -= dx*d;
1800                                 camera_pitch += dy*d;
1801                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1802                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1803                                 
1804                                 turn_amount = v2f(dx, dy).getLength() * d;
1805                         }
1806                         input->setMousePos(displaycenter.X, displaycenter.Y);
1807                 }
1808                 else{
1809                         // Mac OSX gets upset if this is set every frame
1810                         if(device->getCursorControl()->isVisible() == false)
1811                                 device->getCursorControl()->setVisible(true);
1812
1813                         //infostream<<"window inactive"<<std::endl;
1814                         first_loop_after_window_activation = true;
1815                 }
1816                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1817                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1818
1819                 /*
1820                         Player speed control
1821                 */
1822                 {
1823                         /*bool a_up,
1824                         bool a_down,
1825                         bool a_left,
1826                         bool a_right,
1827                         bool a_jump,
1828                         bool a_superspeed,
1829                         bool a_sneak,
1830                         float a_pitch,
1831                         float a_yaw*/
1832                         PlayerControl control(
1833                                 input->isKeyDown(getKeySetting("keymap_forward")),
1834                                 input->isKeyDown(getKeySetting("keymap_backward")),
1835                                 input->isKeyDown(getKeySetting("keymap_left")),
1836                                 input->isKeyDown(getKeySetting("keymap_right")),
1837                                 input->isKeyDown(getKeySetting("keymap_jump")),
1838                                 input->isKeyDown(getKeySetting("keymap_special1")),
1839                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1840                                 camera_pitch,
1841                                 camera_yaw
1842                         );
1843                         client.setPlayerControl(control);
1844                 }
1845                 
1846                 /*
1847                         Run server
1848                 */
1849
1850                 if(server != NULL)
1851                 {
1852                         //TimeTaker timer("server->step(dtime)");
1853                         server->step(dtime);
1854                 }
1855
1856                 /*
1857                         Process environment
1858                 */
1859                 
1860                 {
1861                         //TimeTaker timer("client.step(dtime)");
1862                         client.step(dtime);
1863                         //client.step(dtime_avg1);
1864                 }
1865
1866                 {
1867                         // Read client events
1868                         for(;;)
1869                         {
1870                                 ClientEvent event = client.getClientEvent();
1871                                 if(event.type == CE_NONE)
1872                                 {
1873                                         break;
1874                                 }
1875                                 else if(event.type == CE_PLAYER_DAMAGE)
1876                                 {
1877                                         //u16 damage = event.player_damage.amount;
1878                                         //infostream<<"Player damage: "<<damage<<std::endl;
1879                                         damage_flash_timer = 0.05;
1880                                         if(event.player_damage.amount >= 2){
1881                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1882                                         }
1883                                 }
1884                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1885                                 {
1886                                         camera_yaw = event.player_force_move.yaw;
1887                                         camera_pitch = event.player_force_move.pitch;
1888                                 }
1889                                 else if(event.type == CE_DEATHSCREEN)
1890                                 {
1891                                         if(respawn_menu_active)
1892                                                 continue;
1893
1894                                         /*bool set_camera_point_target =
1895                                                         event.deathscreen.set_camera_point_target;
1896                                         v3f camera_point_target;
1897                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1898                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1899                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1900                                         MainRespawnInitiator *respawner =
1901                                                         new MainRespawnInitiator(
1902                                                                         &respawn_menu_active, &client);
1903                                         GUIDeathScreen *menu =
1904                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1905                                                                 &g_menumgr, respawner);
1906                                         menu->drop();
1907                                         
1908                                         chat_backend.addMessage(L"", L"You died.");
1909
1910                                         /* Handle visualization */
1911
1912                                         damage_flash_timer = 0;
1913
1914                                         /*LocalPlayer* player = client.getLocalPlayer();
1915                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1916                                         camera.update(player, busytime, screensize);*/
1917                                 }
1918                                 else if(event.type == CE_TEXTURES_UPDATED)
1919                                 {
1920                                         update_wielded_item_trigger = true;
1921                                 }
1922                         }
1923                 }
1924                 
1925                 //TimeTaker //timer2("//timer2");
1926
1927                 /*
1928                         For interaction purposes, get info about the held item
1929                         - What item is it?
1930                         - Is it a usable item?
1931                         - Can it point to liquids?
1932                 */
1933                 ItemStack playeritem;
1934                 bool playeritem_usable = false;
1935                 bool playeritem_liquids_pointable = false;
1936                 {
1937                         InventoryList *mlist = local_inventory.getList("main");
1938                         if(mlist != NULL)
1939                         {
1940                                 playeritem = mlist->getItem(client.getPlayerItem());
1941                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1942                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1943                         }
1944                 }
1945                 ToolCapabilities playeritem_toolcap =
1946                                 playeritem.getToolCapabilities(itemdef);
1947                 
1948                 /*
1949                         Update camera
1950                 */
1951
1952                 LocalPlayer* player = client.getEnv().getLocalPlayer();
1953                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1954                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1955                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1956                 camera.update(player, busytime, screensize, tool_reload_ratio);
1957                 camera.step(dtime);
1958
1959                 v3f player_position = player->getPosition();
1960                 v3f camera_position = camera.getPosition();
1961                 v3f camera_direction = camera.getDirection();
1962                 f32 camera_fov = camera.getFovMax();
1963                 
1964                 if(!disable_camera_update){
1965                         client.getEnv().getClientMap().updateCamera(camera_position,
1966                                 camera_direction, camera_fov);
1967                 }
1968                 
1969                 // Update sound listener
1970                 sound->updateListener(camera.getCameraNode()->getPosition(),
1971                                 v3f(0,0,0), // velocity
1972                                 camera.getDirection(),
1973                                 camera.getCameraNode()->getUpVector());
1974                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
1975
1976                 /*
1977                         Update sound maker
1978                 */
1979                 {
1980                         soundmaker.step(dtime);
1981                         
1982                         ClientMap &map = client.getEnv().getClientMap();
1983                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
1984                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
1985                 }
1986
1987                 /*
1988                         Calculate what block is the crosshair pointing to
1989                 */
1990                 
1991                 //u32 t1 = device->getTimer()->getRealTime();
1992                 
1993                 f32 d = 4; // max. distance
1994                 core::line3d<f32> shootline(camera_position,
1995                                 camera_position + camera_direction * BS * (d+1));
1996
1997                 ClientActiveObject *selected_object = NULL;
1998
1999                 PointedThing pointed = getPointedThing(
2000                                 // input
2001                                 &client, player_position, camera_direction,
2002                                 camera_position, shootline, d,
2003                                 playeritem_liquids_pointable, !ldown_for_dig,
2004                                 // output
2005                                 hilightboxes,
2006                                 selected_object);
2007
2008                 if(pointed != pointed_old)
2009                 {
2010                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2011                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2012                 }
2013
2014                 /*
2015                         Stop digging when
2016                         - releasing left mouse button
2017                         - pointing away from node
2018                 */
2019                 if(digging)
2020                 {
2021                         if(input->getLeftReleased())
2022                         {
2023                                 infostream<<"Left button released"
2024                                         <<" (stopped digging)"<<std::endl;
2025                                 digging = false;
2026                         }
2027                         else if(pointed != pointed_old)
2028                         {
2029                                 if (pointed.type == POINTEDTHING_NODE
2030                                         && pointed_old.type == POINTEDTHING_NODE
2031                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2032                                 {
2033                                         // Still pointing to the same node,
2034                                         // but a different face. Don't reset.
2035                                 }
2036                                 else
2037                                 {
2038                                         infostream<<"Pointing away from node"
2039                                                 <<" (stopped digging)"<<std::endl;
2040                                         digging = false;
2041                                 }
2042                         }
2043                         if(!digging)
2044                         {
2045                                 client.interact(1, pointed_old);
2046                                 client.setCrack(-1, v3s16(0,0,0));
2047                                 dig_time = 0.0;
2048                         }
2049                 }
2050                 if(!digging && ldown_for_dig && !input->getLeftState())
2051                 {
2052                         ldown_for_dig = false;
2053                 }
2054
2055                 bool left_punch = false;
2056                 soundmaker.m_player_leftpunch_sound.name = "";
2057
2058                 if(playeritem_usable && input->getLeftState())
2059                 {
2060                         if(input->getLeftClicked())
2061                                 client.interact(4, pointed);
2062                 }
2063                 else if(pointed.type == POINTEDTHING_NODE)
2064                 {
2065                         v3s16 nodepos = pointed.node_undersurface;
2066                         v3s16 neighbourpos = pointed.node_abovesurface;
2067
2068                         /*
2069                                 Check information text of node
2070                         */
2071                         
2072                         ClientMap &map = client.getEnv().getClientMap();
2073                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2074                         if(meta){
2075                                 infotext = narrow_to_wide(meta->getString("infotext"));
2076                         } else {
2077                                 MapNode n = map.getNode(nodepos);
2078                                 if(nodedef->get(n).tiledef[0].name == "unknown_block.png"){
2079                                         infotext = L"Unknown node: ";
2080                                         infotext += narrow_to_wide(nodedef->get(n).name);
2081                                 }
2082                         }
2083                         
2084                         // We can't actually know, but assume the sound of right-clicking
2085                         // to be the sound of placing a node
2086                         soundmaker.m_player_rightpunch_sound.gain = 0.5;
2087                         soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2088                         
2089                         /*
2090                                 Handle digging
2091                         */
2092                         
2093                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
2094                         {
2095                                 if(!digging)
2096                                 {
2097                                         infostream<<"Started digging"<<std::endl;
2098                                         client.interact(0, pointed);
2099                                         digging = true;
2100                                         ldown_for_dig = true;
2101                                 }
2102                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2103
2104                                 // Get digging parameters
2105                                 DigParams params = getDigParams(nodedef->get(n).groups,
2106                                                 &playeritem_toolcap);
2107                                 // If can't dig, try hand
2108                                 if(!params.diggable){
2109                                         const ItemDefinition &hand = itemdef->get("");
2110                                         const ToolCapabilities *tp = hand.tool_capabilities;
2111                                         if(tp)
2112                                                 params = getDigParams(nodedef->get(n).groups, tp);
2113                                 }
2114                                 
2115                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2116                                 if(sound_dig.exists()){
2117                                         if(sound_dig.name == "__group"){
2118                                                 if(params.main_group != ""){
2119                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2120                                                         soundmaker.m_player_leftpunch_sound.name =
2121                                                                         std::string("default_dig_") +
2122                                                                                         params.main_group;
2123                                                 }
2124                                         } else{
2125                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2126                                         }
2127                                 }
2128
2129                                 float dig_time_complete = 0.0;
2130
2131                                 if(params.diggable == false)
2132                                 {
2133                                         // I guess nobody will wait for this long
2134                                         dig_time_complete = 10000000.0;
2135                                 }
2136                                 else
2137                                 {
2138                                         dig_time_complete = params.time;
2139                                 }
2140
2141                                 if(dig_time_complete >= 0.001)
2142                                 {
2143                                         dig_index = (u16)((float)crack_animation_length
2144                                                         * dig_time/dig_time_complete);
2145                                 }
2146                                 // This is for torches
2147                                 else
2148                                 {
2149                                         dig_index = crack_animation_length;
2150                                 }
2151                                 
2152                                 // Don't show cracks if not diggable
2153                                 if(dig_time_complete >= 100000.0)
2154                                 {
2155                                 }
2156                                 else if(dig_index < crack_animation_length)
2157                                 {
2158                                         //TimeTaker timer("client.setTempMod");
2159                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2160                                         client.setCrack(dig_index, nodepos);
2161                                 }
2162                                 else
2163                                 {
2164                                         infostream<<"Digging completed"<<std::endl;
2165                                         client.interact(2, pointed);
2166                                         client.setCrack(-1, v3s16(0,0,0));
2167                                         MapNode wasnode = map.getNode(nodepos);
2168                                         client.removeNode(nodepos);
2169
2170                                         dig_time = 0;
2171                                         digging = false;
2172
2173                                         nodig_delay_timer = dig_time_complete
2174                                                         / (float)crack_animation_length;
2175
2176                                         // We don't want a corresponding delay to
2177                                         // very time consuming nodes
2178                                         if(nodig_delay_timer > 0.3)
2179                                                 nodig_delay_timer = 0.3;
2180                                         // We want a slight delay to very little
2181                                         // time consuming nodes
2182                                         float mindelay = 0.15;
2183                                         if(nodig_delay_timer < mindelay)
2184                                                 nodig_delay_timer = mindelay;
2185                                         
2186                                         // Send event to trigger sound
2187                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2188                                         gamedef->event()->put(e);
2189                                 }
2190
2191                                 dig_time += dtime;
2192
2193                                 camera.setDigging(0);  // left click animation
2194                         }
2195
2196                         if(input->getRightClicked())
2197                         {
2198                                 infostream<<"Ground right-clicked"<<std::endl;
2199                                 
2200                                 // sign special case, at least until formspec is properly implemented
2201                                 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2202                                 {
2203                                         infostream<<"Launching metadata text input"<<std::endl;
2204                                         
2205                                         // Get a new text for it
2206
2207                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2208
2209                                         std::wstring wtext = narrow_to_wide(meta->getString("text"));
2210
2211                                         (new GUITextInputMenu(guienv, guiroot, -1,
2212                                                         &g_menumgr, dest,
2213                                                         wtext))->drop();
2214                                 }
2215                                 // If metadata provides an inventory view, activate it
2216                                 else if(meta && meta->getString("formspec") != "" && !random_input)
2217                                 {
2218                                         infostream<<"Launching custom inventory view"<<std::endl;
2219
2220                                         InventoryLocation inventoryloc;
2221                                         inventoryloc.setNodeMeta(nodepos);
2222                                         
2223                                         /* Create menu */
2224
2225                                         GUIInventoryMenu *menu =
2226                                                 new GUIInventoryMenu(guienv, guiroot, -1,
2227                                                         &g_menumgr,
2228                                                         &client, gamedef);
2229                                         menu->setFormSpec(meta->getString("formspec"),
2230                                                         inventoryloc);
2231                                         menu->setFormSource(new NodeMetadataFormSource(
2232                                                         &client.getEnv().getClientMap(), nodepos));
2233                                         menu->drop();
2234                                 }
2235                                 // Otherwise report right click to server
2236                                 else
2237                                 {
2238                                         // Report to server
2239                                         client.interact(3, pointed);
2240                                         camera.setDigging(1);  // right click animation
2241                                         
2242                                         // If the wielded item has node placement prediction,
2243                                         // make that happen
2244                                         const ItemDefinition &def =
2245                                                         playeritem.getDefinition(itemdef);
2246                                         if(def.node_placement_prediction != "")
2247                                         do{ // breakable
2248                                                 verbosestream<<"Node placement prediction for "
2249                                                                 <<playeritem.name<<" is "
2250                                                                 <<def.node_placement_prediction<<std::endl;
2251                                                 v3s16 p = neighbourpos;
2252                                                 content_t id;
2253                                                 bool found =
2254                                                         nodedef->getId(def.node_placement_prediction, id);
2255                                                 if(!found){
2256                                                         errorstream<<"Node placement prediction failed for "
2257                                                                         <<playeritem.name<<" (places "
2258                                                                         <<def.node_placement_prediction
2259                                                                         <<") - Name not known"<<std::endl;
2260                                                         break;
2261                                                 }
2262                                                 MapNode n(id);
2263                                                 try{
2264                                                         // This triggers the required mesh update too
2265                                                         client.addNode(p, n);
2266                                                 }catch(InvalidPositionException &e){
2267                                                         errorstream<<"Node placement prediction failed for "
2268                                                                         <<playeritem.name<<" (places "
2269                                                                         <<def.node_placement_prediction
2270                                                                         <<") - Position not loaded"<<std::endl;
2271                                                 }
2272                                         }while(0);
2273                                 }
2274                         }
2275                 }
2276                 else if(pointed.type == POINTEDTHING_OBJECT)
2277                 {
2278                         infotext = narrow_to_wide(selected_object->infoText());
2279
2280                         if(infotext == L"" && show_debug){
2281                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2282                         }
2283
2284                         //if(input->getLeftClicked())
2285                         if(input->getLeftState())
2286                         {
2287                                 bool do_punch = false;
2288                                 bool do_punch_damage = false;
2289                                 if(object_hit_delay_timer <= 0.0){
2290                                         do_punch = true;
2291                                         do_punch_damage = true;
2292                                         object_hit_delay_timer = object_hit_delay;
2293                                 }
2294                                 if(input->getLeftClicked()){
2295                                         do_punch = true;
2296                                 }
2297                                 if(do_punch){
2298                                         infostream<<"Left-clicked object"<<std::endl;
2299                                         left_punch = true;
2300                                 }
2301                                 if(do_punch_damage){
2302                                         // Report direct punch
2303                                         v3f objpos = selected_object->getPosition();
2304                                         v3f dir = (objpos - player_position).normalize();
2305                                         
2306                                         bool disable_send = selected_object->directReportPunch(
2307                                                         dir, &playeritem, time_from_last_punch);
2308                                         time_from_last_punch = 0;
2309                                         if(!disable_send)
2310                                                 client.interact(0, pointed);
2311                                 }
2312                         }
2313                         else if(input->getRightClicked())
2314                         {
2315                                 infostream<<"Right-clicked object"<<std::endl;
2316                                 client.interact(3, pointed);  // place
2317                         }
2318                 }
2319                 else if(input->getLeftState())
2320                 {
2321                         // When button is held down in air, show continuous animation
2322                         left_punch = true;
2323                 }
2324
2325                 pointed_old = pointed;
2326                 
2327                 if(left_punch || input->getLeftClicked())
2328                 {
2329                         camera.setDigging(0); // left click animation
2330                 }
2331
2332                 input->resetLeftClicked();
2333                 input->resetRightClicked();
2334
2335                 input->resetLeftReleased();
2336                 input->resetRightReleased();
2337                 
2338                 /*
2339                         Calculate stuff for drawing
2340                 */
2341
2342                 /*
2343                         Fog range
2344                 */
2345         
2346                 f32 fog_range;
2347                 if(farmesh)
2348                 {
2349                         fog_range = BS*farmesh_range;
2350                 }
2351                 else
2352                 {
2353                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2354                         fog_range *= 0.9;
2355                         if(draw_control.range_all)
2356                                 fog_range = 100000*BS;
2357                 }
2358
2359                 /*
2360                         Calculate general brightness
2361                 */
2362                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2363                 float time_brightness = (float)decode_light(
2364                                 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2365                 float direct_brightness = 0;
2366                 bool sunlight_seen = false;
2367                 if(g_settings->getBool("free_move")){
2368                         direct_brightness = time_brightness;
2369                         sunlight_seen = true;
2370                 } else {
2371                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2372                         float old_brightness = sky->getBrightness();
2373                         direct_brightness = (float)client.getEnv().getClientMap()
2374                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2375                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2376                                         / 255.0;
2377                 }
2378                 
2379                 time_of_day = client.getEnv().getTimeOfDayF();
2380                 float maxsm = 0.05;
2381                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2382                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2383                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2384                         time_of_day_smooth = time_of_day;
2385                 float todsm = 0.05;
2386                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2387                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2388                                         + (time_of_day+1.0) * todsm;
2389                 else
2390                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2391                                         + time_of_day * todsm;
2392                         
2393                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2394                                 sunlight_seen);
2395                 
2396                 float brightness = sky->getBrightness();
2397                 video::SColor bgcolor = sky->getBgColor();
2398                 video::SColor skycolor = sky->getSkyColor();
2399
2400                 /*
2401                         Update clouds
2402                 */
2403                 if(clouds){
2404                         if(sky->getCloudsVisible()){
2405                                 clouds->setVisible(true);
2406                                 clouds->step(dtime);
2407                                 clouds->update(v2f(player_position.X, player_position.Z),
2408                                                 sky->getCloudColor());
2409                         } else{
2410                                 clouds->setVisible(false);
2411                         }
2412                 }
2413                 
2414                 /*
2415                         Update farmesh
2416                 */
2417                 if(farmesh)
2418                 {
2419                         farmesh_range = draw_control.wanted_range * 10;
2420                         if(draw_control.range_all && farmesh_range < 500)
2421                                 farmesh_range = 500;
2422                         if(farmesh_range > 1000)
2423                                 farmesh_range = 1000;
2424
2425                         farmesh->step(dtime);
2426                         farmesh->update(v2f(player_position.X, player_position.Z),
2427                                         brightness, farmesh_range);
2428                 }
2429                 
2430                 /*
2431                         Fog
2432                 */
2433                 
2434                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2435                 {
2436                         driver->setFog(
2437                                 bgcolor,
2438                                 video::EFT_FOG_LINEAR,
2439                                 fog_range*0.4,
2440                                 fog_range*1.0,
2441                                 0.01,
2442                                 false, // pixel fog
2443                                 false // range fog
2444                         );
2445                 }
2446                 else
2447                 {
2448                         driver->setFog(
2449                                 bgcolor,
2450                                 video::EFT_FOG_LINEAR,
2451                                 100000*BS,
2452                                 110000*BS,
2453                                 0.01,
2454                                 false, // pixel fog
2455                                 false // range fog
2456                         );
2457                 }
2458
2459                 /*
2460                         Update gui stuff (0ms)
2461                 */
2462
2463                 //TimeTaker guiupdatetimer("Gui updating");
2464                 
2465                 const char program_name_and_version[] =
2466                         "Minetest-c55 " VERSION_STRING;
2467
2468                 if(show_debug)
2469                 {
2470                         static float drawtime_avg = 0;
2471                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2472                         /*static float beginscenetime_avg = 0;
2473                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2474                         static float scenetime_avg = 0;
2475                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2476                         static float endscenetime_avg = 0;
2477                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2478                         
2479                         char temptext[300];
2480                         snprintf(temptext, 300, "%s ("
2481                                         "R: range_all=%i"
2482                                         ")"
2483                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2484                                         ", v_range = %.1f, RTT = %.3f",
2485                                         program_name_and_version,
2486                                         draw_control.range_all,
2487                                         drawtime_avg,
2488                                         dtime_jitter1_max_fraction * 100.0,
2489                                         draw_control.wanted_range,
2490                                         client.getRTT()
2491                                         );
2492                         
2493                         guitext->setText(narrow_to_wide(temptext).c_str());
2494                         guitext->setVisible(true);
2495                 }
2496                 else if(show_hud || show_chat)
2497                 {
2498                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2499                         guitext->setVisible(true);
2500                 }
2501                 else
2502                 {
2503                         guitext->setVisible(false);
2504                 }
2505                 
2506                 if(show_debug)
2507                 {
2508                         char temptext[300];
2509                         snprintf(temptext, 300,
2510                                         "(% .1f, % .1f, % .1f)"
2511                                         " (yaw = %.1f) (seed = %lli)",
2512                                         player_position.X/BS,
2513                                         player_position.Y/BS,
2514                                         player_position.Z/BS,
2515                                         wrapDegrees_0_360(camera_yaw),
2516                                         client.getMapSeed());
2517
2518                         guitext2->setText(narrow_to_wide(temptext).c_str());
2519                         guitext2->setVisible(true);
2520                 }
2521                 else
2522                 {
2523                         guitext2->setVisible(false);
2524                 }
2525                 
2526                 {
2527                         guitext_info->setText(infotext.c_str());
2528                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2529                 }
2530
2531                 {
2532                         float statustext_time_max = 1.5;
2533                         if(!statustext.empty())
2534                         {
2535                                 statustext_time += dtime;
2536                                 if(statustext_time >= statustext_time_max)
2537                                 {
2538                                         statustext = L"";
2539                                         statustext_time = 0;
2540                                 }
2541                         }
2542                         guitext_status->setText(statustext.c_str());
2543                         guitext_status->setVisible(!statustext.empty());
2544
2545                         if(!statustext.empty())
2546                         {
2547                                 s32 status_y = screensize.Y - 130;
2548                                 core::rect<s32> rect(
2549                                                 10,
2550                                                 status_y - guitext_status->getTextHeight(),
2551                                                 screensize.X - 10,
2552                                                 status_y
2553                                 );
2554                                 guitext_status->setRelativePosition(rect);
2555
2556                                 // Fade out
2557                                 video::SColor initial_color(255,0,0,0);
2558                                 if(guienv->getSkin())
2559                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2560                                 video::SColor final_color = initial_color;
2561                                 final_color.setAlpha(0);
2562                                 video::SColor fade_color =
2563                                         initial_color.getInterpolated_quadratic(
2564                                                 initial_color,
2565                                                 final_color,
2566                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
2567                                 guitext_status->setOverrideColor(fade_color);
2568                                 guitext_status->enableOverrideColor(true);
2569                         }
2570                 }
2571                 
2572                 /*
2573                         Get chat messages from client
2574                 */
2575                 {
2576                         // Get new messages from error log buffer
2577                         while(!chat_log_error_buf.empty())
2578                         {
2579                                 chat_backend.addMessage(L"", narrow_to_wide(
2580                                                 chat_log_error_buf.get()));
2581                         }
2582                         // Get new messages from client
2583                         std::wstring message;
2584                         while(client.getChatMessage(message))
2585                         {
2586                                 chat_backend.addUnparsedMessage(message);
2587                         }
2588                         // Remove old messages
2589                         chat_backend.step(dtime);
2590
2591                         // Display all messages in a static text element
2592                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2593                         std::wstring recent_chat = chat_backend.getRecentChat();
2594                         guitext_chat->setText(recent_chat.c_str());
2595
2596                         // Update gui element size and position
2597                         s32 chat_y = 5+(text_height+5);
2598                         if(show_debug)
2599                                 chat_y += (text_height+5);
2600                         core::rect<s32> rect(
2601                                 10,
2602                                 chat_y,
2603                                 screensize.X - 10,
2604                                 chat_y + guitext_chat->getTextHeight()
2605                         );
2606                         guitext_chat->setRelativePosition(rect);
2607
2608                         // Don't show chat if disabled or empty or profiler is enabled
2609                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
2610                                         && !show_profiler);
2611                 }
2612
2613                 /*
2614                         Inventory
2615                 */
2616                 
2617                 if(client.getPlayerItem() != new_playeritem)
2618                 {
2619                         client.selectPlayerItem(new_playeritem);
2620                 }
2621                 if(client.getLocalInventoryUpdated())
2622                 {
2623                         //infostream<<"Updating local inventory"<<std::endl;
2624                         client.getLocalInventory(local_inventory);
2625                         
2626                         update_wielded_item_trigger = true;
2627                 }
2628                 if(update_wielded_item_trigger)
2629                 {
2630                         update_wielded_item_trigger = false;
2631                         // Update wielded tool
2632                         InventoryList *mlist = local_inventory.getList("main");
2633                         ItemStack item;
2634                         if(mlist != NULL)
2635                                 item = mlist->getItem(client.getPlayerItem());
2636                         camera.wield(item);
2637                 }
2638                 
2639                 /*
2640                         Drawing begins
2641                 */
2642
2643                 TimeTaker tt_draw("mainloop: draw");
2644
2645                 
2646                 {
2647                         TimeTaker timer("beginScene");
2648                         //driver->beginScene(false, true, bgcolor);
2649                         //driver->beginScene(true, true, bgcolor);
2650                         driver->beginScene(true, true, skycolor);
2651                         beginscenetime = timer.stop(true);
2652                 }
2653                 
2654                 //timer3.stop();
2655         
2656                 //infostream<<"smgr->drawAll()"<<std::endl;
2657                 {
2658                         TimeTaker timer("smgr");
2659                         smgr->drawAll();
2660                         scenetime = timer.stop(true);
2661                 }
2662                 
2663                 {
2664                 //TimeTaker timer9("auxiliary drawings");
2665                 // 0ms
2666                 
2667                 //timer9.stop();
2668                 //TimeTaker //timer10("//timer10");
2669                 
2670                 video::SMaterial m;
2671                 //m.Thickness = 10;
2672                 m.Thickness = 3;
2673                 m.Lighting = false;
2674                 driver->setMaterial(m);
2675
2676                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2677
2678                 if(show_hud)
2679                 {
2680                         for(std::vector<aabb3f>::const_iterator
2681                                         i = hilightboxes.begin();
2682                                         i != hilightboxes.end(); i++)
2683                         {
2684                                 /*infostream<<"hilightbox min="
2685                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2686                                                 <<" max="
2687                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2688                                                 <<std::endl;*/
2689                                 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2690                         }
2691                 }
2692
2693                 /*
2694                         Wielded tool
2695                 */
2696                 if(show_hud)
2697                 {
2698                         // Warning: This clears the Z buffer.
2699                         camera.drawWieldedTool();
2700                 }
2701
2702                 /*
2703                         Post effects
2704                 */
2705                 {
2706                         client.getEnv().getClientMap().renderPostFx();
2707                 }
2708
2709                 /*
2710                         Profiler graph
2711                 */
2712                 if(show_profiler_graph)
2713                 {
2714                         graph.draw(10, screensize.Y - 10, driver, font);
2715                 }
2716
2717                 /*
2718                         Draw crosshair
2719                 */
2720                 if(show_hud)
2721                 {
2722                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2723                                         displaycenter + core::vector2d<s32>(10,0),
2724                                         video::SColor(255,255,255,255));
2725                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2726                                         displaycenter + core::vector2d<s32>(0,10),
2727                                         video::SColor(255,255,255,255));
2728                 }
2729
2730                 } // timer
2731
2732                 //timer10.stop();
2733                 //TimeTaker //timer11("//timer11");
2734
2735                 /*
2736                         Draw gui
2737                 */
2738                 // 0-1ms
2739                 guienv->drawAll();
2740
2741                 /*
2742                         Draw hotbar
2743                 */
2744                 if(show_hud)
2745                 {
2746                         draw_hotbar(driver, font, gamedef,
2747                                         v2s32(displaycenter.X, screensize.Y),
2748                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2749                                         client.getHP(), client.getPlayerItem());
2750                 }
2751
2752                 /*
2753                         Damage flash
2754                 */
2755                 if(damage_flash_timer > 0.0)
2756                 {
2757                         damage_flash_timer -= dtime;
2758                         
2759                         video::SColor color(128,255,0,0);
2760                         driver->draw2DRectangle(color,
2761                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2762                                         NULL);
2763                 }
2764
2765                 /*
2766                         End scene
2767                 */
2768                 {
2769                         TimeTaker timer("endScene");
2770                         endSceneX(driver);
2771                         endscenetime = timer.stop(true);
2772                 }
2773
2774                 drawtime = tt_draw.stop(true);
2775                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2776
2777                 /*
2778                         End of drawing
2779                 */
2780
2781                 static s16 lastFPS = 0;
2782                 //u16 fps = driver->getFPS();
2783                 u16 fps = (1.0/dtime_avg1);
2784
2785                 if (lastFPS != fps)
2786                 {
2787                         core::stringw str = L"Minetest [";
2788                         str += driver->getName();
2789                         str += "] FPS=";
2790                         str += fps;
2791
2792                         device->setWindowCaption(str.c_str());
2793                         lastFPS = fps;
2794                 }
2795
2796                 /*
2797                         Log times and stuff for visualization
2798                 */
2799                 Profiler::GraphValues values;
2800                 g_profiler->graphGet(values);
2801                 graph.put(values);
2802         }
2803
2804         /*
2805                 Drop stuff
2806         */
2807         if(clouds)
2808                 clouds->drop();
2809         if(gui_chat_console)
2810                 gui_chat_console->drop();
2811         
2812         /*
2813                 Draw a "shutting down" screen, which will be shown while the map
2814                 generator and other stuff quits
2815         */
2816         {
2817                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2818                 draw_load_screen(L"Shutting down stuff...", driver, font);
2819                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2820                 guienv->drawAll();
2821                 driver->endScene();
2822                 gui_shuttingdowntext->remove();*/
2823         }
2824
2825         chat_backend.addMessage(L"", L"# Disconnected.");
2826         chat_backend.addMessage(L"", L"");
2827
2828         // Client scope (client is destructed before destructing *def and tsrc)
2829         }while(0);
2830         } // try-catch
2831         catch(SerializationError &e)
2832         {
2833                 error_message = L"A serialization error occurred:\n"
2834                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
2835                                 L" running a different version of Minetest.";
2836                 errorstream<<wide_to_narrow(error_message)<<std::endl;
2837         }
2838         
2839         if(!sound_is_dummy)
2840                 delete sound;
2841         delete nodedef;
2842         delete itemdef;
2843         delete tsrc;
2844 }
2845
2846