3cad4c89543030903777cfa31ada872a145a0d64
[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         float m_player_step_timer;
789
790         SimpleSoundSpec m_player_step_sound;
791         SimpleSoundSpec m_player_leftpunch_sound;
792         SimpleSoundSpec m_player_rightpunch_sound;
793
794         SoundMaker(ISoundManager *sound):
795                 m_sound(sound),
796                 m_player_step_timer(0)
797         {
798         }
799
800         void playPlayerStep()
801         {
802                 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
803                         m_player_step_timer = 0.03;
804                         m_sound->playSound(m_player_step_sound, false);
805                 }
806         }
807
808         void playPlayerLeftPunch()
809         {
810                 if(m_player_leftpunch_sound.exists()){
811                         m_sound->playSound(m_player_leftpunch_sound, false);
812                 }
813         }
814
815         void playPlayerRightPunch()
816         {
817                 if(m_player_rightpunch_sound.exists()){
818                         m_sound->playSound(m_player_rightpunch_sound, false);
819                 }
820         }
821
822         static void viewBobbingStep(MtEvent *e, void *data)
823         {
824                 SoundMaker *sm = (SoundMaker*)data;
825                 sm->playPlayerStep();
826         }
827
828         static void playerRegainGround(MtEvent *e, void *data)
829         {
830                 SoundMaker *sm = (SoundMaker*)data;
831                 sm->playPlayerStep();
832         }
833
834         static void playerJump(MtEvent *e, void *data)
835         {
836                 //SoundMaker *sm = (SoundMaker*)data;
837         }
838
839         static void cameraPunchLeft(MtEvent *e, void *data)
840         {
841                 SoundMaker *sm = (SoundMaker*)data;
842                 sm->playPlayerLeftPunch();
843         }
844
845         static void cameraPunchRight(MtEvent *e, void *data)
846         {
847                 SoundMaker *sm = (SoundMaker*)data;
848                 sm->playPlayerRightPunch();
849         }
850
851         void registerReceiver(MtEventManager *mgr)
852         {
853                 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
854                 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
855                 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
856                 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
857                 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
858         }
859
860         void step(float dtime)
861         {
862                 m_player_step_timer -= dtime;
863         }
864 };
865
866 void the_game(
867         bool &kill,
868         bool random_input,
869         InputHandler *input,
870         IrrlichtDevice *device,
871         gui::IGUIFont* font,
872         std::string map_dir,
873         std::string playername,
874         std::string password,
875         std::string address, // If "", local server is used
876         u16 port,
877         std::wstring &error_message,
878         std::string configpath,
879         ChatBackend &chat_backend,
880         const SubgameSpec &gamespec, // Used for local game,
881         bool simple_singleplayer_mode
882 )
883 {
884         video::IVideoDriver* driver = device->getVideoDriver();
885         scene::ISceneManager* smgr = device->getSceneManager();
886         
887         // Calculate text height using the font
888         u32 text_height = font->getDimension(L"Random test string").Height;
889
890         v2u32 screensize(0,0);
891         v2u32 last_screensize(0,0);
892         screensize = driver->getScreenSize();
893
894         const s32 hotbar_itemcount = 8;
895         //const s32 hotbar_imagesize = 36;
896         //const s32 hotbar_imagesize = 64;
897         s32 hotbar_imagesize = 48;
898         
899         /*
900                 Draw "Loading" screen
901         */
902
903         draw_load_screen(L"Loading...", driver, font);
904         
905         // Create texture source
906         IWritableTextureSource *tsrc = createTextureSource(device);
907         
908         // These will be filled by data received from the server
909         // Create item definition manager
910         IWritableItemDefManager *itemdef = createItemDefManager();
911         // Create node definition manager
912         IWritableNodeDefManager *nodedef = createNodeDefManager();
913         
914         // Sound manager
915         ISoundManager *sound = NULL;
916         bool sound_is_dummy = false;
917 #if USE_AUDIO
918         infostream<<"Attempting to use OpenAL audio"<<std::endl;
919         sound = createOpenALSoundManager(NULL);
920         if(!sound)
921                 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
922 #endif
923         if(!sound){
924                 infostream<<"Using dummy audio."<<std::endl;
925                 sound = &dummySoundManager;
926                 sound_is_dummy = true;
927         }
928
929         // Event manager
930         EventManager eventmgr;
931
932         // Sound maker
933         SoundMaker soundmaker(sound);
934         soundmaker.registerReceiver(&eventmgr);
935         
936         // Test sounds
937         sound->loadSound("default_grass_footstep", porting::path_share + DIR_DELIM
938                         + "sounds" + DIR_DELIM + "default_grass_walk1.ogg");
939         sound->loadSound("default_grass_footstep", porting::path_share + DIR_DELIM
940                         + "sounds" + DIR_DELIM + "default_grass_walk2.ogg");
941         sound->loadSound("default_grass_footstep", porting::path_share + DIR_DELIM
942                         + "sounds" + DIR_DELIM + "default_grass_walk3.ogg");
943         
944         sound->loadSound("default_dig_crumbly", porting::path_share + DIR_DELIM
945                         + "sounds" + DIR_DELIM + "default_dig_crumbly1.ogg");
946         sound->loadSound("default_dig_crumbly", porting::path_share + DIR_DELIM
947                         + "sounds" + DIR_DELIM + "default_dig_crumbly2.ogg");
948         
949         sound->loadSound("default_dig_cracky", porting::path_share + DIR_DELIM
950                         + "sounds" + DIR_DELIM + "default_dig_cracky1.ogg");
951         
952         sound->loadSound("default_place_node", porting::path_share + DIR_DELIM
953                         + "sounds" + DIR_DELIM + "default_place_node1.ogg");
954         sound->loadSound("default_place_node", porting::path_share + DIR_DELIM
955                         + "sounds" + DIR_DELIM + "default_place_node2.ogg");
956         sound->loadSound("default_place_node", porting::path_share + DIR_DELIM
957                         + "sounds" + DIR_DELIM + "default_place_node3.ogg");
958
959         // Add chat log output for errors to be shown in chat
960         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
961
962         // Create UI for modifying quicktune values
963         QuicktuneShortcutter quicktune;
964
965         /*
966                 Create server.
967                 SharedPtr will delete it when it goes out of scope.
968         */
969         SharedPtr<Server> server;
970         if(address == ""){
971                 draw_load_screen(L"Creating server...", driver, font);
972                 infostream<<"Creating server"<<std::endl;
973                 server = new Server(map_dir, configpath, gamespec,
974                                 simple_singleplayer_mode);
975                 server->start(port);
976         }
977
978         do{ // Client scope (breakable do-while(0))
979         
980         /*
981                 Create client
982         */
983
984         draw_load_screen(L"Creating client...", driver, font);
985         infostream<<"Creating client"<<std::endl;
986         
987         MapDrawControl draw_control;
988
989         Client client(device, playername.c_str(), password, draw_control,
990                         tsrc, itemdef, nodedef, sound, &eventmgr);
991         
992         // Client acts as our GameDef
993         IGameDef *gamedef = &client;
994                         
995         draw_load_screen(L"Resolving address...", driver, font);
996         Address connect_address(0,0,0,0, port);
997         try{
998                 if(address == "")
999                         //connect_address.Resolve("localhost");
1000                         connect_address.setAddress(127,0,0,1);
1001                 else
1002                         connect_address.Resolve(address.c_str());
1003         }
1004         catch(ResolveError &e)
1005         {
1006                 error_message = L"Couldn't resolve address";
1007                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1008                 // Break out of client scope
1009                 break;
1010         }
1011
1012         /*
1013                 Attempt to connect to the server
1014         */
1015         
1016         infostream<<"Connecting to server at ";
1017         connect_address.print(&infostream);
1018         infostream<<std::endl;
1019         client.connect(connect_address);
1020         
1021         /*
1022                 Wait for server to accept connection
1023         */
1024         bool could_connect = false;
1025         bool connect_aborted = false;
1026         try{
1027                 float frametime = 0.033;
1028                 float time_counter = 0.0;
1029                 input->clear();
1030                 while(device->run())
1031                 {
1032                         // Update client and server
1033                         client.step(frametime);
1034                         if(server != NULL)
1035                                 server->step(frametime);
1036                         
1037                         // End condition
1038                         if(client.connectedAndInitialized()){
1039                                 could_connect = true;
1040                                 break;
1041                         }
1042                         // Break conditions
1043                         if(client.accessDenied()){
1044                                 error_message = L"Access denied. Reason: "
1045                                                 +client.accessDeniedReason();
1046                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1047                                 break;
1048                         }
1049                         if(input->wasKeyDown(EscapeKey)){
1050                                 connect_aborted = true;
1051                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1052                                 break;
1053                         }
1054                         
1055                         // Display status
1056                         std::wostringstream ss;
1057                         ss<<L"Connecting to server... (press Escape to cancel)\n";
1058                         std::wstring animation = L"/-\\|";
1059                         ss<<animation[(int)(time_counter/0.2)%4];
1060                         draw_load_screen(ss.str(), driver, font);
1061                         
1062                         // Delay a bit
1063                         sleep_ms(1000*frametime);
1064                         time_counter += frametime;
1065                 }
1066         }
1067         catch(con::PeerNotFoundException &e)
1068         {}
1069         
1070         /*
1071                 Handle failure to connect
1072         */
1073         if(!could_connect){
1074                 if(error_message == L"" && !connect_aborted){
1075                         error_message = L"Connection failed";
1076                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1077                 }
1078                 // Break out of client scope
1079                 break;
1080         }
1081         
1082         /*
1083                 Wait until content has been received
1084         */
1085         bool got_content = false;
1086         bool content_aborted = false;
1087         {
1088                 float frametime = 0.033;
1089                 float time_counter = 0.0;
1090                 input->clear();
1091                 while(device->run())
1092                 {
1093                         // Update client and server
1094                         client.step(frametime);
1095                         if(server != NULL)
1096                                 server->step(frametime);
1097                         
1098                         // End condition
1099                         if(client.texturesReceived() &&
1100                                         client.itemdefReceived() &&
1101                                         client.nodedefReceived()){
1102                                 got_content = true;
1103                                 break;
1104                         }
1105                         // Break conditions
1106                         if(!client.connectedAndInitialized()){
1107                                 error_message = L"Client disconnected";
1108                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1109                                 break;
1110                         }
1111                         if(input->wasKeyDown(EscapeKey)){
1112                                 content_aborted = true;
1113                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1114                                 break;
1115                         }
1116                         
1117                         // Display status
1118                         std::wostringstream ss;
1119                         ss<<L"Waiting content... (press Escape to cancel)\n";
1120
1121                         ss<<(client.itemdefReceived()?L"[X]":L"[  ]");
1122                         ss<<L" Item definitions\n";
1123                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
1124                         ss<<L" Node definitions\n";
1125                         //ss<<(client.texturesReceived()?L"[X]":L"[  ]");
1126                         ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
1127                         ss<<L" Textures\n";
1128
1129                         draw_load_screen(ss.str(), driver, font);
1130                         
1131                         // Delay a bit
1132                         sleep_ms(1000*frametime);
1133                         time_counter += frametime;
1134                 }
1135         }
1136
1137         if(!got_content){
1138                 if(error_message == L"" && !content_aborted){
1139                         error_message = L"Something failed";
1140                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1141                 }
1142                 // Break out of client scope
1143                 break;
1144         }
1145
1146         /*
1147                 After all content has been received:
1148                 Update cached textures, meshes and materials
1149         */
1150         client.afterContentReceived();
1151
1152         /*
1153                 Create the camera node
1154         */
1155         Camera camera(smgr, draw_control, gamedef);
1156         if (!camera.successfullyCreated(error_message))
1157                 return;
1158
1159         f32 camera_yaw = 0; // "right/left"
1160         f32 camera_pitch = 0; // "up/down"
1161
1162         /*
1163                 Clouds
1164         */
1165         
1166         Clouds *clouds = NULL;
1167         if(g_settings->getBool("enable_clouds"))
1168         {
1169                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1170         }
1171
1172         /*
1173                 Skybox thingy
1174         */
1175
1176         Sky *sky = NULL;
1177         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1178         
1179         /*
1180                 FarMesh
1181         */
1182
1183         FarMesh *farmesh = NULL;
1184         if(g_settings->getBool("enable_farmesh"))
1185         {
1186                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1187         }
1188
1189         /*
1190                 A copy of the local inventory
1191         */
1192         Inventory local_inventory(itemdef);
1193
1194         /*
1195                 Add some gui stuff
1196         */
1197
1198         // First line of debug text
1199         gui::IGUIStaticText *guitext = guienv->addStaticText(
1200                         L"Minetest-c55",
1201                         core::rect<s32>(5, 5, 795, 5+text_height),
1202                         false, false);
1203         // Second line of debug text
1204         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1205                         L"",
1206                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1207                         false, false);
1208         // At the middle of the screen
1209         // Object infos are shown in this
1210         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1211                         L"",
1212                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1213                         false, false);
1214         
1215         // Status text (displays info when showing and hiding GUI stuff, etc.)
1216         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1217                         L"<Status>",
1218                         core::rect<s32>(0,0,0,0),
1219                         false, false);
1220         guitext_status->setVisible(false);
1221         
1222         std::wstring statustext;
1223         float statustext_time = 0;
1224         
1225         // Chat text
1226         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1227                         L"",
1228                         core::rect<s32>(0,0,0,0),
1229                         //false, false); // Disable word wrap as of now
1230                         false, true);
1231         // Remove stale "recent" chat messages from previous connections
1232         chat_backend.clearRecentChat();
1233         // Chat backend and console
1234         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1235         
1236         // Profiler text (size is updated when text is updated)
1237         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1238                         L"<Profiler>",
1239                         core::rect<s32>(0,0,0,0),
1240                         false, false);
1241         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1242         guitext_profiler->setVisible(false);
1243         
1244         /*
1245                 Some statistics are collected in these
1246         */
1247         u32 drawtime = 0;
1248         u32 beginscenetime = 0;
1249         u32 scenetime = 0;
1250         u32 endscenetime = 0;
1251         
1252         float recent_turn_speed = 0.0;
1253         
1254         ProfilerGraph graph;
1255         // Initially clear the profiler
1256         Profiler::GraphValues dummyvalues;
1257         g_profiler->graphGet(dummyvalues);
1258
1259         float nodig_delay_timer = 0.0;
1260         float dig_time = 0.0;
1261         u16 dig_index = 0;
1262         PointedThing pointed_old;
1263         bool digging = false;
1264         bool ldown_for_dig = false;
1265
1266         float damage_flash_timer = 0;
1267         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1268
1269         const float object_hit_delay = 0.2;
1270         float object_hit_delay_timer = 0.0;
1271         float time_from_last_punch = 10;
1272
1273         bool invert_mouse = g_settings->getBool("invert_mouse");
1274
1275         bool respawn_menu_active = false;
1276         bool update_wielded_item_trigger = false;
1277
1278         bool show_hud = true;
1279         bool show_chat = true;
1280         bool force_fog_off = false;
1281         bool disable_camera_update = false;
1282         bool show_debug = g_settings->getBool("show_debug");
1283         bool show_profiler_graph = false;
1284         u32 show_profiler = 0;
1285         u32 show_profiler_max = 3;  // Number of pages
1286
1287         float time_of_day = 0;
1288         float time_of_day_smooth = 0;
1289
1290         /*
1291                 Main loop
1292         */
1293
1294         bool first_loop_after_window_activation = true;
1295
1296         // TODO: Convert the static interval timers to these
1297         // Interval limiter for profiler
1298         IntervalLimiter m_profiler_interval;
1299
1300         // Time is in milliseconds
1301         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1302         // NOTE: So we have to use getTime() and call run()s between them
1303         u32 lasttime = device->getTimer()->getTime();
1304
1305         for(;;)
1306         {
1307                 if(device->run() == false || kill == true)
1308                         break;
1309
1310                 // Time of frame without fps limit
1311                 float busytime;
1312                 u32 busytime_u32;
1313                 {
1314                         // not using getRealTime is necessary for wine
1315                         u32 time = device->getTimer()->getTime();
1316                         if(time > lasttime)
1317                                 busytime_u32 = time - lasttime;
1318                         else
1319                                 busytime_u32 = 0;
1320                         busytime = busytime_u32 / 1000.0;
1321                 }
1322                 
1323                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1324
1325                 // Necessary for device->getTimer()->getTime()
1326                 device->run();
1327
1328                 /*
1329                         FPS limiter
1330                 */
1331
1332                 {
1333                         float fps_max = g_settings->getFloat("fps_max");
1334                         u32 frametime_min = 1000./fps_max;
1335                         
1336                         if(busytime_u32 < frametime_min)
1337                         {
1338                                 u32 sleeptime = frametime_min - busytime_u32;
1339                                 device->sleep(sleeptime);
1340                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1341                         }
1342                 }
1343
1344                 // Necessary for device->getTimer()->getTime()
1345                 device->run();
1346
1347                 /*
1348                         Time difference calculation
1349                 */
1350                 f32 dtime; // in seconds
1351                 
1352                 u32 time = device->getTimer()->getTime();
1353                 if(time > lasttime)
1354                         dtime = (time - lasttime) / 1000.0;
1355                 else
1356                         dtime = 0;
1357                 lasttime = time;
1358
1359                 g_profiler->graphAdd("mainloop_dtime", dtime);
1360
1361                 /* Run timers */
1362
1363                 if(nodig_delay_timer >= 0)
1364                         nodig_delay_timer -= dtime;
1365                 if(object_hit_delay_timer >= 0)
1366                         object_hit_delay_timer -= dtime;
1367                 time_from_last_punch += dtime;
1368                 
1369                 g_profiler->add("Elapsed time", dtime);
1370                 g_profiler->avg("FPS", 1./dtime);
1371
1372                 /*
1373                         Time average and jitter calculation
1374                 */
1375
1376                 static f32 dtime_avg1 = 0.0;
1377                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1378                 f32 dtime_jitter1 = dtime - dtime_avg1;
1379
1380                 static f32 dtime_jitter1_max_sample = 0.0;
1381                 static f32 dtime_jitter1_max_fraction = 0.0;
1382                 {
1383                         static f32 jitter1_max = 0.0;
1384                         static f32 counter = 0.0;
1385                         if(dtime_jitter1 > jitter1_max)
1386                                 jitter1_max = dtime_jitter1;
1387                         counter += dtime;
1388                         if(counter > 0.0)
1389                         {
1390                                 counter -= 3.0;
1391                                 dtime_jitter1_max_sample = jitter1_max;
1392                                 dtime_jitter1_max_fraction
1393                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1394                                 jitter1_max = 0.0;
1395                         }
1396                 }
1397                 
1398                 /*
1399                         Busytime average and jitter calculation
1400                 */
1401
1402                 static f32 busytime_avg1 = 0.0;
1403                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1404                 f32 busytime_jitter1 = busytime - busytime_avg1;
1405                 
1406                 static f32 busytime_jitter1_max_sample = 0.0;
1407                 static f32 busytime_jitter1_min_sample = 0.0;
1408                 {
1409                         static f32 jitter1_max = 0.0;
1410                         static f32 jitter1_min = 0.0;
1411                         static f32 counter = 0.0;
1412                         if(busytime_jitter1 > jitter1_max)
1413                                 jitter1_max = busytime_jitter1;
1414                         if(busytime_jitter1 < jitter1_min)
1415                                 jitter1_min = busytime_jitter1;
1416                         counter += dtime;
1417                         if(counter > 0.0){
1418                                 counter -= 3.0;
1419                                 busytime_jitter1_max_sample = jitter1_max;
1420                                 busytime_jitter1_min_sample = jitter1_min;
1421                                 jitter1_max = 0.0;
1422                                 jitter1_min = 0.0;
1423                         }
1424                 }
1425
1426                 /*
1427                         Handle miscellaneous stuff
1428                 */
1429                 
1430                 if(client.accessDenied())
1431                 {
1432                         error_message = L"Access denied. Reason: "
1433                                         +client.accessDeniedReason();
1434                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1435                         break;
1436                 }
1437
1438                 if(g_gamecallback->disconnect_requested)
1439                 {
1440                         g_gamecallback->disconnect_requested = false;
1441                         break;
1442                 }
1443
1444                 if(g_gamecallback->changepassword_requested)
1445                 {
1446                         (new GUIPasswordChange(guienv, guiroot, -1,
1447                                 &g_menumgr, &client))->drop();
1448                         g_gamecallback->changepassword_requested = false;
1449                 }
1450
1451                 /*
1452                         Process TextureSource's queue
1453                 */
1454                 tsrc->processQueue();
1455
1456                 /*
1457                         Random calculations
1458                 */
1459                 last_screensize = screensize;
1460                 screensize = driver->getScreenSize();
1461                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1462                 //bool screensize_changed = screensize != last_screensize;
1463
1464                 // Resize hotbar
1465                 if(screensize.Y <= 800)
1466                         hotbar_imagesize = 32;
1467                 else if(screensize.Y <= 1280)
1468                         hotbar_imagesize = 48;
1469                 else
1470                         hotbar_imagesize = 64;
1471                 
1472                 // Hilight boxes collected during the loop and displayed
1473                 core::list< core::aabbox3d<f32> > hilightboxes;
1474                 
1475                 // Info text
1476                 std::wstring infotext;
1477
1478                 /*
1479                         Debug info for client
1480                 */
1481                 {
1482                         static float counter = 0.0;
1483                         counter -= dtime;
1484                         if(counter < 0)
1485                         {
1486                                 counter = 30.0;
1487                                 client.printDebugInfo(infostream);
1488                         }
1489                 }
1490
1491                 /*
1492                         Profiler
1493                 */
1494                 float profiler_print_interval =
1495                                 g_settings->getFloat("profiler_print_interval");
1496                 bool print_to_log = true;
1497                 if(profiler_print_interval == 0){
1498                         print_to_log = false;
1499                         profiler_print_interval = 5;
1500                 }
1501                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1502                 {
1503                         if(print_to_log){
1504                                 infostream<<"Profiler:"<<std::endl;
1505                                 g_profiler->print(infostream);
1506                         }
1507
1508                         update_profiler_gui(guitext_profiler, font, text_height,
1509                                         show_profiler, show_profiler_max);
1510
1511                         g_profiler->clear();
1512                 }
1513
1514                 /*
1515                         Direct handling of user input
1516                 */
1517                 
1518                 // Reset input if window not active or some menu is active
1519                 if(device->isWindowActive() == false
1520                                 || noMenuActive() == false
1521                                 || guienv->hasFocus(gui_chat_console))
1522                 {
1523                         input->clear();
1524                 }
1525
1526                 // Input handler step() (used by the random input generator)
1527                 input->step(dtime);
1528
1529                 /*
1530                         Launch menus and trigger stuff according to keys
1531                 */
1532                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1533                 {
1534                         // drop selected item
1535                         IDropAction *a = new IDropAction();
1536                         a->count = 0;
1537                         a->from_inv.setCurrentPlayer();
1538                         a->from_list = "main";
1539                         a->from_i = client.getPlayerItem();
1540                         client.inventoryAction(a);
1541                 }
1542                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1543                 {
1544                         infostream<<"the_game: "
1545                                         <<"Launching inventory"<<std::endl;
1546                         
1547                         GUIInventoryMenu *menu =
1548                                 new GUIInventoryMenu(guienv, guiroot, -1,
1549                                         &g_menumgr, v2s16(8,7),
1550                                         &client, gamedef);
1551
1552                         InventoryLocation inventoryloc;
1553                         inventoryloc.setCurrentPlayer();
1554
1555                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1556                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1557                                         "list", inventoryloc, "main",
1558                                         v2s32(0, 3), v2s32(8, 4)));
1559                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1560                                         "list", inventoryloc, "craft",
1561                                         v2s32(3, 0), v2s32(3, 3)));
1562                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1563                                         "list", inventoryloc, "craftpreview",
1564                                         v2s32(7, 1), v2s32(1, 1)));
1565
1566                         menu->setDrawSpec(draw_spec);
1567
1568                         menu->drop();
1569                 }
1570                 else if(input->wasKeyDown(EscapeKey))
1571                 {
1572                         infostream<<"the_game: "
1573                                         <<"Launching pause menu"<<std::endl;
1574                         // It will delete itself by itself
1575                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1576                                         &g_menumgr, simple_singleplayer_mode))->drop();
1577
1578                         // Move mouse cursor on top of the disconnect button
1579                         if(simple_singleplayer_mode)
1580                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1581                         else
1582                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1583                 }
1584                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1585                 {
1586                         TextDest *dest = new TextDestChat(&client);
1587
1588                         (new GUITextInputMenu(guienv, guiroot, -1,
1589                                         &g_menumgr, dest,
1590                                         L""))->drop();
1591                 }
1592                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1593                 {
1594                         TextDest *dest = new TextDestChat(&client);
1595
1596                         (new GUITextInputMenu(guienv, guiroot, -1,
1597                                         &g_menumgr, dest,
1598                                         L"/"))->drop();
1599                 }
1600                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1601                 {
1602                         if (!gui_chat_console->isOpenInhibited())
1603                         {
1604                                 // Open up to over half of the screen
1605                                 gui_chat_console->openConsole(0.6);
1606                                 guienv->setFocus(gui_chat_console);
1607                         }
1608                 }
1609                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1610                 {
1611                         if(g_settings->getBool("free_move"))
1612                         {
1613                                 g_settings->set("free_move","false");
1614                                 statustext = L"free_move disabled";
1615                                 statustext_time = 0;
1616                         }
1617                         else
1618                         {
1619                                 g_settings->set("free_move","true");
1620                                 statustext = L"free_move enabled";
1621                                 statustext_time = 0;
1622                         }
1623                 }
1624                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1625                 {
1626                         if(g_settings->getBool("fast_move"))
1627                         {
1628                                 g_settings->set("fast_move","false");
1629                                 statustext = L"fast_move disabled";
1630                                 statustext_time = 0;
1631                         }
1632                         else
1633                         {
1634                                 g_settings->set("fast_move","true");
1635                                 statustext = L"fast_move enabled";
1636                                 statustext_time = 0;
1637                         }
1638                 }
1639                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1640                 {
1641                         irr::video::IImage* const image = driver->createScreenShot(); 
1642                         if (image) { 
1643                                 irr::c8 filename[256]; 
1644                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1645                                                  g_settings->get("screenshot_path").c_str(),
1646                                                  device->getTimer()->getRealTime()); 
1647                                 if (driver->writeImageToFile(image, filename)) {
1648                                         std::wstringstream sstr;
1649                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1650                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1651                                         statustext = sstr.str();
1652                                         statustext_time = 0;
1653                                 } else{
1654                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1655                                 }
1656                                 image->drop(); 
1657                         }                        
1658                 }
1659                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1660                 {
1661                         show_hud = !show_hud;
1662                         if(show_hud)
1663                                 statustext = L"HUD shown";
1664                         else
1665                                 statustext = L"HUD hidden";
1666                         statustext_time = 0;
1667                 }
1668                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1669                 {
1670                         show_chat = !show_chat;
1671                         if(show_chat)
1672                                 statustext = L"Chat shown";
1673                         else
1674                                 statustext = L"Chat hidden";
1675                         statustext_time = 0;
1676                 }
1677                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1678                 {
1679                         force_fog_off = !force_fog_off;
1680                         if(force_fog_off)
1681                                 statustext = L"Fog disabled";
1682                         else
1683                                 statustext = L"Fog enabled";
1684                         statustext_time = 0;
1685                 }
1686                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1687                 {
1688                         disable_camera_update = !disable_camera_update;
1689                         if(disable_camera_update)
1690                                 statustext = L"Camera update disabled";
1691                         else
1692                                 statustext = L"Camera update enabled";
1693                         statustext_time = 0;
1694                 }
1695                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1696                 {
1697                         // Initial / 3x toggle: Chat only
1698                         // 1x toggle: Debug text with chat
1699                         // 2x toggle: Debug text with profiler graph
1700                         if(!show_debug)
1701                         {
1702                                 show_debug = true;
1703                                 show_profiler_graph = false;
1704                                 statustext = L"Debug info shown";
1705                                 statustext_time = 0;
1706                         }
1707                         else if(show_profiler_graph)
1708                         {
1709                                 show_debug = false;
1710                                 show_profiler_graph = false;
1711                                 statustext = L"Debug info and profiler graph hidden";
1712                                 statustext_time = 0;
1713                         }
1714                         else
1715                         {
1716                                 show_profiler_graph = true;
1717                                 statustext = L"Profiler graph shown";
1718                                 statustext_time = 0;
1719                         }
1720                 }
1721                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1722                 {
1723                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1724
1725                         // FIXME: This updates the profiler with incomplete values
1726                         update_profiler_gui(guitext_profiler, font, text_height,
1727                                         show_profiler, show_profiler_max);
1728
1729                         if(show_profiler != 0)
1730                         {
1731                                 std::wstringstream sstr;
1732                                 sstr<<"Profiler shown (page "<<show_profiler
1733                                         <<" of "<<show_profiler_max<<")";
1734                                 statustext = sstr.str();
1735                                 statustext_time = 0;
1736                         }
1737                         else
1738                         {
1739                                 statustext = L"Profiler hidden";
1740                                 statustext_time = 0;
1741                         }
1742                 }
1743                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1744                 {
1745                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1746                         s16 range_new = range + 10;
1747                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1748                         statustext = narrow_to_wide(
1749                                         "Minimum viewing range changed to "
1750                                         + itos(range_new));
1751                         statustext_time = 0;
1752                 }
1753                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1754                 {
1755                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1756                         s16 range_new = range - 10;
1757                         if(range_new < 0)
1758                                 range_new = range;
1759                         g_settings->set("viewing_range_nodes_min",
1760                                         itos(range_new));
1761                         statustext = narrow_to_wide(
1762                                         "Minimum viewing range changed to "
1763                                         + itos(range_new));
1764                         statustext_time = 0;
1765                 }
1766                 
1767                 // Handle QuicktuneShortcutter
1768                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1769                         quicktune.next();
1770                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1771                         quicktune.prev();
1772                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1773                         quicktune.inc();
1774                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1775                         quicktune.dec();
1776                 {
1777                         std::string msg = quicktune.getMessage();
1778                         if(msg != ""){
1779                                 statustext = narrow_to_wide(msg);
1780                                 statustext_time = 0;
1781                         }
1782                 }
1783
1784                 // Item selection with mouse wheel
1785                 u16 new_playeritem = client.getPlayerItem();
1786                 {
1787                         s32 wheel = input->getMouseWheel();
1788                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1789                                         hotbar_itemcount-1);
1790
1791                         if(wheel < 0)
1792                         {
1793                                 if(new_playeritem < max_item)
1794                                         new_playeritem++;
1795                                 else
1796                                         new_playeritem = 0;
1797                         }
1798                         else if(wheel > 0)
1799                         {
1800                                 if(new_playeritem > 0)
1801                                         new_playeritem--;
1802                                 else
1803                                         new_playeritem = max_item;
1804                         }
1805                 }
1806                 
1807                 // Item selection
1808                 for(u16 i=0; i<10; i++)
1809                 {
1810                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1811                         if(input->wasKeyDown(*kp))
1812                         {
1813                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1814                                 {
1815                                         new_playeritem = i;
1816
1817                                         infostream<<"Selected item: "
1818                                                         <<new_playeritem<<std::endl;
1819                                 }
1820                         }
1821                 }
1822
1823                 // Viewing range selection
1824                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1825                 {
1826                         draw_control.range_all = !draw_control.range_all;
1827                         if(draw_control.range_all)
1828                         {
1829                                 infostream<<"Enabled full viewing range"<<std::endl;
1830                                 statustext = L"Enabled full viewing range";
1831                                 statustext_time = 0;
1832                         }
1833                         else
1834                         {
1835                                 infostream<<"Disabled full viewing range"<<std::endl;
1836                                 statustext = L"Disabled full viewing range";
1837                                 statustext_time = 0;
1838                         }
1839                 }
1840
1841                 // Print debug stacks
1842                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1843                 {
1844                         dstream<<"-----------------------------------------"
1845                                         <<std::endl;
1846                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1847                         dstream<<"-----------------------------------------"
1848                                         <<std::endl;
1849                         debug_stacks_print();
1850                 }
1851
1852                 /*
1853                         Mouse and camera control
1854                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1855                 */
1856                 
1857                 float turn_amount = 0;
1858                 if((device->isWindowActive() && noMenuActive()) || random_input)
1859                 {
1860                         if(!random_input)
1861                         {
1862                                 // Mac OSX gets upset if this is set every frame
1863                                 if(device->getCursorControl()->isVisible())
1864                                         device->getCursorControl()->setVisible(false);
1865                         }
1866
1867                         if(first_loop_after_window_activation){
1868                                 //infostream<<"window active, first loop"<<std::endl;
1869                                 first_loop_after_window_activation = false;
1870                         }
1871                         else{
1872                                 s32 dx = input->getMousePos().X - displaycenter.X;
1873                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1874                                 if(invert_mouse)
1875                                         dy = -dy;
1876                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1877                                 
1878                                 /*const float keyspeed = 500;
1879                                 if(input->isKeyDown(irr::KEY_UP))
1880                                         dy -= dtime * keyspeed;
1881                                 if(input->isKeyDown(irr::KEY_DOWN))
1882                                         dy += dtime * keyspeed;
1883                                 if(input->isKeyDown(irr::KEY_LEFT))
1884                                         dx -= dtime * keyspeed;
1885                                 if(input->isKeyDown(irr::KEY_RIGHT))
1886                                         dx += dtime * keyspeed;*/
1887                                 
1888                                 float d = 0.2;
1889                                 camera_yaw -= dx*d;
1890                                 camera_pitch += dy*d;
1891                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1892                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1893                                 
1894                                 turn_amount = v2f(dx, dy).getLength() * d;
1895                         }
1896                         input->setMousePos(displaycenter.X, displaycenter.Y);
1897                 }
1898                 else{
1899                         // Mac OSX gets upset if this is set every frame
1900                         if(device->getCursorControl()->isVisible() == false)
1901                                 device->getCursorControl()->setVisible(true);
1902
1903                         //infostream<<"window inactive"<<std::endl;
1904                         first_loop_after_window_activation = true;
1905                 }
1906                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1907                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1908
1909                 /*
1910                         Player speed control
1911                 */
1912                 {
1913                         /*bool a_up,
1914                         bool a_down,
1915                         bool a_left,
1916                         bool a_right,
1917                         bool a_jump,
1918                         bool a_superspeed,
1919                         bool a_sneak,
1920                         float a_pitch,
1921                         float a_yaw*/
1922                         PlayerControl control(
1923                                 input->isKeyDown(getKeySetting("keymap_forward")),
1924                                 input->isKeyDown(getKeySetting("keymap_backward")),
1925                                 input->isKeyDown(getKeySetting("keymap_left")),
1926                                 input->isKeyDown(getKeySetting("keymap_right")),
1927                                 input->isKeyDown(getKeySetting("keymap_jump")),
1928                                 input->isKeyDown(getKeySetting("keymap_special1")),
1929                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1930                                 camera_pitch,
1931                                 camera_yaw
1932                         );
1933                         client.setPlayerControl(control);
1934                 }
1935                 
1936                 /*
1937                         Run server
1938                 */
1939
1940                 if(server != NULL)
1941                 {
1942                         //TimeTaker timer("server->step(dtime)");
1943                         server->step(dtime);
1944                 }
1945
1946                 /*
1947                         Process environment
1948                 */
1949                 
1950                 {
1951                         //TimeTaker timer("client.step(dtime)");
1952                         client.step(dtime);
1953                         //client.step(dtime_avg1);
1954                 }
1955
1956                 {
1957                         // Read client events
1958                         for(;;)
1959                         {
1960                                 ClientEvent event = client.getClientEvent();
1961                                 if(event.type == CE_NONE)
1962                                 {
1963                                         break;
1964                                 }
1965                                 else if(event.type == CE_PLAYER_DAMAGE)
1966                                 {
1967                                         //u16 damage = event.player_damage.amount;
1968                                         //infostream<<"Player damage: "<<damage<<std::endl;
1969                                         damage_flash_timer = 0.05;
1970                                         if(event.player_damage.amount >= 2){
1971                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1972                                         }
1973                                 }
1974                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1975                                 {
1976                                         camera_yaw = event.player_force_move.yaw;
1977                                         camera_pitch = event.player_force_move.pitch;
1978                                 }
1979                                 else if(event.type == CE_DEATHSCREEN)
1980                                 {
1981                                         if(respawn_menu_active)
1982                                                 continue;
1983
1984                                         /*bool set_camera_point_target =
1985                                                         event.deathscreen.set_camera_point_target;
1986                                         v3f camera_point_target;
1987                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1988                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1989                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1990                                         MainRespawnInitiator *respawner =
1991                                                         new MainRespawnInitiator(
1992                                                                         &respawn_menu_active, &client);
1993                                         GUIDeathScreen *menu =
1994                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1995                                                                 &g_menumgr, respawner);
1996                                         menu->drop();
1997                                         
1998                                         chat_backend.addMessage(L"", L"You died.");
1999
2000                                         /* Handle visualization */
2001
2002                                         damage_flash_timer = 0;
2003
2004                                         /*LocalPlayer* player = client.getLocalPlayer();
2005                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
2006                                         camera.update(player, busytime, screensize);*/
2007                                 }
2008                                 else if(event.type == CE_TEXTURES_UPDATED)
2009                                 {
2010                                         update_wielded_item_trigger = true;
2011                                 }
2012                         }
2013                 }
2014                 
2015                 //TimeTaker //timer2("//timer2");
2016
2017                 /*
2018                         For interaction purposes, get info about the held item
2019                         - What item is it?
2020                         - Is it a usable item?
2021                         - Can it point to liquids?
2022                 */
2023                 ItemStack playeritem;
2024                 bool playeritem_usable = false;
2025                 bool playeritem_liquids_pointable = false;
2026                 {
2027                         InventoryList *mlist = local_inventory.getList("main");
2028                         if(mlist != NULL)
2029                         {
2030                                 playeritem = mlist->getItem(client.getPlayerItem());
2031                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2032                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2033                         }
2034                 }
2035                 ToolCapabilities playeritem_toolcap =
2036                                 playeritem.getToolCapabilities(itemdef);
2037                 
2038                 /*
2039                         Update camera
2040                 */
2041
2042                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2043                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2044                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2045                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2046                 camera.update(player, busytime, screensize, tool_reload_ratio);
2047                 camera.step(dtime);
2048
2049                 v3f player_position = player->getPosition();
2050                 v3f camera_position = camera.getPosition();
2051                 v3f camera_direction = camera.getDirection();
2052                 f32 camera_fov = camera.getFovMax();
2053                 
2054                 if(!disable_camera_update){
2055                         client.getEnv().getClientMap().updateCamera(camera_position,
2056                                 camera_direction, camera_fov);
2057                 }
2058                 
2059                 // Update sound listener
2060                 sound->updateListener(camera.getCameraNode()->getPosition(),
2061                                 v3f(0,0,0), // velocity
2062                                 camera.getCameraNode()->getTarget(),
2063                                 camera.getCameraNode()->getUpVector());
2064
2065                 /*
2066                         Update sound maker
2067                 */
2068                 {
2069                         soundmaker.step(dtime);
2070                         
2071                         ClientMap &map = client.getEnv().getClientMap();
2072                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2073                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2074                 }
2075
2076                 /*
2077                         Calculate what block is the crosshair pointing to
2078                 */
2079                 
2080                 //u32 t1 = device->getTimer()->getRealTime();
2081                 
2082                 f32 d = 4; // max. distance
2083                 core::line3d<f32> shootline(camera_position,
2084                                 camera_position + camera_direction * BS * (d+1));
2085
2086                 core::aabbox3d<f32> hilightbox;
2087                 bool should_show_hilightbox = false;
2088                 ClientActiveObject *selected_object = NULL;
2089
2090                 PointedThing pointed = getPointedThing(
2091                                 // input
2092                                 &client, player_position, camera_direction,
2093                                 camera_position, shootline, d,
2094                                 playeritem_liquids_pointable, !ldown_for_dig,
2095                                 // output
2096                                 hilightbox, should_show_hilightbox,
2097                                 selected_object);
2098
2099                 if(pointed != pointed_old)
2100                 {
2101                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2102                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2103                 }
2104
2105                 /*
2106                         Visualize selection
2107                 */
2108                 if(should_show_hilightbox)
2109                         hilightboxes.push_back(hilightbox);
2110
2111                 /*
2112                         Stop digging when
2113                         - releasing left mouse button
2114                         - pointing away from node
2115                 */
2116                 if(digging)
2117                 {
2118                         if(input->getLeftReleased())
2119                         {
2120                                 infostream<<"Left button released"
2121                                         <<" (stopped digging)"<<std::endl;
2122                                 digging = false;
2123                         }
2124                         else if(pointed != pointed_old)
2125                         {
2126                                 if (pointed.type == POINTEDTHING_NODE
2127                                         && pointed_old.type == POINTEDTHING_NODE
2128                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2129                                 {
2130                                         // Still pointing to the same node,
2131                                         // but a different face. Don't reset.
2132                                 }
2133                                 else
2134                                 {
2135                                         infostream<<"Pointing away from node"
2136                                                 <<" (stopped digging)"<<std::endl;
2137                                         digging = false;
2138                                 }
2139                         }
2140                         if(!digging)
2141                         {
2142                                 client.interact(1, pointed_old);
2143                                 client.setCrack(-1, v3s16(0,0,0));
2144                                 dig_time = 0.0;
2145                         }
2146                 }
2147                 if(!digging && ldown_for_dig && !input->getLeftState())
2148                 {
2149                         ldown_for_dig = false;
2150                 }
2151
2152                 bool left_punch = false;
2153
2154                 if(playeritem_usable && input->getLeftState())
2155                 {
2156                         if(input->getLeftClicked())
2157                                 client.interact(4, pointed);
2158                 }
2159                 else if(pointed.type == POINTEDTHING_NODE)
2160                 {
2161                         v3s16 nodepos = pointed.node_undersurface;
2162                         v3s16 neighbourpos = pointed.node_abovesurface;
2163
2164                         /*
2165                                 Check information text of node
2166                         */
2167                         
2168                         ClientMap &map = client.getEnv().getClientMap();
2169                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2170                         if(meta){
2171                                 infotext = narrow_to_wide(meta->infoText());
2172                         } else {
2173                                 MapNode n = map.getNode(nodepos);
2174                                 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2175                                         infotext = L"Unknown node: ";
2176                                         infotext += narrow_to_wide(nodedef->get(n).name);
2177                                 }
2178                         }
2179                         
2180                         // We can't actually know, but assume the sound of right-clicking
2181                         // to be the sound of placing a node
2182                         soundmaker.m_player_rightpunch_sound.gain = 0.5;
2183                         soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2184                         
2185                         /*
2186                                 Handle digging
2187                         */
2188                         
2189                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
2190                         {
2191                                 if(!digging)
2192                                 {
2193                                         infostream<<"Started digging"<<std::endl;
2194                                         client.interact(0, pointed);
2195                                         digging = true;
2196                                         ldown_for_dig = true;
2197                                 }
2198                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2199
2200                                 // Get digging parameters
2201                                 DigParams params = getDigParams(nodedef->get(n).groups,
2202                                                 &playeritem_toolcap);
2203                                 // If can't dig, try hand
2204                                 if(!params.diggable){
2205                                         const ItemDefinition &hand = itemdef->get("");
2206                                         const ToolCapabilities *tp = hand.tool_capabilities;
2207                                         if(tp)
2208                                                 params = getDigParams(nodedef->get(n).groups, tp);
2209                                 }
2210                                 
2211                                 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2212                                 if(params.main_group == "crumbly")
2213                                         soundmaker.m_player_leftpunch_sound.name =
2214                                                         "default_dig_crumbly";
2215                                 else if(params.main_group == "cracky")
2216                                         soundmaker.m_player_leftpunch_sound.name =
2217                                                         "default_dig_cracky";
2218                                 else
2219                                         soundmaker.m_player_leftpunch_sound.name = "";
2220
2221                                 float dig_time_complete = 0.0;
2222
2223                                 if(params.diggable == false)
2224                                 {
2225                                         // I guess nobody will wait for this long
2226                                         dig_time_complete = 10000000.0;
2227                                 }
2228                                 else
2229                                 {
2230                                         dig_time_complete = params.time;
2231                                 }
2232
2233                                 if(dig_time_complete >= 0.001)
2234                                 {
2235                                         dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2236                                                         * dig_time/dig_time_complete);
2237                                 }
2238                                 // This is for torches
2239                                 else
2240                                 {
2241                                         dig_index = CRACK_ANIMATION_LENGTH;
2242                                 }
2243                                 
2244                                 // Don't show cracks if not diggable
2245                                 if(dig_time_complete >= 100000.0)
2246                                 {
2247                                 }
2248                                 else if(dig_index < CRACK_ANIMATION_LENGTH)
2249                                 {
2250                                         //TimeTaker timer("client.setTempMod");
2251                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2252                                         client.setCrack(dig_index, nodepos);
2253                                 }
2254                                 else
2255                                 {
2256                                         infostream<<"Digging completed"<<std::endl;
2257                                         client.interact(2, pointed);
2258                                         client.setCrack(-1, v3s16(0,0,0));
2259                                         client.removeNode(nodepos);
2260
2261                                         dig_time = 0;
2262                                         digging = false;
2263
2264                                         nodig_delay_timer = dig_time_complete
2265                                                         / (float)CRACK_ANIMATION_LENGTH;
2266
2267                                         // We don't want a corresponding delay to
2268                                         // very time consuming nodes
2269                                         if(nodig_delay_timer > 0.5)
2270                                         {
2271                                                 nodig_delay_timer = 0.5;
2272                                         }
2273                                         // We want a slight delay to very little
2274                                         // time consuming nodes
2275                                         float mindelay = 0.15;
2276                                         if(nodig_delay_timer < mindelay)
2277                                         {
2278                                                 nodig_delay_timer = mindelay;
2279                                         }
2280                                 }
2281
2282                                 dig_time += dtime;
2283
2284                                 camera.setDigging(0);  // left click animation
2285                         }
2286
2287                         if(input->getRightClicked())
2288                         {
2289                                 infostream<<"Ground right-clicked"<<std::endl;
2290                                 
2291                                 // If metadata provides an inventory view, activate it
2292                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2293                                 {
2294                                         infostream<<"Launching custom inventory view"<<std::endl;
2295
2296                                         InventoryLocation inventoryloc;
2297                                         inventoryloc.setNodeMeta(nodepos);
2298                                         
2299
2300                                         /*
2301                                                 Create menu
2302                                         */
2303
2304                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2305                                         v2s16 invsize =
2306                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
2307                                                         draw_spec,
2308                                                         meta->getInventoryDrawSpecString(),
2309                                                         inventoryloc);
2310
2311                                         GUIInventoryMenu *menu =
2312                                                 new GUIInventoryMenu(guienv, guiroot, -1,
2313                                                         &g_menumgr, invsize,
2314                                                         &client, gamedef);
2315                                         menu->setDrawSpec(draw_spec);
2316                                         menu->drop();
2317                                 }
2318                                 // If metadata provides text input, activate text input
2319                                 else if(meta && meta->allowsTextInput() && !random_input)
2320                                 {
2321                                         infostream<<"Launching metadata text input"<<std::endl;
2322                                         
2323                                         // Get a new text for it
2324
2325                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2326
2327                                         std::wstring wtext = narrow_to_wide(meta->getText());
2328
2329                                         (new GUITextInputMenu(guienv, guiroot, -1,
2330                                                         &g_menumgr, dest,
2331                                                         wtext))->drop();
2332                                 }
2333                                 // Otherwise report right click to server
2334                                 else
2335                                 {
2336                                         client.interact(3, pointed);
2337                                         camera.setDigging(1);  // right click animation
2338                                 }
2339                         }
2340                 }
2341                 else if(pointed.type == POINTEDTHING_OBJECT)
2342                 {
2343                         infotext = narrow_to_wide(selected_object->infoText());
2344
2345                         if(infotext == L"" && show_debug){
2346                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2347                         }
2348
2349                         //if(input->getLeftClicked())
2350                         if(input->getLeftState())
2351                         {
2352                                 bool do_punch = false;
2353                                 bool do_punch_damage = false;
2354                                 if(object_hit_delay_timer <= 0.0){
2355                                         do_punch = true;
2356                                         do_punch_damage = true;
2357                                         object_hit_delay_timer = object_hit_delay;
2358                                 }
2359                                 if(input->getLeftClicked()){
2360                                         do_punch = true;
2361                                 }
2362                                 if(do_punch){
2363                                         infostream<<"Left-clicked object"<<std::endl;
2364                                         left_punch = true;
2365                                 }
2366                                 if(do_punch_damage){
2367                                         // Report direct punch
2368                                         v3f objpos = selected_object->getPosition();
2369                                         v3f dir = (objpos - player_position).normalize();
2370                                         
2371                                         bool disable_send = selected_object->directReportPunch(
2372                                                         dir, &playeritem, time_from_last_punch);
2373                                         time_from_last_punch = 0;
2374                                         if(!disable_send)
2375                                                 client.interact(0, pointed);
2376                                 }
2377                         }
2378                         else if(input->getRightClicked())
2379                         {
2380                                 infostream<<"Right-clicked object"<<std::endl;
2381                                 client.interact(3, pointed);  // place
2382                         }
2383                 }
2384                 else if(input->getLeftState())
2385                 {
2386                         // When button is held down in air, show continuous animation
2387                         left_punch = true;
2388                 }
2389
2390                 pointed_old = pointed;
2391                 
2392                 if(left_punch || input->getLeftClicked())
2393                 {
2394                         camera.setDigging(0); // left click animation
2395                 }
2396
2397                 input->resetLeftClicked();
2398                 input->resetRightClicked();
2399
2400                 input->resetLeftReleased();
2401                 input->resetRightReleased();
2402                 
2403                 /*
2404                         Calculate stuff for drawing
2405                 */
2406
2407                 /*
2408                         Fog range
2409                 */
2410         
2411                 f32 fog_range;
2412                 if(farmesh)
2413                 {
2414                         fog_range = BS*farmesh_range;
2415                 }
2416                 else
2417                 {
2418                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2419                         fog_range *= 0.9;
2420                         if(draw_control.range_all)
2421                                 fog_range = 100000*BS;
2422                 }
2423
2424                 /*
2425                         Calculate general brightness
2426                 */
2427                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2428                 float time_brightness = (float)decode_light(
2429                                 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2430                 float direct_brightness = 0;
2431                 bool sunlight_seen = false;
2432                 if(g_settings->getBool("free_move")){
2433                         direct_brightness = time_brightness;
2434                         sunlight_seen = true;
2435                 } else {
2436                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2437                         float old_brightness = sky->getBrightness();
2438                         direct_brightness = (float)client.getEnv().getClientMap()
2439                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2440                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2441                                         / 255.0;
2442                 }
2443                 
2444                 time_of_day = client.getEnv().getTimeOfDayF();
2445                 float maxsm = 0.05;
2446                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2447                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2448                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2449                         time_of_day_smooth = time_of_day;
2450                 float todsm = 0.05;
2451                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2452                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2453                                         + (time_of_day+1.0) * todsm;
2454                 else
2455                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2456                                         + time_of_day * todsm;
2457                         
2458                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2459                                 sunlight_seen);
2460                 
2461                 float brightness = sky->getBrightness();
2462                 video::SColor bgcolor = sky->getBgColor();
2463                 video::SColor skycolor = sky->getSkyColor();
2464
2465                 /*
2466                         Update clouds
2467                 */
2468                 if(clouds){
2469                         if(sky->getCloudsVisible()){
2470                                 clouds->setVisible(true);
2471                                 clouds->step(dtime);
2472                                 clouds->update(v2f(player_position.X, player_position.Z),
2473                                                 sky->getCloudColor());
2474                         } else{
2475                                 clouds->setVisible(false);
2476                         }
2477                 }
2478                 
2479                 /*
2480                         Update farmesh
2481                 */
2482                 if(farmesh)
2483                 {
2484                         farmesh_range = draw_control.wanted_range * 10;
2485                         if(draw_control.range_all && farmesh_range < 500)
2486                                 farmesh_range = 500;
2487                         if(farmesh_range > 1000)
2488                                 farmesh_range = 1000;
2489
2490                         farmesh->step(dtime);
2491                         farmesh->update(v2f(player_position.X, player_position.Z),
2492                                         brightness, farmesh_range);
2493                 }
2494                 
2495                 /*
2496                         Fog
2497                 */
2498                 
2499                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2500                 {
2501                         driver->setFog(
2502                                 bgcolor,
2503                                 video::EFT_FOG_LINEAR,
2504                                 fog_range*0.4,
2505                                 fog_range*1.0,
2506                                 0.01,
2507                                 false, // pixel fog
2508                                 false // range fog
2509                         );
2510                 }
2511                 else
2512                 {
2513                         driver->setFog(
2514                                 bgcolor,
2515                                 video::EFT_FOG_LINEAR,
2516                                 100000*BS,
2517                                 110000*BS,
2518                                 0.01,
2519                                 false, // pixel fog
2520                                 false // range fog
2521                         );
2522                 }
2523
2524                 /*
2525                         Update gui stuff (0ms)
2526                 */
2527
2528                 //TimeTaker guiupdatetimer("Gui updating");
2529                 
2530                 const char program_name_and_version[] =
2531                         "Minetest-c55 " VERSION_STRING;
2532
2533                 if(show_debug)
2534                 {
2535                         static float drawtime_avg = 0;
2536                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2537                         /*static float beginscenetime_avg = 0;
2538                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2539                         static float scenetime_avg = 0;
2540                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2541                         static float endscenetime_avg = 0;
2542                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2543                         
2544                         char temptext[300];
2545                         snprintf(temptext, 300, "%s ("
2546                                         "R: range_all=%i"
2547                                         ")"
2548                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2549                                         ", v_range = %.1f, RTT = %.3f",
2550                                         program_name_and_version,
2551                                         draw_control.range_all,
2552                                         drawtime_avg,
2553                                         dtime_jitter1_max_fraction * 100.0,
2554                                         draw_control.wanted_range,
2555                                         client.getRTT()
2556                                         );
2557                         
2558                         guitext->setText(narrow_to_wide(temptext).c_str());
2559                         guitext->setVisible(true);
2560                 }
2561                 else if(show_hud || show_chat)
2562                 {
2563                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2564                         guitext->setVisible(true);
2565                 }
2566                 else
2567                 {
2568                         guitext->setVisible(false);
2569                 }
2570                 
2571                 if(show_debug)
2572                 {
2573                         char temptext[300];
2574                         snprintf(temptext, 300,
2575                                         "(% .1f, % .1f, % .1f)"
2576                                         " (yaw = %.1f)",
2577                                         player_position.X/BS,
2578                                         player_position.Y/BS,
2579                                         player_position.Z/BS,
2580                                         wrapDegrees_0_360(camera_yaw));
2581
2582                         guitext2->setText(narrow_to_wide(temptext).c_str());
2583                         guitext2->setVisible(true);
2584                 }
2585                 else
2586                 {
2587                         guitext2->setVisible(false);
2588                 }
2589                 
2590                 {
2591                         guitext_info->setText(infotext.c_str());
2592                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2593                 }
2594
2595                 {
2596                         float statustext_time_max = 1.5;
2597                         if(!statustext.empty())
2598                         {
2599                                 statustext_time += dtime;
2600                                 if(statustext_time >= statustext_time_max)
2601                                 {
2602                                         statustext = L"";
2603                                         statustext_time = 0;
2604                                 }
2605                         }
2606                         guitext_status->setText(statustext.c_str());
2607                         guitext_status->setVisible(!statustext.empty());
2608
2609                         if(!statustext.empty())
2610                         {
2611                                 s32 status_y = screensize.Y - 130;
2612                                 core::rect<s32> rect(
2613                                                 10,
2614                                                 status_y - guitext_status->getTextHeight(),
2615                                                 screensize.X - 10,
2616                                                 status_y
2617                                 );
2618                                 guitext_status->setRelativePosition(rect);
2619
2620                                 // Fade out
2621                                 video::SColor initial_color(255,0,0,0);
2622                                 if(guienv->getSkin())
2623                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2624                                 video::SColor final_color = initial_color;
2625                                 final_color.setAlpha(0);
2626                                 video::SColor fade_color =
2627                                         initial_color.getInterpolated_quadratic(
2628                                                 initial_color,
2629                                                 final_color,
2630                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
2631                                 guitext_status->setOverrideColor(fade_color);
2632                                 guitext_status->enableOverrideColor(true);
2633                         }
2634                 }
2635                 
2636                 /*
2637                         Get chat messages from client
2638                 */
2639                 {
2640                         // Get new messages from error log buffer
2641                         while(!chat_log_error_buf.empty())
2642                         {
2643                                 chat_backend.addMessage(L"", narrow_to_wide(
2644                                                 chat_log_error_buf.get()));
2645                         }
2646                         // Get new messages from client
2647                         std::wstring message;
2648                         while(client.getChatMessage(message))
2649                         {
2650                                 chat_backend.addUnparsedMessage(message);
2651                         }
2652                         // Remove old messages
2653                         chat_backend.step(dtime);
2654
2655                         // Display all messages in a static text element
2656                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2657                         std::wstring recent_chat = chat_backend.getRecentChat();
2658                         guitext_chat->setText(recent_chat.c_str());
2659
2660                         // Update gui element size and position
2661                         s32 chat_y = 5+(text_height+5);
2662                         if(show_debug)
2663                                 chat_y += (text_height+5);
2664                         core::rect<s32> rect(
2665                                 10,
2666                                 chat_y,
2667                                 screensize.X - 10,
2668                                 chat_y + guitext_chat->getTextHeight()
2669                         );
2670                         guitext_chat->setRelativePosition(rect);
2671
2672                         // Don't show chat if disabled or empty or profiler is enabled
2673                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
2674                                         && !show_profiler);
2675                 }
2676
2677                 /*
2678                         Inventory
2679                 */
2680                 
2681                 if(client.getPlayerItem() != new_playeritem)
2682                 {
2683                         client.selectPlayerItem(new_playeritem);
2684                 }
2685                 if(client.getLocalInventoryUpdated())
2686                 {
2687                         //infostream<<"Updating local inventory"<<std::endl;
2688                         client.getLocalInventory(local_inventory);
2689                         
2690                         update_wielded_item_trigger = true;
2691                 }
2692                 if(update_wielded_item_trigger)
2693                 {
2694                         update_wielded_item_trigger = false;
2695                         // Update wielded tool
2696                         InventoryList *mlist = local_inventory.getList("main");
2697                         ItemStack item;
2698                         if(mlist != NULL)
2699                                 item = mlist->getItem(client.getPlayerItem());
2700                         camera.wield(item);
2701                 }
2702                 
2703                 /*
2704                         Drawing begins
2705                 */
2706
2707                 TimeTaker tt_draw("mainloop: draw");
2708
2709                 
2710                 {
2711                         TimeTaker timer("beginScene");
2712                         //driver->beginScene(false, true, bgcolor);
2713                         //driver->beginScene(true, true, bgcolor);
2714                         driver->beginScene(true, true, skycolor);
2715                         beginscenetime = timer.stop(true);
2716                 }
2717                 
2718                 //timer3.stop();
2719         
2720                 //infostream<<"smgr->drawAll()"<<std::endl;
2721                 {
2722                         TimeTaker timer("smgr");
2723                         smgr->drawAll();
2724                         scenetime = timer.stop(true);
2725                 }
2726                 
2727                 {
2728                 //TimeTaker timer9("auxiliary drawings");
2729                 // 0ms
2730                 
2731                 //timer9.stop();
2732                 //TimeTaker //timer10("//timer10");
2733                 
2734                 video::SMaterial m;
2735                 //m.Thickness = 10;
2736                 m.Thickness = 3;
2737                 m.Lighting = false;
2738                 driver->setMaterial(m);
2739
2740                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2741
2742                 if(show_hud)
2743                 {
2744                         for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2745                                         i != hilightboxes.end(); i++)
2746                         {
2747                                 /*infostream<<"hilightbox min="
2748                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2749                                                 <<" max="
2750                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2751                                                 <<std::endl;*/
2752                                 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2753                         }
2754                 }
2755
2756                 /*
2757                         Wielded tool
2758                 */
2759                 if(show_hud)
2760                 {
2761                         // Warning: This clears the Z buffer.
2762                         camera.drawWieldedTool();
2763                 }
2764
2765                 /*
2766                         Post effects
2767                 */
2768                 {
2769                         client.getEnv().getClientMap().renderPostFx();
2770                 }
2771
2772                 /*
2773                         Profiler graph
2774                 */
2775                 if(show_profiler_graph)
2776                 {
2777                         graph.draw(10, screensize.Y - 10, driver, font);
2778                 }
2779
2780                 /*
2781                         Draw crosshair
2782                 */
2783                 if(show_hud)
2784                 {
2785                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2786                                         displaycenter + core::vector2d<s32>(10,0),
2787                                         video::SColor(255,255,255,255));
2788                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2789                                         displaycenter + core::vector2d<s32>(0,10),
2790                                         video::SColor(255,255,255,255));
2791                 }
2792
2793                 } // timer
2794
2795                 //timer10.stop();
2796                 //TimeTaker //timer11("//timer11");
2797
2798                 /*
2799                         Draw gui
2800                 */
2801                 // 0-1ms
2802                 guienv->drawAll();
2803
2804                 /*
2805                         Draw hotbar
2806                 */
2807                 if(show_hud)
2808                 {
2809                         draw_hotbar(driver, font, gamedef,
2810                                         v2s32(displaycenter.X, screensize.Y),
2811                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2812                                         client.getHP(), client.getPlayerItem());
2813                 }
2814
2815                 /*
2816                         Damage flash
2817                 */
2818                 if(damage_flash_timer > 0.0)
2819                 {
2820                         damage_flash_timer -= dtime;
2821                         
2822                         video::SColor color(128,255,0,0);
2823                         driver->draw2DRectangle(color,
2824                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2825                                         NULL);
2826                 }
2827
2828                 /*
2829                         End scene
2830                 */
2831                 {
2832                         TimeTaker timer("endScene");
2833                         endSceneX(driver);
2834                         endscenetime = timer.stop(true);
2835                 }
2836
2837                 drawtime = tt_draw.stop(true);
2838                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2839
2840                 /*
2841                         End of drawing
2842                 */
2843
2844                 static s16 lastFPS = 0;
2845                 //u16 fps = driver->getFPS();
2846                 u16 fps = (1.0/dtime_avg1);
2847
2848                 if (lastFPS != fps)
2849                 {
2850                         core::stringw str = L"Minetest [";
2851                         str += driver->getName();
2852                         str += "] FPS=";
2853                         str += fps;
2854
2855                         device->setWindowCaption(str.c_str());
2856                         lastFPS = fps;
2857                 }
2858
2859                 /*
2860                         Log times and stuff for visualization
2861                 */
2862                 Profiler::GraphValues values;
2863                 g_profiler->graphGet(values);
2864                 graph.put(values);
2865         }
2866
2867         /*
2868                 Drop stuff
2869         */
2870         if(clouds)
2871                 clouds->drop();
2872         if(gui_chat_console)
2873                 gui_chat_console->drop();
2874         
2875         /*
2876                 Draw a "shutting down" screen, which will be shown while the map
2877                 generator and other stuff quits
2878         */
2879         {
2880                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2881                 draw_load_screen(L"Shutting down stuff...", driver, font);
2882                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2883                 guienv->drawAll();
2884                 driver->endScene();
2885                 gui_shuttingdowntext->remove();*/
2886         }
2887
2888         chat_backend.addMessage(L"", L"# Disconnected.");
2889         chat_backend.addMessage(L"", L"");
2890
2891         // Client scope (client is destructed before destructing *def and tsrc)
2892         }while(0);
2893         
2894         if(!sound_is_dummy)
2895                 delete sound;
2896         delete nodedef;
2897         delete itemdef;
2898         delete tsrc;
2899 }
2900
2901