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