]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
Fix an obvious bug in utility.h
[dragonfireclient.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
892         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
893                         L"<Profiler>",
894                         core::rect<s32>(6, 4+(text_height+5)*3, 400,
895                         (text_height+5)*3 + 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
955         bool force_fog_off = 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                         guitext_profiler->setText(narrow_to_wide(os.str()).c_str());
1192
1193                         g_profiler->clear();
1194                 }
1195
1196                 /*
1197                         Direct handling of user input
1198                 */
1199                 
1200                 // Reset input if window not active or some menu is active
1201                 if(device->isWindowActive() == false || noMenuActive() == false)
1202                 {
1203                         input->clear();
1204                 }
1205
1206                 // Input handler step() (used by the random input generator)
1207                 input->step(dtime);
1208
1209                 /*
1210                         Launch menus according to keys
1211                 */
1212                 if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1213                 {
1214                         infostream<<"the_game: "
1215                                         <<"Launching inventory"<<std::endl;
1216                         
1217                         GUIInventoryMenu *menu =
1218                                 new GUIInventoryMenu(guienv, guiroot, -1,
1219                                         &g_menumgr, v2s16(8,7),
1220                                         client.getInventoryContext(),
1221                                         &client);
1222
1223                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1224                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1225                                         "list", "current_player", "main",
1226                                         v2s32(0, 3), v2s32(8, 4)));
1227                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1228                                         "list", "current_player", "craft",
1229                                         v2s32(3, 0), v2s32(3, 3)));
1230                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1231                                         "list", "current_player", "craftresult",
1232                                         v2s32(7, 1), v2s32(1, 1)));
1233
1234                         menu->setDrawSpec(draw_spec);
1235
1236                         menu->drop();
1237                 }
1238                 else if(input->wasKeyDown(EscapeKey))
1239                 {
1240                         infostream<<"the_game: "
1241                                         <<"Launching pause menu"<<std::endl;
1242                         // It will delete itself by itself
1243                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1244                                         &g_menumgr))->drop();
1245
1246                         // Move mouse cursor on top of the disconnect button
1247                         input->setMousePos(displaycenter.X, displaycenter.Y+25);
1248                 }
1249                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1250                 {
1251                         TextDest *dest = new TextDestChat(&client);
1252
1253                         (new GUITextInputMenu(guienv, guiroot, -1,
1254                                         &g_menumgr, dest,
1255                                         L""))->drop();
1256                 }
1257                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1258                 {
1259                         TextDest *dest = new TextDestChat(&client);
1260
1261                         (new GUITextInputMenu(guienv, guiroot, -1,
1262                                         &g_menumgr, dest,
1263                                         L"/"))->drop();
1264                 }
1265                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1266                 {
1267                         if(g_settings->getBool("free_move"))
1268                         {
1269                                 g_settings->set("free_move","false");
1270                                 chat_lines.push_back(ChatLine(L"free_move disabled"));
1271                         }
1272                         else
1273                         {
1274                                 g_settings->set("free_move","true");
1275                                 chat_lines.push_back(ChatLine(L"free_move enabled"));
1276                         }
1277                 }
1278                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1279                 {
1280                         if(g_settings->getBool("fast_move"))
1281                         {
1282                                 g_settings->set("fast_move","false");
1283                                 chat_lines.push_back(ChatLine(L"fast_move disabled"));
1284                         }
1285                         else
1286                         {
1287                                 g_settings->set("fast_move","true");
1288                                 chat_lines.push_back(ChatLine(L"fast_move enabled"));
1289                         }
1290                 }
1291                 else if(input->wasKeyDown(getKeySetting("keymap_frametime_graph")))
1292                 {
1293                         if(g_settings->getBool("frametime_graph"))
1294                         {
1295                                 g_settings->set("frametime_graph","false");
1296                                 chat_lines.push_back(ChatLine(L"frametime_graph disabled"));
1297                         }
1298                         else
1299                         {
1300                                 g_settings->set("frametime_graph","true");
1301                                 chat_lines.push_back(ChatLine(L"frametime_graph enabled"));
1302                         }
1303                 }
1304                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1305                 {
1306                         irr::video::IImage* const image = driver->createScreenShot(); 
1307                         if (image) { 
1308                                 irr::c8 filename[256]; 
1309                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1310                                                  g_settings->get("screenshot_path").c_str(),
1311                                                  device->getTimer()->getRealTime()); 
1312                                 if (driver->writeImageToFile(image, filename)) {
1313                                         std::wstringstream sstr;
1314                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1315                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1316                                         chat_lines.push_back(ChatLine(sstr.str()));
1317                                 } else{
1318                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1319                                 }
1320                                 image->drop(); 
1321                         }                        
1322                 }
1323                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1324                 {
1325                         show_profiler = !show_profiler;
1326                         guitext_profiler->setVisible(show_profiler);
1327                 }
1328                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1329                 {
1330                         force_fog_off = !force_fog_off;
1331                 }
1332
1333                 // Item selection with mouse wheel
1334                 {
1335                         s32 wheel = input->getMouseWheel();
1336                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1337                                         hotbar_itemcount-1);
1338
1339                         if(wheel < 0)
1340                         {
1341                                 if(g_selected_item < max_item)
1342                                         g_selected_item++;
1343                                 else
1344                                         g_selected_item = 0;
1345                         }
1346                         else if(wheel > 0)
1347                         {
1348                                 if(g_selected_item > 0)
1349                                         g_selected_item--;
1350                                 else
1351                                         g_selected_item = max_item;
1352                         }
1353                 }
1354                 
1355                 // Item selection
1356                 for(u16 i=0; i<10; i++)
1357                 {
1358                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1359                         if(input->wasKeyDown(*kp))
1360                         {
1361                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1362                                 {
1363                                         g_selected_item = i;
1364
1365                                         infostream<<"Selected item: "
1366                                                         <<g_selected_item<<std::endl;
1367                                 }
1368                         }
1369                 }
1370
1371                 // Viewing range selection
1372                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1373                 {
1374                         if(draw_control.range_all)
1375                         {
1376                                 draw_control.range_all = false;
1377                                 infostream<<"Disabled full viewing range"<<std::endl;
1378                         }
1379                         else
1380                         {
1381                                 draw_control.range_all = true;
1382                                 infostream<<"Enabled full viewing range"<<std::endl;
1383                         }
1384                 }
1385
1386                 // Print debug stacks
1387                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1388                 {
1389                         dstream<<"-----------------------------------------"
1390                                         <<std::endl;
1391                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1392                         dstream<<"-----------------------------------------"
1393                                         <<std::endl;
1394                         debug_stacks_print();
1395                 }
1396
1397                 /*
1398                         Mouse and camera control
1399                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1400                 */
1401                 
1402                 if((device->isWindowActive() && noMenuActive()) || random_input)
1403                 {
1404                         if(!random_input)
1405                         {
1406                                 // Mac OSX gets upset if this is set every frame
1407                                 if(device->getCursorControl()->isVisible())
1408                                         device->getCursorControl()->setVisible(false);
1409                         }
1410
1411                         if(first_loop_after_window_activation){
1412                                 //infostream<<"window active, first loop"<<std::endl;
1413                                 first_loop_after_window_activation = false;
1414                         }
1415                         else{
1416                                 s32 dx = input->getMousePos().X - displaycenter.X;
1417                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1418                                 if(invert_mouse)
1419                                         dy = -dy;
1420                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1421                                 
1422                                 /*const float keyspeed = 500;
1423                                 if(input->isKeyDown(irr::KEY_UP))
1424                                         dy -= dtime * keyspeed;
1425                                 if(input->isKeyDown(irr::KEY_DOWN))
1426                                         dy += dtime * keyspeed;
1427                                 if(input->isKeyDown(irr::KEY_LEFT))
1428                                         dx -= dtime * keyspeed;
1429                                 if(input->isKeyDown(irr::KEY_RIGHT))
1430                                         dx += dtime * keyspeed;*/
1431
1432                                 camera_yaw -= dx*0.2;
1433                                 camera_pitch += dy*0.2;
1434                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1435                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1436                         }
1437                         input->setMousePos(displaycenter.X, displaycenter.Y);
1438                 }
1439                 else{
1440                         // Mac OSX gets upset if this is set every frame
1441                         if(device->getCursorControl()->isVisible() == false)
1442                                 device->getCursorControl()->setVisible(true);
1443
1444                         //infostream<<"window inactive"<<std::endl;
1445                         first_loop_after_window_activation = true;
1446                 }
1447
1448                 /*
1449                         Player speed control
1450                 */
1451                 
1452                 if(!noMenuActive() || !device->isWindowActive())
1453                 {
1454                         PlayerControl control(
1455                                 false,
1456                                 false,
1457                                 false,
1458                                 false,
1459                                 false,
1460                                 false,
1461                                 false,
1462                                 camera_pitch,
1463                                 camera_yaw
1464                         );
1465                         client.setPlayerControl(control);
1466                 }
1467                 else
1468                 {
1469                         /*bool a_up,
1470                         bool a_down,
1471                         bool a_left,
1472                         bool a_right,
1473                         bool a_jump,
1474                         bool a_superspeed,
1475                         bool a_sneak,
1476                         float a_pitch,
1477                         float a_yaw*/
1478                         PlayerControl control(
1479                                 input->isKeyDown(getKeySetting("keymap_forward")),
1480                                 input->isKeyDown(getKeySetting("keymap_backward")),
1481                                 input->isKeyDown(getKeySetting("keymap_left")),
1482                                 input->isKeyDown(getKeySetting("keymap_right")),
1483                                 input->isKeyDown(getKeySetting("keymap_jump")),
1484                                 input->isKeyDown(getKeySetting("keymap_special1")),
1485                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1486                                 camera_pitch,
1487                                 camera_yaw
1488                         );
1489                         client.setPlayerControl(control);
1490                 }
1491                 
1492                 /*
1493                         Run server
1494                 */
1495
1496                 if(server != NULL)
1497                 {
1498                         //TimeTaker timer("server->step(dtime)");
1499                         server->step(dtime);
1500                 }
1501
1502                 /*
1503                         Process environment
1504                 */
1505                 
1506                 {
1507                         //TimeTaker timer("client.step(dtime)");
1508                         client.step(dtime);
1509                         //client.step(dtime_avg1);
1510                 }
1511
1512                 {
1513                         // Read client events
1514                         for(;;)
1515                         {
1516                                 ClientEvent event = client.getClientEvent();
1517                                 if(event.type == CE_NONE)
1518                                 {
1519                                         break;
1520                                 }
1521                                 else if(event.type == CE_PLAYER_DAMAGE)
1522                                 {
1523                                         //u16 damage = event.player_damage.amount;
1524                                         //infostream<<"Player damage: "<<damage<<std::endl;
1525                                         damage_flash_timer = 0.05;
1526                                         if(event.player_damage.amount >= 2){
1527                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1528                                         }
1529                                 }
1530                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1531                                 {
1532                                         camera_yaw = event.player_force_move.yaw;
1533                                         camera_pitch = event.player_force_move.pitch;
1534                                 }
1535                                 else if(event.type == CE_DEATHSCREEN)
1536                                 {
1537                                         if(respawn_menu_active)
1538                                                 continue;
1539
1540                                         /*bool set_camera_point_target =
1541                                                         event.deathscreen.set_camera_point_target;
1542                                         v3f camera_point_target;
1543                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1544                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1545                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1546                                         MainRespawnInitiator *respawner =
1547                                                         new MainRespawnInitiator(
1548                                                                         &respawn_menu_active, &client);
1549                                         GUIDeathScreen *menu =
1550                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1551                                                                 &g_menumgr, respawner);
1552                                         menu->drop();
1553                                         
1554                                         /* Handle visualization */
1555
1556                                         damage_flash_timer = 0;
1557
1558                                         /*LocalPlayer* player = client.getLocalPlayer();
1559                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1560                                         camera.update(player, busytime, screensize);*/
1561                                 }
1562                         }
1563                 }
1564                 
1565                 //TimeTaker //timer2("//timer2");
1566
1567                 LocalPlayer* player = client.getLocalPlayer();
1568                 camera.update(player, busytime, screensize);
1569                 camera.step(dtime);
1570
1571                 v3f player_position = player->getPosition();
1572                 v3f camera_position = camera.getPosition();
1573                 v3f camera_direction = camera.getDirection();
1574                 f32 camera_fov = camera.getFovMax();
1575                 
1576                 if(FIELD_OF_VIEW_TEST)
1577                         client.updateCamera(v3f(0,0,0), v3f(0,0,1), camera_fov);
1578                 else
1579                         client.updateCamera(camera_position,
1580                                 camera_direction, camera_fov);
1581
1582                 //timer2.stop();
1583                 //TimeTaker //timer3("//timer3");
1584
1585                 /*
1586                         Calculate what block is the crosshair pointing to
1587                 */
1588                 
1589                 //u32 t1 = device->getTimer()->getRealTime();
1590                 
1591                 //f32 d = 4; // max. distance
1592                 f32 d = 4; // max. distance
1593                 core::line3d<f32> shootline(camera_position,
1594                                 camera_position + camera_direction * BS * (d+1));
1595
1596                 ClientActiveObject *selected_active_object
1597                                 = client.getSelectedActiveObject
1598                                         (d*BS, camera_position, shootline);
1599                 
1600                 bool left_punch = false;
1601                 bool left_punch_muted = false;
1602
1603                 if(selected_active_object != NULL)
1604                 {
1605                         /* Clear possible cracking animation */
1606                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1607                         {
1608                                 client.clearTempMod(nodepos_old);
1609                                 dig_time = 0.0;
1610                                 nodepos_old = v3s16(-32768,-32768,-32768);
1611                         }
1612
1613                         //infostream<<"Client returned selected_active_object != NULL"<<std::endl;
1614                         
1615                         core::aabbox3d<f32> *selection_box
1616                                         = selected_active_object->getSelectionBox();
1617                         // Box should exist because object was returned in the
1618                         // first place
1619                         assert(selection_box);
1620
1621                         v3f pos = selected_active_object->getPosition();
1622
1623                         core::aabbox3d<f32> box_on_map(
1624                                         selection_box->MinEdge + pos,
1625                                         selection_box->MaxEdge + pos
1626                         );
1627                         
1628                         if(selected_active_object->doShowSelectionBox())
1629                                 hilightboxes.push_back(box_on_map);
1630
1631                         //infotext = narrow_to_wide("A ClientActiveObject");
1632                         infotext = narrow_to_wide(selected_active_object->infoText());
1633
1634                         //if(input->getLeftClicked())
1635                         if(input->getLeftState())
1636                         {
1637                                 bool do_punch = false;
1638                                 bool do_punch_damage = false;
1639                                 if(object_hit_delay_timer <= 0.0){
1640                                         do_punch = true;
1641                                         do_punch_damage = true;
1642                                         object_hit_delay_timer = object_hit_delay;
1643                                 }
1644                                 if(input->getLeftClicked()){
1645                                         do_punch = true;
1646                                 }
1647                                 if(do_punch){
1648                                         infostream<<"Left-clicked object"<<std::endl;
1649                                         left_punch = true;
1650                                 }
1651                                 if(do_punch_damage){
1652                                         client.clickActiveObject(0,
1653                                                         selected_active_object->getId(), g_selected_item);
1654                                 }
1655                         }
1656                         else if(input->getRightClicked())
1657                         {
1658                                 infostream<<"Right-clicked object"<<std::endl;
1659                                 client.clickActiveObject(1,
1660                                                 selected_active_object->getId(), g_selected_item);
1661                         }
1662                 }
1663                 else // selected_object == NULL
1664                 {
1665
1666                 /*
1667                         Find out which node we are pointing at
1668                 */
1669                 
1670                 bool nodefound = false;
1671                 v3s16 nodepos;
1672                 v3s16 neighbourpos;
1673                 core::aabbox3d<f32> nodehilightbox;
1674
1675                 getPointedNode(&client, player_position,
1676                                 camera_direction, camera_position,
1677                                 nodefound, shootline,
1678                                 nodepos, neighbourpos,
1679                                 nodehilightbox, d);
1680         
1681                 if(!nodefound){
1682                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1683                         {
1684                                 client.clearTempMod(nodepos_old);
1685                                 dig_time = 0.0;
1686                                 nodepos_old = v3s16(-32768,-32768,-32768);
1687                         }
1688                 } else {
1689                         /*
1690                                 Visualize selection
1691                         */
1692
1693                         hilightboxes.push_back(nodehilightbox);
1694
1695                         /*
1696                                 Check information text of node
1697                         */
1698
1699                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1700                         if(meta)
1701                         {
1702                                 infotext = narrow_to_wide(meta->infoText());
1703                         }
1704                         
1705                         //MapNode node = client.getNode(nodepos);
1706
1707                         /*
1708                                 Handle digging
1709                         */
1710                         
1711                         if(input->getLeftReleased())
1712                         {
1713                                 client.clearTempMod(nodepos);
1714                                 dig_time = 0.0;
1715                         }
1716                         
1717                         if(nodig_delay_counter > 0.0)
1718                         {
1719                                 nodig_delay_counter -= dtime;
1720                         }
1721                         else
1722                         {
1723                                 if(nodepos != nodepos_old)
1724                                 {
1725                                         infostream<<"Pointing at ("<<nodepos.X<<","
1726                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1727
1728                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1729                                         {
1730                                                 client.clearTempMod(nodepos_old);
1731                                                 dig_time = 0.0;
1732                                                 nodepos_old = v3s16(-32768,-32768,-32768);
1733                                         }
1734                                 }
1735
1736                                 if(input->getLeftClicked() ||
1737                                                 (input->getLeftState() && nodepos != nodepos_old))
1738                                 {
1739                                         infostream<<"Started digging"<<std::endl;
1740                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1741                                 }
1742                                 if(input->getLeftClicked())
1743                                 {
1744                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1745                                 }
1746                                 if(input->getLeftState())
1747                                 {
1748                                         MapNode n = client.getNode(nodepos);
1749                                 
1750                                         // Get tool name. Default is "" = bare hands
1751                                         std::string toolname = "";
1752                                         InventoryList *mlist = local_inventory.getList("main");
1753                                         if(mlist != NULL)
1754                                         {
1755                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1756                                                 if(item && (std::string)item->getName() == "ToolItem")
1757                                                 {
1758                                                         ToolItem *titem = (ToolItem*)item;
1759                                                         toolname = titem->getToolName();
1760                                                 }
1761                                         }
1762
1763                                         // Get digging properties for material and tool
1764                                         content_t material = n.getContent();
1765                                         DiggingProperties prop =
1766                                                         getDiggingProperties(material, toolname);
1767                                         
1768                                         float dig_time_complete = 0.0;
1769
1770                                         if(prop.diggable == false)
1771                                         {
1772                                                 /*infostream<<"Material "<<(int)material
1773                                                                 <<" not diggable with \""
1774                                                                 <<toolname<<"\""<<std::endl;*/
1775                                                 // I guess nobody will wait for this long
1776                                                 dig_time_complete = 10000000.0;
1777                                         }
1778                                         else
1779                                         {
1780                                                 dig_time_complete = prop.time;
1781                                         }
1782                                         
1783                                         if(dig_time_complete >= 0.001)
1784                                         {
1785                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1786                                                                 * dig_time/dig_time_complete);
1787                                         }
1788                                         // This is for torches
1789                                         else
1790                                         {
1791                                                 dig_index = CRACK_ANIMATION_LENGTH;
1792                                         }
1793
1794                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1795                                         {
1796                                                 //TimeTaker timer("client.setTempMod");
1797                                                 //infostream<<"dig_index="<<dig_index<<std::endl;
1798                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1799                                         }
1800                                         else
1801                                         {
1802                                                 infostream<<"Digging completed"<<std::endl;
1803                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1804                                                 client.clearTempMod(nodepos);
1805                                                 client.removeNode(nodepos);
1806
1807                                                 dig_time = 0;
1808
1809                                                 nodig_delay_counter = dig_time_complete
1810                                                                 / (float)CRACK_ANIMATION_LENGTH;
1811
1812                                                 // We don't want a corresponding delay to
1813                                                 // very time consuming nodes
1814                                                 if(nodig_delay_counter > 0.5)
1815                                                 {
1816                                                         nodig_delay_counter = 0.5;
1817                                                 }
1818                                                 // We want a slight delay to very little
1819                                                 // time consuming nodes
1820                                                 float mindelay = 0.15;
1821                                                 if(nodig_delay_counter < mindelay)
1822                                                 {
1823                                                         nodig_delay_counter = mindelay;
1824                                                 }
1825                                         }
1826
1827                                         dig_time += dtime;
1828
1829                                         camera.setDigging(0);  // left click animation
1830                                 }
1831                         }
1832                         
1833                         
1834                         if(input->getRightClicked())
1835                         {
1836                                 infostream<<"Ground right-clicked"<<std::endl;
1837                                 
1838                                 // If metadata provides an inventory view, activate it
1839                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
1840                                 {
1841                                         infostream<<"Launching custom inventory view"<<std::endl;
1842                                         /*
1843                                                 Construct the unique identification string of the node
1844                                         */
1845                                         std::string current_name;
1846                                         current_name += "nodemeta:";
1847                                         current_name += itos(nodepos.X);
1848                                         current_name += ",";
1849                                         current_name += itos(nodepos.Y);
1850                                         current_name += ",";
1851                                         current_name += itos(nodepos.Z);
1852                                         
1853                                         /*
1854                                                 Create menu
1855                                         */
1856
1857                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1858                                         v2s16 invsize =
1859                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
1860                                                         draw_spec,
1861                                                         meta->getInventoryDrawSpecString(),
1862                                                         current_name);
1863
1864                                         GUIInventoryMenu *menu =
1865                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1866                                                         &g_menumgr, invsize,
1867                                                         client.getInventoryContext(),
1868                                                         &client);
1869                                         menu->setDrawSpec(draw_spec);
1870                                         menu->drop();
1871                                 }
1872                                 else if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1873                                 {
1874                                         infostream<<"Sign node right-clicked"<<std::endl;
1875                                         
1876                                         SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1877                                         
1878                                         // Get a new text for it
1879
1880                                         TextDest *dest = new TextDestSignNode(nodepos, &client);
1881
1882                                         std::wstring wtext =
1883                                                         narrow_to_wide(signmeta->getText());
1884
1885                                         (new GUITextInputMenu(guienv, guiroot, -1,
1886                                                         &g_menumgr, dest,
1887                                                         wtext))->drop();
1888                                 }
1889                                 else
1890                                 {
1891                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1892                                         camera.setDigging(1);  // right click animation
1893                                 }
1894                         }
1895                         
1896                         nodepos_old = nodepos;
1897                 }
1898
1899                 } // selected_object == NULL
1900                 
1901                 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
1902                 {
1903                         camera.setDigging(0); // left click animation
1904                 }
1905
1906                 input->resetLeftClicked();
1907                 input->resetRightClicked();
1908                 
1909                 if(input->getLeftReleased())
1910                 {
1911                         infostream<<"Left button released (stopped digging)"
1912                                         <<std::endl;
1913                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1914                 }
1915                 if(input->getRightReleased())
1916                 {
1917                         //inostream<<DTIME<<"Right released"<<std::endl;
1918                         // Nothing here
1919                 }
1920                 
1921                 input->resetLeftReleased();
1922                 input->resetRightReleased();
1923                 
1924                 /*
1925                         Calculate stuff for drawing
1926                 */
1927
1928                 u32 daynight_ratio = client.getDayNightRatio();
1929                 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1930                 video::SColor bgcolor = video::SColor(
1931                                 255,
1932                                 bgcolor_bright.getRed() * l / 255,
1933                                 bgcolor_bright.getGreen() * l / 255,
1934                                 bgcolor_bright.getBlue() * l / 255);
1935                                 /*skycolor.getRed() * l / 255,
1936                                 skycolor.getGreen() * l / 255,
1937                                 skycolor.getBlue() * l / 255);*/
1938
1939                 float brightness = (float)l/255.0;
1940
1941                 /*
1942                         Update skybox
1943                 */
1944                 if(fabs(brightness - old_brightness) > 0.01)
1945                         update_skybox(driver, smgr, skybox, brightness);
1946
1947                 /*
1948                         Update clouds
1949                 */
1950                 if(clouds)
1951                 {
1952                         clouds->step(dtime);
1953                         clouds->update(v2f(player_position.X, player_position.Z),
1954                                         0.05+brightness*0.95);
1955                 }
1956                 
1957                 /*
1958                         Update farmesh
1959                 */
1960                 if(farmesh)
1961                 {
1962                         farmesh_range = draw_control.wanted_range * 10;
1963                         if(draw_control.range_all && farmesh_range < 500)
1964                                 farmesh_range = 500;
1965                         if(farmesh_range > 1000)
1966                                 farmesh_range = 1000;
1967
1968                         farmesh->step(dtime);
1969                         farmesh->update(v2f(player_position.X, player_position.Z),
1970                                         0.05+brightness*0.95, farmesh_range);
1971                 }
1972                 
1973                 // Store brightness value
1974                 old_brightness = brightness;
1975
1976                 /*
1977                         Fog
1978                 */
1979                 
1980                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
1981                 {
1982                         f32 range;
1983                         if(farmesh)
1984                         {
1985                                 range = BS*farmesh_range;
1986                         }
1987                         else
1988                         {
1989                                 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
1990                                 range *= 0.9;
1991                                 if(draw_control.range_all)
1992                                         range = 100000*BS;
1993                                 /*if(range < 50*BS)
1994                                         range = range * 0.5 + 25*BS;*/
1995                         }
1996
1997                         driver->setFog(
1998                                 bgcolor,
1999                                 video::EFT_FOG_LINEAR,
2000                                 range*0.4,
2001                                 range*1.0,
2002                                 0.01,
2003                                 false, // pixel fog
2004                                 false // range fog
2005                         );
2006                 }
2007                 else
2008                 {
2009                         driver->setFog(
2010                                 bgcolor,
2011                                 video::EFT_FOG_LINEAR,
2012                                 100000*BS,
2013                                 110000*BS,
2014                                 0.01,
2015                                 false, // pixel fog
2016                                 false // range fog
2017                         );
2018                 }
2019
2020                 /*
2021                         Update gui stuff (0ms)
2022                 */
2023
2024                 //TimeTaker guiupdatetimer("Gui updating");
2025                 
2026                 {
2027                         static float drawtime_avg = 0;
2028                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2029                         static float beginscenetime_avg = 0;
2030                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2031                         static float scenetime_avg = 0;
2032                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2033                         static float endscenetime_avg = 0;
2034                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
2035                         
2036                         char temptext[300];
2037                         snprintf(temptext, 300, "Minetest-c55 %s ("
2038                                         "R: range_all=%i"
2039                                         ")"
2040                                         " drawtime=%.0f, beginscenetime=%.0f"
2041                                         ", scenetime=%.0f, endscenetime=%.0f",
2042                                         VERSION_STRING,
2043                                         draw_control.range_all,
2044                                         drawtime_avg,
2045                                         beginscenetime_avg,
2046                                         scenetime_avg,
2047                                         endscenetime_avg
2048                                         );
2049                         
2050                         guitext->setText(narrow_to_wide(temptext).c_str());
2051                 }
2052                 
2053                 {
2054                         char temptext[300];
2055                         snprintf(temptext, 300,
2056                                         "(% .1f, % .1f, % .1f)"
2057                                         " (% .3f < btime_jitter < % .3f"
2058                                         ", dtime_jitter = % .1f %%"
2059                                         ", v_range = %.1f, RTT = %.3f)",
2060                                         player_position.X/BS,
2061                                         player_position.Y/BS,
2062                                         player_position.Z/BS,
2063                                         busytime_jitter1_min_sample,
2064                                         busytime_jitter1_max_sample,
2065                                         dtime_jitter1_max_fraction * 100.0,
2066                                         draw_control.wanted_range,
2067                                         client.getRTT()
2068                                         );
2069
2070                         guitext2->setText(narrow_to_wide(temptext).c_str());
2071                 }
2072                 
2073                 {
2074                         guitext_info->setText(infotext.c_str());
2075                 }
2076                 
2077                 /*
2078                         Get chat messages from client
2079                 */
2080                 {
2081                         // Get new messages
2082                         std::wstring message;
2083                         while(client.getChatMessage(message))
2084                         {
2085                                 chat_lines.push_back(ChatLine(message));
2086                                 /*if(chat_lines.size() > 6)
2087                                 {
2088                                         core::list<ChatLine>::Iterator
2089                                                         i = chat_lines.begin();
2090                                         chat_lines.erase(i);
2091                                 }*/
2092                         }
2093                         // Append them to form the whole static text and throw
2094                         // it to the gui element
2095                         std::wstring whole;
2096                         // This will correspond to the line number counted from
2097                         // top to bottom, from size-1 to 0
2098                         s16 line_number = chat_lines.size();
2099                         // Count of messages to be removed from the top
2100                         u16 to_be_removed_count = 0;
2101                         for(core::list<ChatLine>::Iterator
2102                                         i = chat_lines.begin();
2103                                         i != chat_lines.end(); i++)
2104                         {
2105                                 // After this, line number is valid for this loop
2106                                 line_number--;
2107                                 // Increment age
2108                                 (*i).age += dtime;
2109                                 /*
2110                                         This results in a maximum age of 60*6 to the
2111                                         lowermost line and a maximum of 6 lines
2112                                 */
2113                                 float allowed_age = (6-line_number) * 60.0;
2114
2115                                 if((*i).age > allowed_age)
2116                                 {
2117                                         to_be_removed_count++;
2118                                         continue;
2119                                 }
2120                                 whole += (*i).text + L'\n';
2121                         }
2122                         for(u16 i=0; i<to_be_removed_count; i++)
2123                         {
2124                                 core::list<ChatLine>::Iterator
2125                                                 it = chat_lines.begin();
2126                                 chat_lines.erase(it);
2127                         }
2128                         guitext_chat->setText(whole.c_str());
2129
2130                         // Update gui element size and position
2131
2132                         /*core::rect<s32> rect(
2133                                         10,
2134                                         screensize.Y - guitext_chat_pad_bottom
2135                                                         - text_height*chat_lines.size(),
2136                                         screensize.X - 10,
2137                                         screensize.Y - guitext_chat_pad_bottom
2138                         );*/
2139                         core::rect<s32> rect(
2140                                         10,
2141                                         50,
2142                                         screensize.X - 10,
2143                                         50 + guitext_chat->getTextHeight()
2144                         );
2145
2146                         guitext_chat->setRelativePosition(rect);
2147
2148                         // Don't show chat if empty or profiler is enabled
2149                         if(chat_lines.size() == 0 || show_profiler)
2150                                 guitext_chat->setVisible(false);
2151                         else
2152                                 guitext_chat->setVisible(true);
2153                 }
2154
2155                 /*
2156                         Inventory
2157                 */
2158                 
2159                 static u16 old_selected_item = 65535;
2160                 if(client.getLocalInventoryUpdated()
2161                                 || g_selected_item != old_selected_item)
2162                 {
2163                         client.selectPlayerItem(g_selected_item);
2164                         old_selected_item = g_selected_item;
2165                         //infostream<<"Updating local inventory"<<std::endl;
2166                         client.getLocalInventory(local_inventory);
2167
2168                         // Update wielded tool
2169                         InventoryList *mlist = local_inventory.getList("main");
2170                         InventoryItem *item = NULL;
2171                         if(mlist != NULL)
2172                                 item = mlist->getItem(g_selected_item);
2173                         camera.wield(item);
2174                 }
2175                 
2176                 /*
2177                         Send actions returned by the inventory menu
2178                 */
2179                 while(inventory_action_queue.size() != 0)
2180                 {
2181                         InventoryAction *a = inventory_action_queue.pop_front();
2182
2183                         client.sendInventoryAction(a);
2184                         // Eat it
2185                         delete a;
2186                 }
2187
2188                 /*
2189                         Drawing begins
2190                 */
2191
2192                 TimeTaker drawtimer("Drawing");
2193
2194                 
2195                 {
2196                         TimeTaker timer("beginScene");
2197                         driver->beginScene(true, true, bgcolor);
2198                         //driver->beginScene(false, true, bgcolor);
2199                         beginscenetime = timer.stop(true);
2200                 }
2201                 
2202                 //timer3.stop();
2203                 
2204                 //infostream<<"smgr->drawAll()"<<std::endl;
2205                 
2206                 {
2207                         TimeTaker timer("smgr");
2208                         smgr->drawAll();
2209                         scenetime = timer.stop(true);
2210                 }
2211                 
2212                 {
2213                 //TimeTaker timer9("auxiliary drawings");
2214                 // 0ms
2215                 
2216                 //timer9.stop();
2217                 //TimeTaker //timer10("//timer10");
2218                 
2219                 video::SMaterial m;
2220                 //m.Thickness = 10;
2221                 m.Thickness = 3;
2222                 m.Lighting = false;
2223                 driver->setMaterial(m);
2224
2225                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2226
2227                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
2228                                 i != hilightboxes.end(); i++)
2229                 {
2230                         /*infostream<<"hilightbox min="
2231                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2232                                         <<" max="
2233                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2234                                         <<std::endl;*/
2235                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
2236                 }
2237
2238                 /*
2239                         Wielded tool
2240                 */
2241                 {
2242                         // Warning: This clears the Z buffer.
2243                         camera.drawWieldedTool();
2244                 }
2245
2246                 /*
2247                         Post effects
2248                 */
2249                 {
2250                         client.renderPostFx();
2251                 }
2252
2253                 /*
2254                         Frametime log
2255                 */
2256                 if(g_settings->getBool("frametime_graph") == true)
2257                 {
2258                         s32 x = 10;
2259                         for(core::list<float>::Iterator
2260                                         i = frametime_log.begin();
2261                                         i != frametime_log.end();
2262                                         i++)
2263                         {
2264                                 driver->draw2DLine(v2s32(x,50),
2265                                                 v2s32(x,50+(*i)*1000),
2266                                                 video::SColor(255,255,255,255));
2267                                 x++;
2268                         }
2269                 }
2270
2271                 /*
2272                         Draw crosshair
2273                 */
2274                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2275                                 displaycenter + core::vector2d<s32>(10,0),
2276                                 video::SColor(255,255,255,255));
2277                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2278                                 displaycenter + core::vector2d<s32>(0,10),
2279                                 video::SColor(255,255,255,255));
2280
2281                 } // timer
2282
2283                 //timer10.stop();
2284                 //TimeTaker //timer11("//timer11");
2285
2286                 /*
2287                         Draw gui
2288                 */
2289                 // 0-1ms
2290                 guienv->drawAll();
2291
2292                 /*
2293                         Draw hotbar
2294                 */
2295                 {
2296                         draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
2297                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2298                                         client.getHP());
2299                 }
2300
2301                 /*
2302                         Damage flash
2303                 */
2304                 if(damage_flash_timer > 0.0)
2305                 {
2306                         damage_flash_timer -= dtime;
2307                         
2308                         video::SColor color(128,255,0,0);
2309                         driver->draw2DRectangle(color,
2310                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2311                                         NULL);
2312                 }
2313
2314                 /*
2315                         End scene
2316                 */
2317                 {
2318                         TimeTaker timer("endScene");
2319                         endSceneX(driver);
2320                         endscenetime = timer.stop(true);
2321                 }
2322
2323                 drawtime = drawtimer.stop(true);
2324
2325                 /*
2326                         End of drawing
2327                 */
2328
2329                 static s16 lastFPS = 0;
2330                 //u16 fps = driver->getFPS();
2331                 u16 fps = (1.0/dtime_avg1);
2332
2333                 if (lastFPS != fps)
2334                 {
2335                         core::stringw str = L"Minetest [";
2336                         str += driver->getName();
2337                         str += "] FPS=";
2338                         str += fps;
2339
2340                         device->setWindowCaption(str.c_str());
2341                         lastFPS = fps;
2342                 }
2343         }
2344
2345         /*
2346                 Drop stuff
2347         */
2348         if(clouds)
2349                 clouds->drop();
2350         
2351         /*
2352                 Draw a "shutting down" screen, which will be shown while the map
2353                 generator and other stuff quits
2354         */
2355         {
2356                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2357                 draw_load_screen(L"Shutting down stuff...", driver, font);
2358                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2359                 guienv->drawAll();
2360                 driver->endScene();
2361                 gui_shuttingdowntext->remove();*/
2362         }
2363 }
2364
2365