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