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