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