utility.h: Change Buffer's interface to be more compatible with SharedBuffer's interf...
[oweals/minetest.git] / src / game.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "game.h"
21 #include "common_irrlicht.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
26 #include <IGUIFont.h>
27 #include "client.h"
28 #include "server.h"
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
34 #include "materials.h"
35 #include "config.h"
36 #include "clouds.h"
37 #include "camera.h"
38 #include "farmesh.h"
39 #include "mapblock.h"
40 #include "settings.h"
41 #include "profiler.h"
42 #include "mainmenumanager.h"
43 #include "gettext.h"
44 #include "log.h"
45 #include "filesys.h"
46
47 /*
48         TODO: Move content-aware stuff to separate file by adding properties
49               and virtual interfaces
50 */
51 #include "content_mapnode.h"
52 #include "content_nodemeta.h"
53
54 /*
55         Setting this to 1 enables a special camera mode that forces
56         the renderers to think that the camera statically points from
57         the starting place to a static direction.
58
59         This allows one to move around with the player and see what
60         is actually drawn behind solid things and behind the player.
61 */
62 #define FIELD_OF_VIEW_TEST 0
63
64
65 // Chat data
66 struct ChatLine
67 {
68         ChatLine():
69                 age(0.0)
70         {
71         }
72         ChatLine(const std::wstring &a_text):
73                 age(0.0),
74                 text(a_text)
75         {
76         }
77         float age;
78         std::wstring text;
79 };
80
81 /*
82         Inventory stuff
83 */
84
85 // Inventory actions from the menu are buffered here before sending
86 Queue<InventoryAction*> inventory_action_queue;
87 // This is a copy of the inventory that the client's environment has
88 Inventory local_inventory;
89
90 u16 g_selected_item = 0;
91
92 /*
93         Text input system
94 */
95
96 struct TextDestChat : public TextDest
97 {
98         TextDestChat(Client *client)
99         {
100                 m_client = client;
101         }
102         void gotText(std::wstring text)
103         {
104                 // Discard empty line
105                 if(text == L"")
106                         return;
107
108                 // Send to others
109                 m_client->sendChatMessage(text);
110                 // Show locally
111                 m_client->addChatMessage(text);
112         }
113
114         Client *m_client;
115 };
116
117 struct TextDestSignNode : public TextDest
118 {
119         TextDestSignNode(v3s16 p, Client *client)
120         {
121                 m_p = p;
122                 m_client = client;
123         }
124         void gotText(std::wstring text)
125         {
126                 std::string ntext = wide_to_narrow(text);
127                 infostream<<"Changing text of a sign node: "
128                                 <<ntext<<std::endl;
129                 m_client->sendSignNodeText(m_p, ntext);
130         }
131
132         v3s16 m_p;
133         Client *m_client;
134 };
135
136 /* Respawn menu callback */
137
138 class MainRespawnInitiator: public IRespawnInitiator
139 {
140 public:
141         MainRespawnInitiator(bool *active, Client *client):
142                 m_active(active), m_client(client)
143         {
144                 *m_active = true;
145         }
146         void respawn()
147         {
148                 *m_active = false;
149                 m_client->sendRespawn();
150         }
151 private:
152         bool *m_active;
153         Client *m_client;
154 };
155
156 /*
157         Hotbar draw routine
158 */
159 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
160                 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
161                 Inventory *inventory, s32 halfheartcount)
162 {
163         InventoryList *mainlist = inventory->getList("main");
164         if(mainlist == NULL)
165         {
166                 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
167                 return;
168         }
169         
170         s32 padding = imgsize/12;
171         //s32 height = imgsize + padding*2;
172         s32 width = itemcount*(imgsize+padding*2);
173         
174         // Position of upper left corner of bar
175         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
176         
177         // Draw background color
178         /*core::rect<s32> barrect(0,0,width,height);
179         barrect += pos;
180         video::SColor bgcolor(255,128,128,128);
181         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
182
183         core::rect<s32> imgrect(0,0,imgsize,imgsize);
184
185         for(s32 i=0; i<itemcount; i++)
186         {
187                 InventoryItem *item = mainlist->getItem(i);
188                 
189                 core::rect<s32> rect = imgrect + pos
190                                 + v2s32(padding+i*(imgsize+padding*2), padding);
191                 
192                 if(g_selected_item == i)
193                 {
194                         video::SColor c_outside(255,255,0,0);
195                         //video::SColor c_outside(255,0,0,0);
196                         //video::SColor c_inside(255,192,192,192);
197                         s32 x1 = rect.UpperLeftCorner.X;
198                         s32 y1 = rect.UpperLeftCorner.Y;
199                         s32 x2 = rect.LowerRightCorner.X;
200                         s32 y2 = rect.LowerRightCorner.Y;
201                         // Black base borders
202                         driver->draw2DRectangle(c_outside,
203                                         core::rect<s32>(
204                                                 v2s32(x1 - padding, y1 - padding),
205                                                 v2s32(x2 + padding, y1)
206                                         ), NULL);
207                         driver->draw2DRectangle(c_outside,
208                                         core::rect<s32>(
209                                                 v2s32(x1 - padding, y2),
210                                                 v2s32(x2 + padding, y2 + padding)
211                                         ), NULL);
212                         driver->draw2DRectangle(c_outside,
213                                         core::rect<s32>(
214                                                 v2s32(x1 - padding, y1),
215                                                 v2s32(x1, y2)
216                                         ), NULL);
217                         driver->draw2DRectangle(c_outside,
218                                         core::rect<s32>(
219                                                 v2s32(x2, y1),
220                                                 v2s32(x2 + padding, y2)
221                                         ), NULL);
222                         /*// Light inside borders
223                         driver->draw2DRectangle(c_inside,
224                                         core::rect<s32>(
225                                                 v2s32(x1 - padding/2, y1 - padding/2),
226                                                 v2s32(x2 + padding/2, y1)
227                                         ), NULL);
228                         driver->draw2DRectangle(c_inside,
229                                         core::rect<s32>(
230                                                 v2s32(x1 - padding/2, y2),
231                                                 v2s32(x2 + padding/2, y2 + padding/2)
232                                         ), NULL);
233                         driver->draw2DRectangle(c_inside,
234                                         core::rect<s32>(
235                                                 v2s32(x1 - padding/2, y1),
236                                                 v2s32(x1, y2)
237                                         ), NULL);
238                         driver->draw2DRectangle(c_inside,
239                                         core::rect<s32>(
240                                                 v2s32(x2, y1),
241                                                 v2s32(x2 + padding/2, y2)
242                                         ), NULL);
243                         */
244                 }
245
246                 video::SColor bgcolor2(128,0,0,0);
247                 driver->draw2DRectangle(bgcolor2, rect, NULL);
248
249                 if(item != NULL)
250                 {
251                         drawInventoryItem(driver, font, item, rect, NULL);
252                 }
253         }
254         
255         /*
256                 Draw hearts
257         */
258         {
259                 video::ITexture *heart_texture =
260                                 driver->getTexture(getTexturePath("heart.png").c_str());
261                 v2s32 p = pos + v2s32(0, -20);
262                 for(s32 i=0; i<halfheartcount/2; i++)
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,16);
267                         rect += p;
268                         driver->draw2DImage(heart_texture, rect,
269                                 core::rect<s32>(core::position2d<s32>(0,0),
270                                 core::dimension2di(heart_texture->getOriginalSize())),
271                                 NULL, colors, true);
272                         p += v2s32(16,0);
273                 }
274                 if(halfheartcount % 2 == 1)
275                 {
276                         const video::SColor color(255,255,255,255);
277                         const video::SColor colors[] = {color,color,color,color};
278                         core::rect<s32> rect(0,0,16/2,16);
279                         rect += p;
280                         core::dimension2di srcd(heart_texture->getOriginalSize());
281                         srcd.Width /= 2;
282                         driver->draw2DImage(heart_texture, rect,
283                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
284                                 NULL, colors, true);
285                         p += v2s32(16,0);
286                 }
287         }
288 }
289
290 /*
291         Find what the player is pointing at
292 */
293 void getPointedNode(Client *client, v3f player_position,
294                 v3f camera_direction, v3f camera_position,
295                 bool &nodefound, core::line3d<f32> shootline,
296                 v3s16 &nodepos, v3s16 &neighbourpos,
297                 core::aabbox3d<f32> &nodehilightbox,
298                 f32 d)
299 {
300         f32 mindistance = BS * 1001;
301         
302         v3s16 pos_i = floatToInt(player_position, BS);
303
304         /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
305                         <<std::endl;*/
306
307         s16 a = d;
308         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
309         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
310         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
311         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
312         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
313         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
314         
315         for(s16 y = ystart; y <= yend; y++)
316         for(s16 z = zstart; z <= zend; z++)
317         for(s16 x = xstart; x <= xend; x++)
318         {
319                 MapNode n;
320                 try
321                 {
322                         n = client->getNode(v3s16(x,y,z));
323                         if(content_pointable(n.getContent()) == false)
324                                 continue;
325                 }
326                 catch(InvalidPositionException &e)
327                 {
328                         continue;
329                 }
330
331                 v3s16 np(x,y,z);
332                 v3f npf = intToFloat(np, BS);
333                 
334                 f32 d = 0.01;
335                 
336                 v3s16 dirs[6] = {
337                         v3s16(0,0,1), // back
338                         v3s16(0,1,0), // top
339                         v3s16(1,0,0), // right
340                         v3s16(0,0,-1), // front
341                         v3s16(0,-1,0), // bottom
342                         v3s16(-1,0,0), // left
343                 };
344                 
345                 /*
346                         Meta-objects
347                 */
348                 if(n.getContent() == CONTENT_TORCH)
349                 {
350                         v3s16 dir = unpackDir(n.param2);
351                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
352                         dir_f *= BS/2 - BS/6 - BS/20;
353                         v3f cpf = npf + dir_f;
354                         f32 distance = (cpf - camera_position).getLength();
355
356                         core::aabbox3d<f32> box;
357                         
358                         // bottom
359                         if(dir == v3s16(0,-1,0))
360                         {
361                                 box = core::aabbox3d<f32>(
362                                         npf - v3f(BS/6, BS/2, BS/6),
363                                         npf + v3f(BS/6, -BS/2+BS/3*2, BS/6)
364                                 );
365                         }
366                         // top
367                         else if(dir == v3s16(0,1,0))
368                         {
369                                 box = core::aabbox3d<f32>(
370                                         npf - v3f(BS/6, -BS/2+BS/3*2, BS/6),
371                                         npf + v3f(BS/6, BS/2, BS/6)
372                                 );
373                         }
374                         // side
375                         else
376                         {
377                                 box = core::aabbox3d<f32>(
378                                         cpf - v3f(BS/6, BS/3, BS/6),
379                                         cpf + v3f(BS/6, BS/3, BS/6)
380                                 );
381                         }
382
383                         if(distance < mindistance)
384                         {
385                                 if(box.intersectsWithLine(shootline))
386                                 {
387                                         nodefound = true;
388                                         nodepos = np;
389                                         neighbourpos = np;
390                                         mindistance = distance;
391                                         nodehilightbox = box;
392                                 }
393                         }
394                 }
395                 else if(n.getContent() == CONTENT_SIGN_WALL)
396                 {
397                         v3s16 dir = unpackDir(n.param2);
398                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
399                         dir_f *= BS/2 - BS/6 - BS/20;
400                         v3f cpf = npf + dir_f;
401                         f32 distance = (cpf - camera_position).getLength();
402
403                         v3f vertices[4] =
404                         {
405                                 v3f(BS*0.42,-BS*0.35,-BS*0.4),
406                                 v3f(BS*0.49, BS*0.35, BS*0.4),
407                         };
408
409                         for(s32 i=0; i<2; i++)
410                         {
411                                 if(dir == v3s16(1,0,0))
412                                         vertices[i].rotateXZBy(0);
413                                 if(dir == v3s16(-1,0,0))
414                                         vertices[i].rotateXZBy(180);
415                                 if(dir == v3s16(0,0,1))
416                                         vertices[i].rotateXZBy(90);
417                                 if(dir == v3s16(0,0,-1))
418                                         vertices[i].rotateXZBy(-90);
419                                 if(dir == v3s16(0,-1,0))
420                                         vertices[i].rotateXYBy(-90);
421                                 if(dir == v3s16(0,1,0))
422                                         vertices[i].rotateXYBy(90);
423
424                                 vertices[i] += npf;
425                         }
426
427                         core::aabbox3d<f32> box;
428
429                         box = core::aabbox3d<f32>(vertices[0]);
430                         box.addInternalPoint(vertices[1]);
431
432                         if(distance < mindistance)
433                         {
434                                 if(box.intersectsWithLine(shootline))
435                                 {
436                                         nodefound = true;
437                                         nodepos = np;
438                                         neighbourpos = np;
439                                         mindistance = distance;
440                                         nodehilightbox = box;
441                                 }
442                         }
443                 }
444
445                 else if(n.getContent() == CONTENT_LADDER)
446                 {
447                         v3s16 dir = unpackDir(n.param2);
448                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
449                         dir_f *= BS/2 - BS/6 - BS/20;
450                         v3f cpf = npf + dir_f;
451                         f32 distance = (cpf - camera_position).getLength();
452
453                         v3f vertices[4] =
454                         {
455                                 v3f(BS*0.42,-BS/2,-BS/2),
456                                 v3f(BS*0.49, BS/2, BS/2),
457                         };
458
459                         for(s32 i=0; i<2; i++)
460                         {
461                                 if(dir == v3s16(1,0,0))
462                                         vertices[i].rotateXZBy(0);
463                                 if(dir == v3s16(-1,0,0))
464                                         vertices[i].rotateXZBy(180);
465                                 if(dir == v3s16(0,0,1))
466                                         vertices[i].rotateXZBy(90);
467                                 if(dir == v3s16(0,0,-1))
468                                         vertices[i].rotateXZBy(-90);
469                                 if(dir == v3s16(0,-1,0))
470                                         vertices[i].rotateXYBy(-90);
471                                 if(dir == v3s16(0,1,0))
472                                         vertices[i].rotateXYBy(90);
473
474                                 vertices[i] += npf;
475                         }
476
477                         core::aabbox3d<f32> box;
478
479                         box = core::aabbox3d<f32>(vertices[0]);
480                         box.addInternalPoint(vertices[1]);
481
482                         if(distance < mindistance)
483                         {
484                                 if(box.intersectsWithLine(shootline))
485                                 {
486                                         nodefound = true;
487                                         nodepos = np;
488                                         neighbourpos = np;
489                                         mindistance = distance;
490                                         nodehilightbox = box;
491                                 }
492                         }
493                 }
494                 else if(n.getContent() == CONTENT_RAIL)
495                 {
496                         v3s16 dir = unpackDir(n.param0);
497                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
498                         dir_f *= BS/2 - BS/6 - BS/20;
499                         v3f cpf = npf + dir_f;
500                         f32 distance = (cpf - camera_position).getLength();
501
502                         float d = (float)BS/16;
503                         v3f vertices[4] =
504                         {
505                                 v3f(BS/2, -BS/2+d, -BS/2),
506                                 v3f(-BS/2, -BS/2, BS/2),
507                         };
508
509                         for(s32 i=0; i<2; i++)
510                         {
511                                 vertices[i] += npf;
512                         }
513
514                         core::aabbox3d<f32> box;
515
516                         box = core::aabbox3d<f32>(vertices[0]);
517                         box.addInternalPoint(vertices[1]);
518
519                         if(distance < mindistance)
520                         {
521                                 if(box.intersectsWithLine(shootline))
522                                 {
523                                         nodefound = true;
524                                         nodepos = np;
525                                         neighbourpos = np;
526                                         mindistance = distance;
527                                         nodehilightbox = box;
528                                 }
529                         }
530                 }
531                 /*
532                         Regular blocks
533                 */
534                 else
535                 {
536                         for(u16 i=0; i<6; i++)
537                         {
538                                 v3f dir_f = v3f(dirs[i].X,
539                                                 dirs[i].Y, dirs[i].Z);
540                                 v3f centerpoint = npf + dir_f * BS/2;
541                                 f32 distance =
542                                                 (centerpoint - camera_position).getLength();
543                                 
544                                 if(distance < mindistance)
545                                 {
546                                         core::CMatrix4<f32> m;
547                                         m.buildRotateFromTo(v3f(0,0,1), dir_f);
548
549                                         // This is the back face
550                                         v3f corners[2] = {
551                                                 v3f(BS/2, BS/2, BS/2),
552                                                 v3f(-BS/2, -BS/2, BS/2+d)
553                                         };
554                                         
555                                         for(u16 j=0; j<2; j++)
556                                         {
557                                                 m.rotateVect(corners[j]);
558                                                 corners[j] += npf;
559                                         }
560
561                                         core::aabbox3d<f32> facebox(corners[0]);
562                                         facebox.addInternalPoint(corners[1]);
563
564                                         if(facebox.intersectsWithLine(shootline))
565                                         {
566                                                 nodefound = true;
567                                                 nodepos = np;
568                                                 neighbourpos = np + dirs[i];
569                                                 mindistance = distance;
570
571                                                 //nodehilightbox = facebox;
572
573                                                 const float d = 0.502;
574                                                 core::aabbox3d<f32> nodebox
575                                                                 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
576                                                 v3f nodepos_f = intToFloat(nodepos, BS);
577                                                 nodebox.MinEdge += nodepos_f;
578                                                 nodebox.MaxEdge += nodepos_f;
579                                                 nodehilightbox = nodebox;
580                                         }
581                                 } // if distance < mindistance
582                         } // for dirs
583                 } // regular block
584         } // for coords
585 }
586
587 void update_skybox(video::IVideoDriver* driver,
588                 scene::ISceneManager* smgr, scene::ISceneNode* &skybox,
589                 float brightness)
590 {
591         if(skybox)
592         {
593                 skybox->remove();
594         }
595         
596         /*// Disable skybox if FarMesh is enabled
597         if(g_settings->getBool("enable_farmesh"))
598                 return;*/
599         
600         if(brightness >= 0.5)
601         {
602                 skybox = smgr->addSkyBoxSceneNode(
603                         driver->getTexture(getTexturePath("skybox2.png").c_str()),
604                         driver->getTexture(getTexturePath("skybox3.png").c_str()),
605                         driver->getTexture(getTexturePath("skybox1.png").c_str()),
606                         driver->getTexture(getTexturePath("skybox1.png").c_str()),
607                         driver->getTexture(getTexturePath("skybox1.png").c_str()),
608                         driver->getTexture(getTexturePath("skybox1.png").c_str()));
609         }
610         else if(brightness >= 0.2)
611         {
612                 skybox = smgr->addSkyBoxSceneNode(
613                         driver->getTexture(getTexturePath("skybox2_dawn.png").c_str()),
614                         driver->getTexture(getTexturePath("skybox3_dawn.png").c_str()),
615                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()),
616                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()),
617                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()),
618                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()));
619         }
620         else
621         {
622                 skybox = smgr->addSkyBoxSceneNode(
623                         driver->getTexture(getTexturePath("skybox2_night.png").c_str()),
624                         driver->getTexture(getTexturePath("skybox3_night.png").c_str()),
625                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()),
626                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()),
627                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()),
628                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()));
629         }
630 }
631
632 /*
633         Draws a screen with a single text on it.
634         Text will be removed when the screen is drawn the next time.
635 */
636 /*gui::IGUIStaticText **/
637 void draw_load_screen(const std::wstring &text,
638                 video::IVideoDriver* driver, gui::IGUIFont* font)
639 {
640         v2u32 screensize = driver->getScreenSize();
641         const wchar_t *loadingtext = text.c_str();
642         core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
643         core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
644         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
645         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
646
647         gui::IGUIStaticText *guitext = guienv->addStaticText(
648                         loadingtext, textrect, false, false);
649         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
650
651         driver->beginScene(true, true, video::SColor(255,0,0,0));
652         guienv->drawAll();
653         driver->endScene();
654         
655         guitext->remove();
656         
657         //return guitext;
658 }
659
660 void the_game(
661         bool &kill,
662         bool random_input,
663         InputHandler *input,
664         IrrlichtDevice *device,
665         gui::IGUIFont* font,
666         std::string map_dir,
667         std::string playername,
668         std::string password,
669         std::string address,
670         u16 port,
671         std::wstring &error_message,
672     std::string configpath
673 )
674 {
675         video::IVideoDriver* driver = device->getVideoDriver();
676         scene::ISceneManager* smgr = device->getSceneManager();
677         
678         // Calculate text height using the font
679         u32 text_height = font->getDimension(L"Random test string").Height;
680
681         v2u32 screensize(0,0);
682         v2u32 last_screensize(0,0);
683         screensize = driver->getScreenSize();
684
685         const s32 hotbar_itemcount = 8;
686         //const s32 hotbar_imagesize = 36;
687         //const s32 hotbar_imagesize = 64;
688         s32 hotbar_imagesize = 48;
689         
690         // The color of the sky
691
692         //video::SColor skycolor = video::SColor(255,140,186,250);
693
694         video::SColor bgcolor_bright = video::SColor(255,170,200,230);
695
696         /*
697                 Draw "Loading" screen
698         */
699         /*gui::IGUIStaticText *gui_loadingtext = */
700         //draw_load_screen(L"Loading and connecting...", driver, font);
701
702         draw_load_screen(L"Loading...", driver, font);
703         
704         /*
705                 Create server.
706                 SharedPtr will delete it when it goes out of scope.
707         */
708         SharedPtr<Server> server;
709         if(address == ""){
710                 draw_load_screen(L"Creating server...", driver, font);
711                 infostream<<"Creating server"<<std::endl;
712                 server = new Server(map_dir, configpath);
713                 server->start(port);
714         }
715         
716         /*
717                 Create client
718         */
719
720         draw_load_screen(L"Creating client...", driver, font);
721         infostream<<"Creating client"<<std::endl;
722         MapDrawControl draw_control;
723         Client client(device, playername.c_str(), password, draw_control);
724                         
725         draw_load_screen(L"Resolving address...", driver, font);
726         Address connect_address(0,0,0,0, port);
727         try{
728                 if(address == "")
729                         //connect_address.Resolve("localhost");
730                         connect_address.setAddress(127,0,0,1);
731                 else
732                         connect_address.Resolve(address.c_str());
733         }
734         catch(ResolveError &e)
735         {
736                 errorstream<<"Couldn't resolve address"<<std::endl;
737                 //return 0;
738                 error_message = L"Couldn't resolve address";
739                 //gui_loadingtext->remove();
740                 return;
741         }
742
743         /*
744                 Attempt to connect to the server
745         */
746         
747         infostream<<"Connecting to server at ";
748         connect_address.print(&infostream);
749         infostream<<std::endl;
750         client.connect(connect_address);
751
752         bool could_connect = false;
753         
754         try{
755                 float time_counter = 0.0;
756                 for(;;)
757                 {
758                         if(client.connectedAndInitialized())
759                         {
760                                 could_connect = true;
761                                 break;
762                         }
763                         if(client.accessDenied())
764                         {
765                                 break;
766                         }
767                         // Wait for 10 seconds
768                         if(time_counter >= 10.0)
769                         {
770                                 break;
771                         }
772                         
773                         std::wostringstream ss;
774                         ss<<L"Connecting to server... (timeout in ";
775                         ss<<(int)(10.0 - time_counter + 1.0);
776                         ss<<L" seconds)";
777                         draw_load_screen(ss.str(), driver, font);
778
779                         /*// Update screen
780                         driver->beginScene(true, true, video::SColor(255,0,0,0));
781                         guienv->drawAll();
782                         driver->endScene();*/
783
784                         // Update client and server
785
786                         client.step(0.1);
787
788                         if(server != NULL)
789                                 server->step(0.1);
790                         
791                         // Delay a bit
792                         sleep_ms(100);
793                         time_counter += 0.1;
794                 }
795         }
796         catch(con::PeerNotFoundException &e)
797         {}
798
799         if(could_connect == false)
800         {
801                 if(client.accessDenied())
802                 {
803                         error_message = L"Access denied. Reason: "
804                                         +client.accessDeniedReason();
805                         errorstream<<wide_to_narrow(error_message)<<std::endl;
806                 }
807                 else
808                 {
809                         error_message = L"Connection timed out.";
810                         errorstream<<"Timed out."<<std::endl;
811                 }
812                 //gui_loadingtext->remove();
813                 return;
814         }
815
816         /*
817                 Create skybox
818         */
819         float old_brightness = 1.0;
820         scene::ISceneNode* skybox = NULL;
821         update_skybox(driver, smgr, skybox, 1.0);
822         
823         /*
824                 Create the camera node
825         */
826         Camera camera(smgr, draw_control);
827         if (!camera.successfullyCreated(error_message))
828                 return;
829
830         f32 camera_yaw = 0; // "right/left"
831         f32 camera_pitch = 0; // "up/down"
832
833         /*
834                 Clouds
835         */
836         
837         float cloud_height = BS*100;
838         Clouds *clouds = NULL;
839         if(g_settings->getBool("enable_clouds"))
840         {
841                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
842                                 cloud_height, time(0));
843         }
844         
845         /*
846                 FarMesh
847         */
848
849         FarMesh *farmesh = NULL;
850         if(g_settings->getBool("enable_farmesh"))
851         {
852                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
853         }
854
855         /*
856                 Move into game
857         */
858         
859         //gui_loadingtext->remove();
860
861         /*
862                 Add some gui stuff
863         */
864
865         // First line of debug text
866         gui::IGUIStaticText *guitext = guienv->addStaticText(
867                         L"Minetest-c55",
868                         core::rect<s32>(5, 5, 795, 5+text_height),
869                         false, false);
870         // Second line of debug text
871         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
872                         L"",
873                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
874                         false, false);
875         // At the middle of the screen
876         // Object infos are shown in this
877         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
878                         L"",
879                         core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
880                         false, false);
881         
882         // Chat text
883         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
884                         L"",
885                         core::rect<s32>(0,0,0,0),
886                         //false, false); // Disable word wrap as of now
887                         false, true);
888         //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
889         core::list<ChatLine> chat_lines;
890         
891         // Profiler text (size is updated when text is updated)
892         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
893                         L"<Profiler>",
894                         core::rect<s32>(6, 4+(text_height+5)*2, 400,
895                         (text_height+5)*2 + text_height*35),
896                         false, false);
897         guitext_profiler->setBackgroundColor(video::SColor(80,0,0,0));
898         guitext_profiler->setVisible(false);
899         
900         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
901                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
902         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
903                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
904         
905         // Test the text input system
906         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
907                         NULL))->drop();*/
908         /*GUIMessageMenu *menu =
909                         new GUIMessageMenu(guienv, guiroot, -1, 
910                                 &g_menumgr,
911                                 L"Asd");
912         menu->drop();*/
913         
914         // Launch pause menu
915         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
916                         &g_menumgr))->drop();
917         
918         // Enable texts
919         /*guitext2->setVisible(true);
920         guitext_info->setVisible(true);
921         guitext_chat->setVisible(true);*/
922
923         //s32 guitext_chat_pad_bottom = 70;
924
925         /*
926                 Some statistics are collected in these
927         */
928         u32 drawtime = 0;
929         u32 beginscenetime = 0;
930         u32 scenetime = 0;
931         u32 endscenetime = 0;
932         
933         // A test
934         //throw con::PeerNotFoundException("lol");
935
936         core::list<float> frametime_log;
937
938         float nodig_delay_counter = 0.0;
939         float dig_time = 0.0;
940         u16 dig_index = 0;
941         v3s16 nodepos_old(-32768,-32768,-32768);
942
943         float damage_flash_timer = 0;
944         s16 farmesh_range = 20*MAP_BLOCKSIZE;
945
946         const float object_hit_delay = 0.5;
947         float object_hit_delay_timer = 0.0;
948         
949         bool invert_mouse = g_settings->getBool("invert_mouse");
950
951         bool respawn_menu_active = false;
952
953         bool show_profiler = false;
954         bool force_fog_off = false;
955         bool disable_camera_update = false;
956
957         /*
958                 Main loop
959         */
960
961         bool first_loop_after_window_activation = true;
962
963         // TODO: Convert the static interval timers to these
964         // Interval limiter for profiler
965         IntervalLimiter m_profiler_interval;
966
967         // Time is in milliseconds
968         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
969         // NOTE: So we have to use getTime() and call run()s between them
970         u32 lasttime = device->getTimer()->getTime();
971
972         while(device->run() && kill == false)
973         {
974                 //std::cerr<<"frame"<<std::endl;
975
976                 if(client.accessDenied())
977                 {
978                         error_message = L"Access denied. Reason: "
979                                         +client.accessDeniedReason();
980                         errorstream<<wide_to_narrow(error_message)<<std::endl;
981                         break;
982                 }
983
984                 if(g_gamecallback->disconnect_requested)
985                 {
986                         g_gamecallback->disconnect_requested = false;
987                         break;
988                 }
989
990                 if(g_gamecallback->changepassword_requested)
991                 {
992                         (new GUIPasswordChange(guienv, guiroot, -1,
993                                 &g_menumgr, &client))->drop();
994                         g_gamecallback->changepassword_requested = false;
995                 }
996
997                 /*
998                         Process TextureSource's queue
999                 */
1000                 ((TextureSource*)g_texturesource)->processQueue();
1001
1002                 /*
1003                         Random calculations
1004                 */
1005                 last_screensize = screensize;
1006                 screensize = driver->getScreenSize();
1007                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1008                 //bool screensize_changed = screensize != last_screensize;
1009
1010                 // Resize hotbar
1011                 if(screensize.Y <= 800)
1012                         hotbar_imagesize = 32;
1013                 else if(screensize.Y <= 1280)
1014                         hotbar_imagesize = 48;
1015                 else
1016                         hotbar_imagesize = 64;
1017                 
1018                 // Hilight boxes collected during the loop and displayed
1019                 core::list< core::aabbox3d<f32> > hilightboxes;
1020                 
1021                 // Info text
1022                 std::wstring infotext;
1023
1024                 // When screen size changes, update positions and sizes of stuff
1025                 /*if(screensize_changed)
1026                 {
1027                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
1028                         quick_inventory->updatePosition(pos);
1029                 }*/
1030
1031                 //TimeTaker //timer1("//timer1");
1032                 
1033                 // Time of frame without fps limit
1034                 float busytime;
1035                 u32 busytime_u32;
1036                 {
1037                         // not using getRealTime is necessary for wine
1038                         u32 time = device->getTimer()->getTime();
1039                         if(time > lasttime)
1040                                 busytime_u32 = time - lasttime;
1041                         else
1042                                 busytime_u32 = 0;
1043                         busytime = busytime_u32 / 1000.0;
1044                 }
1045
1046                 //infostream<<"busytime_u32="<<busytime_u32<<std::endl;
1047         
1048                 // Necessary for device->getTimer()->getTime()
1049                 device->run();
1050
1051                 /*
1052                         FPS limiter
1053                 */
1054
1055                 {
1056                         float fps_max = g_settings->getFloat("fps_max");
1057                         u32 frametime_min = 1000./fps_max;
1058                         
1059                         if(busytime_u32 < frametime_min)
1060                         {
1061                                 u32 sleeptime = frametime_min - busytime_u32;
1062                                 device->sleep(sleeptime);
1063                         }
1064                 }
1065
1066                 // Necessary for device->getTimer()->getTime()
1067                 device->run();
1068
1069                 /*
1070                         Time difference calculation
1071                 */
1072                 f32 dtime; // in seconds
1073                 
1074                 u32 time = device->getTimer()->getTime();
1075                 if(time > lasttime)
1076                         dtime = (time - lasttime) / 1000.0;
1077                 else
1078                         dtime = 0;
1079                 lasttime = time;
1080
1081                 /* Run timers */
1082
1083                 object_hit_delay_timer -= dtime;
1084
1085                 g_profiler->add("Elapsed time", dtime);
1086                 g_profiler->avg("FPS", 1./dtime);
1087
1088                 /*
1089                         Log frametime for visualization
1090                 */
1091                 frametime_log.push_back(dtime);
1092                 if(frametime_log.size() > 100)
1093                 {
1094                         core::list<float>::Iterator i = frametime_log.begin();
1095                         frametime_log.erase(i);
1096                 }
1097
1098                 /*
1099                         Visualize frametime in terminal
1100                 */
1101                 /*for(u32 i=0; i<dtime*400; i++)
1102                         infostream<<"X";
1103                 infostream<<std::endl;*/
1104
1105                 /*
1106                         Time average and jitter calculation
1107                 */
1108
1109                 static f32 dtime_avg1 = 0.0;
1110                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1111                 f32 dtime_jitter1 = dtime - dtime_avg1;
1112
1113                 static f32 dtime_jitter1_max_sample = 0.0;
1114                 static f32 dtime_jitter1_max_fraction = 0.0;
1115                 {
1116                         static f32 jitter1_max = 0.0;
1117                         static f32 counter = 0.0;
1118                         if(dtime_jitter1 > jitter1_max)
1119                                 jitter1_max = dtime_jitter1;
1120                         counter += dtime;
1121                         if(counter > 0.0)
1122                         {
1123                                 counter -= 3.0;
1124                                 dtime_jitter1_max_sample = jitter1_max;
1125                                 dtime_jitter1_max_fraction
1126                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1127                                 jitter1_max = 0.0;
1128                         }
1129                 }
1130                 
1131                 /*
1132                         Busytime average and jitter calculation
1133                 */
1134
1135                 static f32 busytime_avg1 = 0.0;
1136                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1137                 f32 busytime_jitter1 = busytime - busytime_avg1;
1138                 
1139                 static f32 busytime_jitter1_max_sample = 0.0;
1140                 static f32 busytime_jitter1_min_sample = 0.0;
1141                 {
1142                         static f32 jitter1_max = 0.0;
1143                         static f32 jitter1_min = 0.0;
1144                         static f32 counter = 0.0;
1145                         if(busytime_jitter1 > jitter1_max)
1146                                 jitter1_max = busytime_jitter1;
1147                         if(busytime_jitter1 < jitter1_min)
1148                                 jitter1_min = busytime_jitter1;
1149                         counter += dtime;
1150                         if(counter > 0.0){
1151                                 counter -= 3.0;
1152                                 busytime_jitter1_max_sample = jitter1_max;
1153                                 busytime_jitter1_min_sample = jitter1_min;
1154                                 jitter1_max = 0.0;
1155                                 jitter1_min = 0.0;
1156                         }
1157                 }
1158                 
1159                 /*
1160                         Debug info for client
1161                 */
1162                 {
1163                         static float counter = 0.0;
1164                         counter -= dtime;
1165                         if(counter < 0)
1166                         {
1167                                 counter = 30.0;
1168                                 client.printDebugInfo(infostream);
1169                         }
1170                 }
1171
1172                 /*
1173                         Profiler
1174                 */
1175                 float profiler_print_interval =
1176                                 g_settings->getFloat("profiler_print_interval");
1177                 bool print_to_log = true;
1178                 if(profiler_print_interval == 0){
1179                         print_to_log = false;
1180                         profiler_print_interval = 5;
1181                 }
1182                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1183                 {
1184                         if(print_to_log){
1185                                 infostream<<"Profiler:"<<std::endl;
1186                                 g_profiler->print(infostream);
1187                         }
1188
1189                         std::ostringstream os(std::ios_base::binary);
1190                         g_profiler->print(os);
1191                         std::wstring text = narrow_to_wide(os.str());
1192                         guitext_profiler->setText(text.c_str());
1193
1194                         g_profiler->clear();
1195                         
1196                         s32 w = font->getDimension(text.c_str()).Width;
1197                         if(w < 400)
1198                                 w = 400;
1199                         core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
1200                                         8+(text_height+5)*2 +
1201                                         font->getDimension(text.c_str()).Height);
1202                         guitext_profiler->setRelativePosition(rect);
1203                 }
1204
1205                 /*
1206                         Direct handling of user input
1207                 */
1208                 
1209                 // Reset input if window not active or some menu is active
1210                 if(device->isWindowActive() == false || noMenuActive() == false)
1211                 {
1212                         input->clear();
1213                 }
1214
1215                 // Input handler step() (used by the random input generator)
1216                 input->step(dtime);
1217
1218                 /*
1219                         Launch menus according to keys
1220                 */
1221                 if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1222                 {
1223                         infostream<<"the_game: "
1224                                         <<"Launching inventory"<<std::endl;
1225                         
1226                         GUIInventoryMenu *menu =
1227                                 new GUIInventoryMenu(guienv, guiroot, -1,
1228                                         &g_menumgr, v2s16(8,7),
1229                                         client.getInventoryContext(),
1230                                         &client);
1231
1232                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1233                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1234                                         "list", "current_player", "main",
1235                                         v2s32(0, 3), v2s32(8, 4)));
1236                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1237                                         "list", "current_player", "craft",
1238                                         v2s32(3, 0), v2s32(3, 3)));
1239                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1240                                         "list", "current_player", "craftresult",
1241                                         v2s32(7, 1), v2s32(1, 1)));
1242
1243                         menu->setDrawSpec(draw_spec);
1244
1245                         menu->drop();
1246                 }
1247                 else if(input->wasKeyDown(EscapeKey))
1248                 {
1249                         infostream<<"the_game: "
1250                                         <<"Launching pause menu"<<std::endl;
1251                         // It will delete itself by itself
1252                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1253                                         &g_menumgr))->drop();
1254
1255                         // Move mouse cursor on top of the disconnect button
1256                         input->setMousePos(displaycenter.X, displaycenter.Y+25);
1257                 }
1258                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1259                 {
1260                         TextDest *dest = new TextDestChat(&client);
1261
1262                         (new GUITextInputMenu(guienv, guiroot, -1,
1263                                         &g_menumgr, dest,
1264                                         L""))->drop();
1265                 }
1266                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1267                 {
1268                         TextDest *dest = new TextDestChat(&client);
1269
1270                         (new GUITextInputMenu(guienv, guiroot, -1,
1271                                         &g_menumgr, dest,
1272                                         L"/"))->drop();
1273                 }
1274                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1275                 {
1276                         if(g_settings->getBool("free_move"))
1277                         {
1278                                 g_settings->set("free_move","false");
1279                                 chat_lines.push_back(ChatLine(L"free_move disabled"));
1280                         }
1281                         else
1282                         {
1283                                 g_settings->set("free_move","true");
1284                                 chat_lines.push_back(ChatLine(L"free_move enabled"));
1285                         }
1286                 }
1287                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1288                 {
1289                         if(g_settings->getBool("fast_move"))
1290                         {
1291                                 g_settings->set("fast_move","false");
1292                                 chat_lines.push_back(ChatLine(L"fast_move disabled"));
1293                         }
1294                         else
1295                         {
1296                                 g_settings->set("fast_move","true");
1297                                 chat_lines.push_back(ChatLine(L"fast_move enabled"));
1298                         }
1299                 }
1300                 else if(input->wasKeyDown(getKeySetting("keymap_frametime_graph")))
1301                 {
1302                         if(g_settings->getBool("frametime_graph"))
1303                         {
1304                                 g_settings->set("frametime_graph","false");
1305                                 chat_lines.push_back(ChatLine(L"frametime_graph disabled"));
1306                         }
1307                         else
1308                         {
1309                                 g_settings->set("frametime_graph","true");
1310                                 chat_lines.push_back(ChatLine(L"frametime_graph enabled"));
1311                         }
1312                 }
1313                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1314                 {
1315                         irr::video::IImage* const image = driver->createScreenShot(); 
1316                         if (image) { 
1317                                 irr::c8 filename[256]; 
1318                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1319                                                  g_settings->get("screenshot_path").c_str(),
1320                                                  device->getTimer()->getRealTime()); 
1321                                 if (driver->writeImageToFile(image, filename)) {
1322                                         std::wstringstream sstr;
1323                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1324                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1325                                         chat_lines.push_back(ChatLine(sstr.str()));
1326                                 } else{
1327                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1328                                 }
1329                                 image->drop(); 
1330                         }                        
1331                 }
1332                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1333                 {
1334                         show_profiler = !show_profiler;
1335                         guitext_profiler->setVisible(show_profiler);
1336                         if(show_profiler)
1337                                 chat_lines.push_back(ChatLine(L"Profiler disabled"));
1338                         else
1339                                 chat_lines.push_back(ChatLine(L"Profiler enabled"));
1340                 }
1341                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1342                 {
1343                         force_fog_off = !force_fog_off;
1344                         if(force_fog_off)
1345                                 chat_lines.push_back(ChatLine(L"Fog disabled"));
1346                         else
1347                                 chat_lines.push_back(ChatLine(L"Fog enabled"));
1348                 }
1349                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1350                 {
1351                         disable_camera_update = !disable_camera_update;
1352                         if(disable_camera_update)
1353                                 chat_lines.push_back(ChatLine(L"Camera update disabled"));
1354                         else
1355                                 chat_lines.push_back(ChatLine(L"Camera update enabled"));
1356                 }
1357
1358                 // Item selection with mouse wheel
1359                 {
1360                         s32 wheel = input->getMouseWheel();
1361                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1362                                         hotbar_itemcount-1);
1363
1364                         if(wheel < 0)
1365                         {
1366                                 if(g_selected_item < max_item)
1367                                         g_selected_item++;
1368                                 else
1369                                         g_selected_item = 0;
1370                         }
1371                         else if(wheel > 0)
1372                         {
1373                                 if(g_selected_item > 0)
1374                                         g_selected_item--;
1375                                 else
1376                                         g_selected_item = max_item;
1377                         }
1378                 }
1379                 
1380                 // Item selection
1381                 for(u16 i=0; i<10; i++)
1382                 {
1383                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1384                         if(input->wasKeyDown(*kp))
1385                         {
1386                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1387                                 {
1388                                         g_selected_item = i;
1389
1390                                         infostream<<"Selected item: "
1391                                                         <<g_selected_item<<std::endl;
1392                                 }
1393                         }
1394                 }
1395
1396                 // Viewing range selection
1397                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1398                 {
1399                         if(draw_control.range_all)
1400                         {
1401                                 draw_control.range_all = false;
1402                                 infostream<<"Disabled full viewing range"<<std::endl;
1403                         }
1404                         else
1405                         {
1406                                 draw_control.range_all = true;
1407                                 infostream<<"Enabled full viewing range"<<std::endl;
1408                         }
1409                 }
1410
1411                 // Print debug stacks
1412                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1413                 {
1414                         dstream<<"-----------------------------------------"
1415                                         <<std::endl;
1416                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1417                         dstream<<"-----------------------------------------"
1418                                         <<std::endl;
1419                         debug_stacks_print();
1420                 }
1421
1422                 /*
1423                         Mouse and camera control
1424                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1425                 */
1426                 
1427                 if((device->isWindowActive() && noMenuActive()) || random_input)
1428                 {
1429                         if(!random_input)
1430                         {
1431                                 // Mac OSX gets upset if this is set every frame
1432                                 if(device->getCursorControl()->isVisible())
1433                                         device->getCursorControl()->setVisible(false);
1434                         }
1435
1436                         if(first_loop_after_window_activation){
1437                                 //infostream<<"window active, first loop"<<std::endl;
1438                                 first_loop_after_window_activation = false;
1439                         }
1440                         else{
1441                                 s32 dx = input->getMousePos().X - displaycenter.X;
1442                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1443                                 if(invert_mouse)
1444                                         dy = -dy;
1445                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1446                                 
1447                                 /*const float keyspeed = 500;
1448                                 if(input->isKeyDown(irr::KEY_UP))
1449                                         dy -= dtime * keyspeed;
1450                                 if(input->isKeyDown(irr::KEY_DOWN))
1451                                         dy += dtime * keyspeed;
1452                                 if(input->isKeyDown(irr::KEY_LEFT))
1453                                         dx -= dtime * keyspeed;
1454                                 if(input->isKeyDown(irr::KEY_RIGHT))
1455                                         dx += dtime * keyspeed;*/
1456
1457                                 camera_yaw -= dx*0.2;
1458                                 camera_pitch += dy*0.2;
1459                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1460                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1461                         }
1462                         input->setMousePos(displaycenter.X, displaycenter.Y);
1463                 }
1464                 else{
1465                         // Mac OSX gets upset if this is set every frame
1466                         if(device->getCursorControl()->isVisible() == false)
1467                                 device->getCursorControl()->setVisible(true);
1468
1469                         //infostream<<"window inactive"<<std::endl;
1470                         first_loop_after_window_activation = true;
1471                 }
1472
1473                 /*
1474                         Player speed control
1475                 */
1476                 
1477                 if(!noMenuActive() || !device->isWindowActive())
1478                 {
1479                         PlayerControl control(
1480                                 false,
1481                                 false,
1482                                 false,
1483                                 false,
1484                                 false,
1485                                 false,
1486                                 false,
1487                                 camera_pitch,
1488                                 camera_yaw
1489                         );
1490                         client.setPlayerControl(control);
1491                 }
1492                 else
1493                 {
1494                         /*bool a_up,
1495                         bool a_down,
1496                         bool a_left,
1497                         bool a_right,
1498                         bool a_jump,
1499                         bool a_superspeed,
1500                         bool a_sneak,
1501                         float a_pitch,
1502                         float a_yaw*/
1503                         PlayerControl control(
1504                                 input->isKeyDown(getKeySetting("keymap_forward")),
1505                                 input->isKeyDown(getKeySetting("keymap_backward")),
1506                                 input->isKeyDown(getKeySetting("keymap_left")),
1507                                 input->isKeyDown(getKeySetting("keymap_right")),
1508                                 input->isKeyDown(getKeySetting("keymap_jump")),
1509                                 input->isKeyDown(getKeySetting("keymap_special1")),
1510                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1511                                 camera_pitch,
1512                                 camera_yaw
1513                         );
1514                         client.setPlayerControl(control);
1515                 }
1516                 
1517                 /*
1518                         Run server
1519                 */
1520
1521                 if(server != NULL)
1522                 {
1523                         //TimeTaker timer("server->step(dtime)");
1524                         server->step(dtime);
1525                 }
1526
1527                 /*
1528                         Process environment
1529                 */
1530                 
1531                 {
1532                         //TimeTaker timer("client.step(dtime)");
1533                         client.step(dtime);
1534                         //client.step(dtime_avg1);
1535                 }
1536
1537                 {
1538                         // Read client events
1539                         for(;;)
1540                         {
1541                                 ClientEvent event = client.getClientEvent();
1542                                 if(event.type == CE_NONE)
1543                                 {
1544                                         break;
1545                                 }
1546                                 else if(event.type == CE_PLAYER_DAMAGE)
1547                                 {
1548                                         //u16 damage = event.player_damage.amount;
1549                                         //infostream<<"Player damage: "<<damage<<std::endl;
1550                                         damage_flash_timer = 0.05;
1551                                         if(event.player_damage.amount >= 2){
1552                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1553                                         }
1554                                 }
1555                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1556                                 {
1557                                         camera_yaw = event.player_force_move.yaw;
1558                                         camera_pitch = event.player_force_move.pitch;
1559                                 }
1560                                 else if(event.type == CE_DEATHSCREEN)
1561                                 {
1562                                         if(respawn_menu_active)
1563                                                 continue;
1564
1565                                         /*bool set_camera_point_target =
1566                                                         event.deathscreen.set_camera_point_target;
1567                                         v3f camera_point_target;
1568                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1569                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1570                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1571                                         MainRespawnInitiator *respawner =
1572                                                         new MainRespawnInitiator(
1573                                                                         &respawn_menu_active, &client);
1574                                         GUIDeathScreen *menu =
1575                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1576                                                                 &g_menumgr, respawner);
1577                                         menu->drop();
1578                                         
1579                                         /* Handle visualization */
1580
1581                                         damage_flash_timer = 0;
1582
1583                                         /*LocalPlayer* player = client.getLocalPlayer();
1584                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1585                                         camera.update(player, busytime, screensize);*/
1586                                 }
1587                         }
1588                 }
1589                 
1590                 //TimeTaker //timer2("//timer2");
1591
1592                 LocalPlayer* player = client.getLocalPlayer();
1593                 camera.update(player, busytime, screensize);
1594                 camera.step(dtime);
1595
1596                 v3f player_position = player->getPosition();
1597                 v3f camera_position = camera.getPosition();
1598                 v3f camera_direction = camera.getDirection();
1599                 f32 camera_fov = camera.getFovMax();
1600                 
1601                 if(!disable_camera_update){
1602                         client.updateCamera(camera_position,
1603                                 camera_direction, camera_fov);
1604                 }
1605
1606                 //timer2.stop();
1607                 //TimeTaker //timer3("//timer3");
1608
1609                 /*
1610                         Calculate what block is the crosshair pointing to
1611                 */
1612                 
1613                 //u32 t1 = device->getTimer()->getRealTime();
1614                 
1615                 //f32 d = 4; // max. distance
1616                 f32 d = 4; // max. distance
1617                 core::line3d<f32> shootline(camera_position,
1618                                 camera_position + camera_direction * BS * (d+1));
1619
1620                 ClientActiveObject *selected_active_object
1621                                 = client.getSelectedActiveObject
1622                                         (d*BS, camera_position, shootline);
1623                 
1624                 bool left_punch = false;
1625                 bool left_punch_muted = false;
1626
1627                 if(selected_active_object != NULL)
1628                 {
1629                         /* Clear possible cracking animation */
1630                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1631                         {
1632                                 client.clearTempMod(nodepos_old);
1633                                 dig_time = 0.0;
1634                                 nodepos_old = v3s16(-32768,-32768,-32768);
1635                         }
1636
1637                         //infostream<<"Client returned selected_active_object != NULL"<<std::endl;
1638                         
1639                         core::aabbox3d<f32> *selection_box
1640                                         = selected_active_object->getSelectionBox();
1641                         // Box should exist because object was returned in the
1642                         // first place
1643                         assert(selection_box);
1644
1645                         v3f pos = selected_active_object->getPosition();
1646
1647                         core::aabbox3d<f32> box_on_map(
1648                                         selection_box->MinEdge + pos,
1649                                         selection_box->MaxEdge + pos
1650                         );
1651                         
1652                         if(selected_active_object->doShowSelectionBox())
1653                                 hilightboxes.push_back(box_on_map);
1654
1655                         //infotext = narrow_to_wide("A ClientActiveObject");
1656                         infotext = narrow_to_wide(selected_active_object->infoText());
1657
1658                         //if(input->getLeftClicked())
1659                         if(input->getLeftState())
1660                         {
1661                                 bool do_punch = false;
1662                                 bool do_punch_damage = false;
1663                                 if(object_hit_delay_timer <= 0.0){
1664                                         do_punch = true;
1665                                         do_punch_damage = true;
1666                                         object_hit_delay_timer = object_hit_delay;
1667                                 }
1668                                 if(input->getLeftClicked()){
1669                                         do_punch = true;
1670                                 }
1671                                 if(do_punch){
1672                                         infostream<<"Left-clicked object"<<std::endl;
1673                                         left_punch = true;
1674                                 }
1675                                 if(do_punch_damage){
1676                                         client.clickActiveObject(0,
1677                                                         selected_active_object->getId(), g_selected_item);
1678                                 }
1679                         }
1680                         else if(input->getRightClicked())
1681                         {
1682                                 infostream<<"Right-clicked object"<<std::endl;
1683                                 client.clickActiveObject(1,
1684                                                 selected_active_object->getId(), g_selected_item);
1685                         }
1686                 }
1687                 else // selected_object == NULL
1688                 {
1689
1690                 /*
1691                         Find out which node we are pointing at
1692                 */
1693                 
1694                 bool nodefound = false;
1695                 v3s16 nodepos;
1696                 v3s16 neighbourpos;
1697                 core::aabbox3d<f32> nodehilightbox;
1698
1699                 getPointedNode(&client, player_position,
1700                                 camera_direction, camera_position,
1701                                 nodefound, shootline,
1702                                 nodepos, neighbourpos,
1703                                 nodehilightbox, d);
1704         
1705                 if(!nodefound){
1706                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1707                         {
1708                                 client.clearTempMod(nodepos_old);
1709                                 dig_time = 0.0;
1710                                 nodepos_old = v3s16(-32768,-32768,-32768);
1711                         }
1712                 } else {
1713                         /*
1714                                 Visualize selection
1715                         */
1716
1717                         hilightboxes.push_back(nodehilightbox);
1718
1719                         /*
1720                                 Check information text of node
1721                         */
1722
1723                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1724                         if(meta)
1725                         {
1726                                 infotext = narrow_to_wide(meta->infoText());
1727                         }
1728                         
1729                         //MapNode node = client.getNode(nodepos);
1730
1731                         /*
1732                                 Handle digging
1733                         */
1734                         
1735                         if(input->getLeftReleased())
1736                         {
1737                                 client.clearTempMod(nodepos);
1738                                 dig_time = 0.0;
1739                         }
1740                         
1741                         if(nodig_delay_counter > 0.0)
1742                         {
1743                                 nodig_delay_counter -= dtime;
1744                         }
1745                         else
1746                         {
1747                                 if(nodepos != nodepos_old)
1748                                 {
1749                                         infostream<<"Pointing at ("<<nodepos.X<<","
1750                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1751
1752                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1753                                         {
1754                                                 client.clearTempMod(nodepos_old);
1755                                                 dig_time = 0.0;
1756                                                 nodepos_old = v3s16(-32768,-32768,-32768);
1757                                         }
1758                                 }
1759
1760                                 if(input->getLeftClicked() ||
1761                                                 (input->getLeftState() && nodepos != nodepos_old))
1762                                 {
1763                                         infostream<<"Started digging"<<std::endl;
1764                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1765                                 }
1766                                 if(input->getLeftClicked())
1767                                 {
1768                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1769                                 }
1770                                 if(input->getLeftState())
1771                                 {
1772                                         MapNode n = client.getNode(nodepos);
1773                                 
1774                                         // Get tool name. Default is "" = bare hands
1775                                         std::string toolname = "";
1776                                         InventoryList *mlist = local_inventory.getList("main");
1777                                         if(mlist != NULL)
1778                                         {
1779                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1780                                                 if(item && (std::string)item->getName() == "ToolItem")
1781                                                 {
1782                                                         ToolItem *titem = (ToolItem*)item;
1783                                                         toolname = titem->getToolName();
1784                                                 }
1785                                         }
1786
1787                                         // Get digging properties for material and tool
1788                                         content_t material = n.getContent();
1789                                         DiggingProperties prop =
1790                                                         getDiggingProperties(material, toolname);
1791                                         
1792                                         float dig_time_complete = 0.0;
1793
1794                                         if(prop.diggable == false)
1795                                         {
1796                                                 /*infostream<<"Material "<<(int)material
1797                                                                 <<" not diggable with \""
1798                                                                 <<toolname<<"\""<<std::endl;*/
1799                                                 // I guess nobody will wait for this long
1800                                                 dig_time_complete = 10000000.0;
1801                                         }
1802                                         else
1803                                         {
1804                                                 dig_time_complete = prop.time;
1805                                         }
1806                                         
1807                                         if(dig_time_complete >= 0.001)
1808                                         {
1809                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1810                                                                 * dig_time/dig_time_complete);
1811                                         }
1812                                         // This is for torches
1813                                         else
1814                                         {
1815                                                 dig_index = CRACK_ANIMATION_LENGTH;
1816                                         }
1817
1818                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1819                                         {
1820                                                 //TimeTaker timer("client.setTempMod");
1821                                                 //infostream<<"dig_index="<<dig_index<<std::endl;
1822                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1823                                         }
1824                                         else
1825                                         {
1826                                                 infostream<<"Digging completed"<<std::endl;
1827                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1828                                                 client.clearTempMod(nodepos);
1829                                                 client.removeNode(nodepos);
1830
1831                                                 dig_time = 0;
1832
1833                                                 nodig_delay_counter = dig_time_complete
1834                                                                 / (float)CRACK_ANIMATION_LENGTH;
1835
1836                                                 // We don't want a corresponding delay to
1837                                                 // very time consuming nodes
1838                                                 if(nodig_delay_counter > 0.5)
1839                                                 {
1840                                                         nodig_delay_counter = 0.5;
1841                                                 }
1842                                                 // We want a slight delay to very little
1843                                                 // time consuming nodes
1844                                                 float mindelay = 0.15;
1845                                                 if(nodig_delay_counter < mindelay)
1846                                                 {
1847                                                         nodig_delay_counter = mindelay;
1848                                                 }
1849                                         }
1850
1851                                         dig_time += dtime;
1852
1853                                         camera.setDigging(0);  // left click animation
1854                                 }
1855                         }
1856                         
1857                         
1858                         if(input->getRightClicked())
1859                         {
1860                                 infostream<<"Ground right-clicked"<<std::endl;
1861                                 
1862                                 // If metadata provides an inventory view, activate it
1863                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
1864                                 {
1865                                         infostream<<"Launching custom inventory view"<<std::endl;
1866                                         /*
1867                                                 Construct the unique identification string of the node
1868                                         */
1869                                         std::string current_name;
1870                                         current_name += "nodemeta:";
1871                                         current_name += itos(nodepos.X);
1872                                         current_name += ",";
1873                                         current_name += itos(nodepos.Y);
1874                                         current_name += ",";
1875                                         current_name += itos(nodepos.Z);
1876                                         
1877                                         /*
1878                                                 Create menu
1879                                         */
1880
1881                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1882                                         v2s16 invsize =
1883                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
1884                                                         draw_spec,
1885                                                         meta->getInventoryDrawSpecString(),
1886                                                         current_name);
1887
1888                                         GUIInventoryMenu *menu =
1889                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1890                                                         &g_menumgr, invsize,
1891                                                         client.getInventoryContext(),
1892                                                         &client);
1893                                         menu->setDrawSpec(draw_spec);
1894                                         menu->drop();
1895                                 }
1896                                 else if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1897                                 {
1898                                         infostream<<"Sign node right-clicked"<<std::endl;
1899                                         
1900                                         SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1901                                         
1902                                         // Get a new text for it
1903
1904                                         TextDest *dest = new TextDestSignNode(nodepos, &client);
1905
1906                                         std::wstring wtext =
1907                                                         narrow_to_wide(signmeta->getText());
1908
1909                                         (new GUITextInputMenu(guienv, guiroot, -1,
1910                                                         &g_menumgr, dest,
1911                                                         wtext))->drop();
1912                                 }
1913                                 else
1914                                 {
1915                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1916                                         camera.setDigging(1);  // right click animation
1917                                 }
1918                         }
1919                         
1920                         nodepos_old = nodepos;
1921                 }
1922
1923                 } // selected_object == NULL
1924                 
1925                 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
1926                 {
1927                         camera.setDigging(0); // left click animation
1928                 }
1929
1930                 input->resetLeftClicked();
1931                 input->resetRightClicked();
1932                 
1933                 if(input->getLeftReleased())
1934                 {
1935                         infostream<<"Left button released (stopped digging)"
1936                                         <<std::endl;
1937                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1938                 }
1939                 if(input->getRightReleased())
1940                 {
1941                         //inostream<<DTIME<<"Right released"<<std::endl;
1942                         // Nothing here
1943                 }
1944                 
1945                 input->resetLeftReleased();
1946                 input->resetRightReleased();
1947                 
1948                 /*
1949                         Calculate stuff for drawing
1950                 */
1951
1952                 u32 daynight_ratio = client.getDayNightRatio();
1953                 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1954                 video::SColor bgcolor = video::SColor(
1955                                 255,
1956                                 bgcolor_bright.getRed() * l / 255,
1957                                 bgcolor_bright.getGreen() * l / 255,
1958                                 bgcolor_bright.getBlue() * l / 255);
1959                                 /*skycolor.getRed() * l / 255,
1960                                 skycolor.getGreen() * l / 255,
1961                                 skycolor.getBlue() * l / 255);*/
1962
1963                 float brightness = (float)l/255.0;
1964
1965                 /*
1966                         Update skybox
1967                 */
1968                 if(fabs(brightness - old_brightness) > 0.01)
1969                         update_skybox(driver, smgr, skybox, brightness);
1970
1971                 /*
1972                         Update clouds
1973                 */
1974                 if(clouds)
1975                 {
1976                         clouds->step(dtime);
1977                         clouds->update(v2f(player_position.X, player_position.Z),
1978                                         0.05+brightness*0.95);
1979                 }
1980                 
1981                 /*
1982                         Update farmesh
1983                 */
1984                 if(farmesh)
1985                 {
1986                         farmesh_range = draw_control.wanted_range * 10;
1987                         if(draw_control.range_all && farmesh_range < 500)
1988                                 farmesh_range = 500;
1989                         if(farmesh_range > 1000)
1990                                 farmesh_range = 1000;
1991
1992                         farmesh->step(dtime);
1993                         farmesh->update(v2f(player_position.X, player_position.Z),
1994                                         0.05+brightness*0.95, farmesh_range);
1995                 }
1996                 
1997                 // Store brightness value
1998                 old_brightness = brightness;
1999
2000                 /*
2001                         Fog
2002                 */
2003                 
2004                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2005                 {
2006                         f32 range;
2007                         if(farmesh)
2008                         {
2009                                 range = BS*farmesh_range;
2010                         }
2011                         else
2012                         {
2013                                 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
2014                                 range *= 0.9;
2015                                 if(draw_control.range_all)
2016                                         range = 100000*BS;
2017                                 /*if(range < 50*BS)
2018                                         range = range * 0.5 + 25*BS;*/
2019                         }
2020
2021                         driver->setFog(
2022                                 bgcolor,
2023                                 video::EFT_FOG_LINEAR,
2024                                 range*0.4,
2025                                 range*1.0,
2026                                 0.01,
2027                                 false, // pixel fog
2028                                 false // range fog
2029                         );
2030                 }
2031                 else
2032                 {
2033                         driver->setFog(
2034                                 bgcolor,
2035                                 video::EFT_FOG_LINEAR,
2036                                 100000*BS,
2037                                 110000*BS,
2038                                 0.01,
2039                                 false, // pixel fog
2040                                 false // range fog
2041                         );
2042                 }
2043
2044                 /*
2045                         Update gui stuff (0ms)
2046                 */
2047
2048                 //TimeTaker guiupdatetimer("Gui updating");
2049                 
2050                 {
2051                         static float drawtime_avg = 0;
2052                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2053                         static float beginscenetime_avg = 0;
2054                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2055                         static float scenetime_avg = 0;
2056                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2057                         static float endscenetime_avg = 0;
2058                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
2059                         
2060                         char temptext[300];
2061                         snprintf(temptext, 300, "Minetest-c55 %s ("
2062                                         "R: range_all=%i"
2063                                         ")"
2064                                         " drawtime=%.0f, beginscenetime=%.0f"
2065                                         ", scenetime=%.0f, endscenetime=%.0f",
2066                                         VERSION_STRING,
2067                                         draw_control.range_all,
2068                                         drawtime_avg,
2069                                         beginscenetime_avg,
2070                                         scenetime_avg,
2071                                         endscenetime_avg
2072                                         );
2073                         
2074                         guitext->setText(narrow_to_wide(temptext).c_str());
2075                 }
2076                 
2077                 {
2078                         char temptext[300];
2079                         snprintf(temptext, 300,
2080                                         "(% .1f, % .1f, % .1f)"
2081                                         " (% .3f < btime_jitter < % .3f"
2082                                         ", dtime_jitter = % .1f %%"
2083                                         ", v_range = %.1f, RTT = %.3f)",
2084                                         player_position.X/BS,
2085                                         player_position.Y/BS,
2086                                         player_position.Z/BS,
2087                                         busytime_jitter1_min_sample,
2088                                         busytime_jitter1_max_sample,
2089                                         dtime_jitter1_max_fraction * 100.0,
2090                                         draw_control.wanted_range,
2091                                         client.getRTT()
2092                                         );
2093
2094                         guitext2->setText(narrow_to_wide(temptext).c_str());
2095                 }
2096                 
2097                 {
2098                         guitext_info->setText(infotext.c_str());
2099                 }
2100                 
2101                 /*
2102                         Get chat messages from client
2103                 */
2104                 {
2105                         // Get new messages
2106                         std::wstring message;
2107                         while(client.getChatMessage(message))
2108                         {
2109                                 chat_lines.push_back(ChatLine(message));
2110                                 /*if(chat_lines.size() > 6)
2111                                 {
2112                                         core::list<ChatLine>::Iterator
2113                                                         i = chat_lines.begin();
2114                                         chat_lines.erase(i);
2115                                 }*/
2116                         }
2117                         // Append them to form the whole static text and throw
2118                         // it to the gui element
2119                         std::wstring whole;
2120                         // This will correspond to the line number counted from
2121                         // top to bottom, from size-1 to 0
2122                         s16 line_number = chat_lines.size();
2123                         // Count of messages to be removed from the top
2124                         u16 to_be_removed_count = 0;
2125                         for(core::list<ChatLine>::Iterator
2126                                         i = chat_lines.begin();
2127                                         i != chat_lines.end(); i++)
2128                         {
2129                                 // After this, line number is valid for this loop
2130                                 line_number--;
2131                                 // Increment age
2132                                 (*i).age += dtime;
2133                                 /*
2134                                         This results in a maximum age of 60*6 to the
2135                                         lowermost line and a maximum of 6 lines
2136                                 */
2137                                 float allowed_age = (6-line_number) * 60.0;
2138
2139                                 if((*i).age > allowed_age)
2140                                 {
2141                                         to_be_removed_count++;
2142                                         continue;
2143                                 }
2144                                 whole += (*i).text + L'\n';
2145                         }
2146                         for(u16 i=0; i<to_be_removed_count; i++)
2147                         {
2148                                 core::list<ChatLine>::Iterator
2149                                                 it = chat_lines.begin();
2150                                 chat_lines.erase(it);
2151                         }
2152                         guitext_chat->setText(whole.c_str());
2153
2154                         // Update gui element size and position
2155
2156                         /*core::rect<s32> rect(
2157                                         10,
2158                                         screensize.Y - guitext_chat_pad_bottom
2159                                                         - text_height*chat_lines.size(),
2160                                         screensize.X - 10,
2161                                         screensize.Y - guitext_chat_pad_bottom
2162                         );*/
2163                         core::rect<s32> rect(
2164                                         10,
2165                                         50,
2166                                         screensize.X - 10,
2167                                         50 + guitext_chat->getTextHeight()
2168                         );
2169
2170                         guitext_chat->setRelativePosition(rect);
2171
2172                         // Don't show chat if empty or profiler is enabled
2173                         if(chat_lines.size() == 0 || show_profiler)
2174                                 guitext_chat->setVisible(false);
2175                         else
2176                                 guitext_chat->setVisible(true);
2177                 }
2178
2179                 /*
2180                         Inventory
2181                 */
2182                 
2183                 static u16 old_selected_item = 65535;
2184                 if(client.getLocalInventoryUpdated()
2185                                 || g_selected_item != old_selected_item)
2186                 {
2187                         client.selectPlayerItem(g_selected_item);
2188                         old_selected_item = g_selected_item;
2189                         //infostream<<"Updating local inventory"<<std::endl;
2190                         client.getLocalInventory(local_inventory);
2191
2192                         // Update wielded tool
2193                         InventoryList *mlist = local_inventory.getList("main");
2194                         InventoryItem *item = NULL;
2195                         if(mlist != NULL)
2196                                 item = mlist->getItem(g_selected_item);
2197                         camera.wield(item);
2198                 }
2199                 
2200                 /*
2201                         Send actions returned by the inventory menu
2202                 */
2203                 while(inventory_action_queue.size() != 0)
2204                 {
2205                         InventoryAction *a = inventory_action_queue.pop_front();
2206
2207                         client.sendInventoryAction(a);
2208                         // Eat it
2209                         delete a;
2210                 }
2211
2212                 /*
2213                         Drawing begins
2214                 */
2215
2216                 TimeTaker drawtimer("Drawing");
2217
2218                 
2219                 {
2220                         TimeTaker timer("beginScene");
2221                         driver->beginScene(true, true, bgcolor);
2222                         //driver->beginScene(false, true, bgcolor);
2223                         beginscenetime = timer.stop(true);
2224                 }
2225                 
2226                 //timer3.stop();
2227                 
2228                 //infostream<<"smgr->drawAll()"<<std::endl;
2229                 
2230                 {
2231                         TimeTaker timer("smgr");
2232                         smgr->drawAll();
2233                         scenetime = timer.stop(true);
2234                 }
2235                 
2236                 {
2237                 //TimeTaker timer9("auxiliary drawings");
2238                 // 0ms
2239                 
2240                 //timer9.stop();
2241                 //TimeTaker //timer10("//timer10");
2242                 
2243                 video::SMaterial m;
2244                 //m.Thickness = 10;
2245                 m.Thickness = 3;
2246                 m.Lighting = false;
2247                 driver->setMaterial(m);
2248
2249                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2250
2251                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
2252                                 i != hilightboxes.end(); i++)
2253                 {
2254                         /*infostream<<"hilightbox min="
2255                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2256                                         <<" max="
2257                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2258                                         <<std::endl;*/
2259                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
2260                 }
2261
2262                 /*
2263                         Wielded tool
2264                 */
2265                 {
2266                         // Warning: This clears the Z buffer.
2267                         camera.drawWieldedTool();
2268                 }
2269
2270                 /*
2271                         Post effects
2272                 */
2273                 {
2274                         client.renderPostFx();
2275                 }
2276
2277                 /*
2278                         Frametime log
2279                 */
2280                 if(g_settings->getBool("frametime_graph") == true)
2281                 {
2282                         s32 x = 10;
2283                         for(core::list<float>::Iterator
2284                                         i = frametime_log.begin();
2285                                         i != frametime_log.end();
2286                                         i++)
2287                         {
2288                                 driver->draw2DLine(v2s32(x,50),
2289                                                 v2s32(x,50+(*i)*1000),
2290                                                 video::SColor(255,255,255,255));
2291                                 x++;
2292                         }
2293                 }
2294
2295                 /*
2296                         Draw crosshair
2297                 */
2298                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2299                                 displaycenter + core::vector2d<s32>(10,0),
2300                                 video::SColor(255,255,255,255));
2301                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2302                                 displaycenter + core::vector2d<s32>(0,10),
2303                                 video::SColor(255,255,255,255));
2304
2305                 } // timer
2306
2307                 //timer10.stop();
2308                 //TimeTaker //timer11("//timer11");
2309
2310                 /*
2311                         Draw gui
2312                 */
2313                 // 0-1ms
2314                 guienv->drawAll();
2315
2316                 /*
2317                         Draw hotbar
2318                 */
2319                 {
2320                         draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
2321                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2322                                         client.getHP());
2323                 }
2324
2325                 /*
2326                         Damage flash
2327                 */
2328                 if(damage_flash_timer > 0.0)
2329                 {
2330                         damage_flash_timer -= dtime;
2331                         
2332                         video::SColor color(128,255,0,0);
2333                         driver->draw2DRectangle(color,
2334                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2335                                         NULL);
2336                 }
2337
2338                 /*
2339                         End scene
2340                 */
2341                 {
2342                         TimeTaker timer("endScene");
2343                         endSceneX(driver);
2344                         endscenetime = timer.stop(true);
2345                 }
2346
2347                 drawtime = drawtimer.stop(true);
2348
2349                 /*
2350                         End of drawing
2351                 */
2352
2353                 static s16 lastFPS = 0;
2354                 //u16 fps = driver->getFPS();
2355                 u16 fps = (1.0/dtime_avg1);
2356
2357                 if (lastFPS != fps)
2358                 {
2359                         core::stringw str = L"Minetest [";
2360                         str += driver->getName();
2361                         str += "] FPS=";
2362                         str += fps;
2363
2364                         device->setWindowCaption(str.c_str());
2365                         lastFPS = fps;
2366                 }
2367         }
2368
2369         /*
2370                 Drop stuff
2371         */
2372         if(clouds)
2373                 clouds->drop();
2374         
2375         /*
2376                 Draw a "shutting down" screen, which will be shown while the map
2377                 generator and other stuff quits
2378         */
2379         {
2380                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2381                 draw_load_screen(L"Shutting down stuff...", driver, font);
2382                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2383                 guienv->drawAll();
2384                 driver->endScene();
2385                 gui_shuttingdowntext->remove();*/
2386         }
2387 }
2388
2389