]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
Display RTT (round trip time, ping) on client status text
[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         
876         // At the middle of the screen
877         // Object infos are shown in this
878         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
879                         L"",
880                         core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
881                         false, false);
882         
883         // Chat text
884         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
885                         L"",
886                         core::rect<s32>(0,0,0,0),
887                         //false, false); // Disable word wrap as of now
888                         false, true);
889         //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
890         core::list<ChatLine> chat_lines;
891         
892         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
893                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
894         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
895                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
896         
897         // Test the text input system
898         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
899                         NULL))->drop();*/
900         /*GUIMessageMenu *menu =
901                         new GUIMessageMenu(guienv, guiroot, -1, 
902                                 &g_menumgr,
903                                 L"Asd");
904         menu->drop();*/
905         
906         // Launch pause menu
907         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
908                         &g_menumgr))->drop();
909         
910         // Enable texts
911         /*guitext2->setVisible(true);
912         guitext_info->setVisible(true);
913         guitext_chat->setVisible(true);*/
914
915         //s32 guitext_chat_pad_bottom = 70;
916
917         /*
918                 Some statistics are collected in these
919         */
920         u32 drawtime = 0;
921         u32 beginscenetime = 0;
922         u32 scenetime = 0;
923         u32 endscenetime = 0;
924         
925         // A test
926         //throw con::PeerNotFoundException("lol");
927
928         core::list<float> frametime_log;
929
930         float nodig_delay_counter = 0.0;
931         float dig_time = 0.0;
932         u16 dig_index = 0;
933         v3s16 nodepos_old(-32768,-32768,-32768);
934
935         float damage_flash_timer = 0;
936         s16 farmesh_range = 20*MAP_BLOCKSIZE;
937
938         const float object_hit_delay = 0.5;
939         float object_hit_delay_timer = 0.0;
940         
941         bool invert_mouse = g_settings->getBool("invert_mouse");
942
943         bool respawn_menu_active = false;
944
945         /*
946                 Main loop
947         */
948
949         bool first_loop_after_window_activation = true;
950
951         // TODO: Convert the static interval timers to these
952         // Interval limiter for profiler
953         IntervalLimiter m_profiler_interval;
954
955         // Time is in milliseconds
956         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
957         // NOTE: So we have to use getTime() and call run()s between them
958         u32 lasttime = device->getTimer()->getTime();
959
960         while(device->run() && kill == false)
961         {
962                 //std::cerr<<"frame"<<std::endl;
963
964                 if(client.accessDenied())
965                 {
966                         error_message = L"Access denied. Reason: "
967                                         +client.accessDeniedReason();
968                         errorstream<<wide_to_narrow(error_message)<<std::endl;
969                         break;
970                 }
971
972                 if(g_gamecallback->disconnect_requested)
973                 {
974                         g_gamecallback->disconnect_requested = false;
975                         break;
976                 }
977
978                 if(g_gamecallback->changepassword_requested)
979                 {
980                         (new GUIPasswordChange(guienv, guiroot, -1,
981                                 &g_menumgr, &client))->drop();
982                         g_gamecallback->changepassword_requested = false;
983                 }
984
985                 /*
986                         Process TextureSource's queue
987                 */
988                 ((TextureSource*)g_texturesource)->processQueue();
989
990                 /*
991                         Random calculations
992                 */
993                 last_screensize = screensize;
994                 screensize = driver->getScreenSize();
995                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
996                 //bool screensize_changed = screensize != last_screensize;
997
998                 // Resize hotbar
999                 if(screensize.Y <= 800)
1000                         hotbar_imagesize = 32;
1001                 else if(screensize.Y <= 1280)
1002                         hotbar_imagesize = 48;
1003                 else
1004                         hotbar_imagesize = 64;
1005                 
1006                 // Hilight boxes collected during the loop and displayed
1007                 core::list< core::aabbox3d<f32> > hilightboxes;
1008                 
1009                 // Info text
1010                 std::wstring infotext;
1011
1012                 // When screen size changes, update positions and sizes of stuff
1013                 /*if(screensize_changed)
1014                 {
1015                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
1016                         quick_inventory->updatePosition(pos);
1017                 }*/
1018
1019                 //TimeTaker //timer1("//timer1");
1020                 
1021                 // Time of frame without fps limit
1022                 float busytime;
1023                 u32 busytime_u32;
1024                 {
1025                         // not using getRealTime is necessary for wine
1026                         u32 time = device->getTimer()->getTime();
1027                         if(time > lasttime)
1028                                 busytime_u32 = time - lasttime;
1029                         else
1030                                 busytime_u32 = 0;
1031                         busytime = busytime_u32 / 1000.0;
1032                 }
1033
1034                 //infostream<<"busytime_u32="<<busytime_u32<<std::endl;
1035         
1036                 // Necessary for device->getTimer()->getTime()
1037                 device->run();
1038
1039                 /*
1040                         FPS limiter
1041                 */
1042
1043                 {
1044                         float fps_max = g_settings->getFloat("fps_max");
1045                         u32 frametime_min = 1000./fps_max;
1046                         
1047                         if(busytime_u32 < frametime_min)
1048                         {
1049                                 u32 sleeptime = frametime_min - busytime_u32;
1050                                 device->sleep(sleeptime);
1051                         }
1052                 }
1053
1054                 // Necessary for device->getTimer()->getTime()
1055                 device->run();
1056
1057                 /*
1058                         Time difference calculation
1059                 */
1060                 f32 dtime; // in seconds
1061                 
1062                 u32 time = device->getTimer()->getTime();
1063                 if(time > lasttime)
1064                         dtime = (time - lasttime) / 1000.0;
1065                 else
1066                         dtime = 0;
1067                 lasttime = time;
1068
1069                 /* Run timers */
1070
1071                 object_hit_delay_timer -= dtime;
1072
1073                 g_profiler->add("Elapsed time", dtime);
1074                 g_profiler->avg("FPS", 1./dtime);
1075
1076                 /*
1077                         Log frametime for visualization
1078                 */
1079                 frametime_log.push_back(dtime);
1080                 if(frametime_log.size() > 100)
1081                 {
1082                         core::list<float>::Iterator i = frametime_log.begin();
1083                         frametime_log.erase(i);
1084                 }
1085
1086                 /*
1087                         Visualize frametime in terminal
1088                 */
1089                 /*for(u32 i=0; i<dtime*400; i++)
1090                         infostream<<"X";
1091                 infostream<<std::endl;*/
1092
1093                 /*
1094                         Time average and jitter calculation
1095                 */
1096
1097                 static f32 dtime_avg1 = 0.0;
1098                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1099                 f32 dtime_jitter1 = dtime - dtime_avg1;
1100
1101                 static f32 dtime_jitter1_max_sample = 0.0;
1102                 static f32 dtime_jitter1_max_fraction = 0.0;
1103                 {
1104                         static f32 jitter1_max = 0.0;
1105                         static f32 counter = 0.0;
1106                         if(dtime_jitter1 > jitter1_max)
1107                                 jitter1_max = dtime_jitter1;
1108                         counter += dtime;
1109                         if(counter > 0.0)
1110                         {
1111                                 counter -= 3.0;
1112                                 dtime_jitter1_max_sample = jitter1_max;
1113                                 dtime_jitter1_max_fraction
1114                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1115                                 jitter1_max = 0.0;
1116                         }
1117                 }
1118                 
1119                 /*
1120                         Busytime average and jitter calculation
1121                 */
1122
1123                 static f32 busytime_avg1 = 0.0;
1124                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1125                 f32 busytime_jitter1 = busytime - busytime_avg1;
1126                 
1127                 static f32 busytime_jitter1_max_sample = 0.0;
1128                 static f32 busytime_jitter1_min_sample = 0.0;
1129                 {
1130                         static f32 jitter1_max = 0.0;
1131                         static f32 jitter1_min = 0.0;
1132                         static f32 counter = 0.0;
1133                         if(busytime_jitter1 > jitter1_max)
1134                                 jitter1_max = busytime_jitter1;
1135                         if(busytime_jitter1 < jitter1_min)
1136                                 jitter1_min = busytime_jitter1;
1137                         counter += dtime;
1138                         if(counter > 0.0){
1139                                 counter -= 3.0;
1140                                 busytime_jitter1_max_sample = jitter1_max;
1141                                 busytime_jitter1_min_sample = jitter1_min;
1142                                 jitter1_max = 0.0;
1143                                 jitter1_min = 0.0;
1144                         }
1145                 }
1146                 
1147                 /*
1148                         Debug info for client
1149                 */
1150                 {
1151                         static float counter = 0.0;
1152                         counter -= dtime;
1153                         if(counter < 0)
1154                         {
1155                                 counter = 30.0;
1156                                 client.printDebugInfo(infostream);
1157                         }
1158                 }
1159
1160                 /*
1161                         Profiler
1162                 */
1163                 float profiler_print_interval =
1164                                 g_settings->getFloat("profiler_print_interval");
1165                 if(profiler_print_interval != 0)
1166                 {
1167                         if(m_profiler_interval.step(0.030, profiler_print_interval))
1168                         {
1169                                 infostream<<"Profiler:"<<std::endl;
1170                                 g_profiler->print(infostream);
1171                                 g_profiler->clear();
1172                         }
1173                 }
1174
1175                 /*
1176                         Direct handling of user input
1177                 */
1178                 
1179                 // Reset input if window not active or some menu is active
1180                 if(device->isWindowActive() == false || noMenuActive() == false)
1181                 {
1182                         input->clear();
1183                 }
1184
1185                 // Input handler step() (used by the random input generator)
1186                 input->step(dtime);
1187
1188                 /*
1189                         Launch menus according to keys
1190                 */
1191                 if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1192                 {
1193                         infostream<<"the_game: "
1194                                         <<"Launching inventory"<<std::endl;
1195                         
1196                         GUIInventoryMenu *menu =
1197                                 new GUIInventoryMenu(guienv, guiroot, -1,
1198                                         &g_menumgr, v2s16(8,7),
1199                                         client.getInventoryContext(),
1200                                         &client);
1201
1202                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1203                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1204                                         "list", "current_player", "main",
1205                                         v2s32(0, 3), v2s32(8, 4)));
1206                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1207                                         "list", "current_player", "craft",
1208                                         v2s32(3, 0), v2s32(3, 3)));
1209                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1210                                         "list", "current_player", "craftresult",
1211                                         v2s32(7, 1), v2s32(1, 1)));
1212
1213                         menu->setDrawSpec(draw_spec);
1214
1215                         menu->drop();
1216                 }
1217                 else if(input->wasKeyDown(EscapeKey))
1218                 {
1219                         infostream<<"the_game: "
1220                                         <<"Launching pause menu"<<std::endl;
1221                         // It will delete itself by itself
1222                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1223                                         &g_menumgr))->drop();
1224
1225                         // Move mouse cursor on top of the disconnect button
1226                         input->setMousePos(displaycenter.X, displaycenter.Y+25);
1227                 }
1228                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1229                 {
1230                         TextDest *dest = new TextDestChat(&client);
1231
1232                         (new GUITextInputMenu(guienv, guiroot, -1,
1233                                         &g_menumgr, dest,
1234                                         L""))->drop();
1235                 }
1236                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1237                 {
1238                         TextDest *dest = new TextDestChat(&client);
1239
1240                         (new GUITextInputMenu(guienv, guiroot, -1,
1241                                         &g_menumgr, dest,
1242                                         L"/"))->drop();
1243                 }
1244                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1245                 {
1246                         if(g_settings->getBool("free_move"))
1247                         {
1248                                 g_settings->set("free_move","false");
1249                                 chat_lines.push_back(ChatLine(L"free_move disabled"));
1250                         }
1251                         else
1252                         {
1253                                 g_settings->set("free_move","true");
1254                                 chat_lines.push_back(ChatLine(L"free_move enabled"));
1255                         }
1256                 }
1257                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1258                 {
1259                         if(g_settings->getBool("fast_move"))
1260                         {
1261                                 g_settings->set("fast_move","false");
1262                                 chat_lines.push_back(ChatLine(L"fast_move disabled"));
1263                         }
1264                         else
1265                         {
1266                                 g_settings->set("fast_move","true");
1267                                 chat_lines.push_back(ChatLine(L"fast_move enabled"));
1268                         }
1269                 }
1270                 else if(input->wasKeyDown(getKeySetting("keymap_frametime_graph")))
1271                 {
1272                         if(g_settings->getBool("frametime_graph"))
1273                         {
1274                                 g_settings->set("frametime_graph","false");
1275                                 chat_lines.push_back(ChatLine(L"frametime_graph disabled"));
1276                         }
1277                         else
1278                         {
1279                                 g_settings->set("frametime_graph","true");
1280                                 chat_lines.push_back(ChatLine(L"frametime_graph enabled"));
1281                         }
1282                 }
1283                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1284                 {
1285                         irr::video::IImage* const image = driver->createScreenShot(); 
1286                         if (image) { 
1287                                 irr::c8 filename[256]; 
1288                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1289                                                  g_settings->get("screenshot_path").c_str(),
1290                                                  device->getTimer()->getRealTime()); 
1291                                 if (driver->writeImageToFile(image, filename)) {
1292                                         std::wstringstream sstr;
1293                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1294                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1295                                         chat_lines.push_back(ChatLine(sstr.str()));
1296                                 } else{
1297                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1298                                 }
1299                                 image->drop(); 
1300                         }                        
1301                 }
1302
1303                 // Item selection with mouse wheel
1304                 {
1305                         s32 wheel = input->getMouseWheel();
1306                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1307                                         hotbar_itemcount-1);
1308
1309                         if(wheel < 0)
1310                         {
1311                                 if(g_selected_item < max_item)
1312                                         g_selected_item++;
1313                                 else
1314                                         g_selected_item = 0;
1315                         }
1316                         else if(wheel > 0)
1317                         {
1318                                 if(g_selected_item > 0)
1319                                         g_selected_item--;
1320                                 else
1321                                         g_selected_item = max_item;
1322                         }
1323                 }
1324                 
1325                 // Item selection
1326                 for(u16 i=0; i<10; i++)
1327                 {
1328                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1329                         if(input->wasKeyDown(*kp))
1330                         {
1331                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1332                                 {
1333                                         g_selected_item = i;
1334
1335                                         infostream<<"Selected item: "
1336                                                         <<g_selected_item<<std::endl;
1337                                 }
1338                         }
1339                 }
1340
1341                 // Viewing range selection
1342                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1343                 {
1344                         if(draw_control.range_all)
1345                         {
1346                                 draw_control.range_all = false;
1347                                 infostream<<"Disabled full viewing range"<<std::endl;
1348                         }
1349                         else
1350                         {
1351                                 draw_control.range_all = true;
1352                                 infostream<<"Enabled full viewing range"<<std::endl;
1353                         }
1354                 }
1355
1356                 // Print debug stacks
1357                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1358                 {
1359                         dstream<<"-----------------------------------------"
1360                                         <<std::endl;
1361                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1362                         dstream<<"-----------------------------------------"
1363                                         <<std::endl;
1364                         debug_stacks_print();
1365                 }
1366
1367                 /*
1368                         Mouse and camera control
1369                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1370                 */
1371                 
1372                 if((device->isWindowActive() && noMenuActive()) || random_input)
1373                 {
1374                         if(!random_input)
1375                         {
1376                                 // Mac OSX gets upset if this is set every frame
1377                                 if(device->getCursorControl()->isVisible())
1378                                         device->getCursorControl()->setVisible(false);
1379                         }
1380
1381                         if(first_loop_after_window_activation){
1382                                 //infostream<<"window active, first loop"<<std::endl;
1383                                 first_loop_after_window_activation = false;
1384                         }
1385                         else{
1386                                 s32 dx = input->getMousePos().X - displaycenter.X;
1387                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1388                                 if(invert_mouse)
1389                                         dy = -dy;
1390                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1391                                 
1392                                 /*const float keyspeed = 500;
1393                                 if(input->isKeyDown(irr::KEY_UP))
1394                                         dy -= dtime * keyspeed;
1395                                 if(input->isKeyDown(irr::KEY_DOWN))
1396                                         dy += dtime * keyspeed;
1397                                 if(input->isKeyDown(irr::KEY_LEFT))
1398                                         dx -= dtime * keyspeed;
1399                                 if(input->isKeyDown(irr::KEY_RIGHT))
1400                                         dx += dtime * keyspeed;*/
1401
1402                                 camera_yaw -= dx*0.2;
1403                                 camera_pitch += dy*0.2;
1404                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1405                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1406                         }
1407                         input->setMousePos(displaycenter.X, displaycenter.Y);
1408                 }
1409                 else{
1410                         // Mac OSX gets upset if this is set every frame
1411                         if(device->getCursorControl()->isVisible() == false)
1412                                 device->getCursorControl()->setVisible(true);
1413
1414                         //infostream<<"window inactive"<<std::endl;
1415                         first_loop_after_window_activation = true;
1416                 }
1417
1418                 /*
1419                         Player speed control
1420                 */
1421                 
1422                 if(!noMenuActive() || !device->isWindowActive())
1423                 {
1424                         PlayerControl control(
1425                                 false,
1426                                 false,
1427                                 false,
1428                                 false,
1429                                 false,
1430                                 false,
1431                                 false,
1432                                 camera_pitch,
1433                                 camera_yaw
1434                         );
1435                         client.setPlayerControl(control);
1436                 }
1437                 else
1438                 {
1439                         /*bool a_up,
1440                         bool a_down,
1441                         bool a_left,
1442                         bool a_right,
1443                         bool a_jump,
1444                         bool a_superspeed,
1445                         bool a_sneak,
1446                         float a_pitch,
1447                         float a_yaw*/
1448                         PlayerControl control(
1449                                 input->isKeyDown(getKeySetting("keymap_forward")),
1450                                 input->isKeyDown(getKeySetting("keymap_backward")),
1451                                 input->isKeyDown(getKeySetting("keymap_left")),
1452                                 input->isKeyDown(getKeySetting("keymap_right")),
1453                                 input->isKeyDown(getKeySetting("keymap_jump")),
1454                                 input->isKeyDown(getKeySetting("keymap_special1")),
1455                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1456                                 camera_pitch,
1457                                 camera_yaw
1458                         );
1459                         client.setPlayerControl(control);
1460                 }
1461                 
1462                 /*
1463                         Run server
1464                 */
1465
1466                 if(server != NULL)
1467                 {
1468                         //TimeTaker timer("server->step(dtime)");
1469                         server->step(dtime);
1470                 }
1471
1472                 /*
1473                         Process environment
1474                 */
1475                 
1476                 {
1477                         //TimeTaker timer("client.step(dtime)");
1478                         client.step(dtime);
1479                         //client.step(dtime_avg1);
1480                 }
1481
1482                 {
1483                         // Read client events
1484                         for(;;)
1485                         {
1486                                 ClientEvent event = client.getClientEvent();
1487                                 if(event.type == CE_NONE)
1488                                 {
1489                                         break;
1490                                 }
1491                                 else if(event.type == CE_PLAYER_DAMAGE)
1492                                 {
1493                                         //u16 damage = event.player_damage.amount;
1494                                         //infostream<<"Player damage: "<<damage<<std::endl;
1495                                         damage_flash_timer = 0.05;
1496                                         if(event.player_damage.amount >= 2){
1497                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1498                                         }
1499                                 }
1500                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1501                                 {
1502                                         camera_yaw = event.player_force_move.yaw;
1503                                         camera_pitch = event.player_force_move.pitch;
1504                                 }
1505                                 else if(event.type == CE_DEATHSCREEN)
1506                                 {
1507                                         if(respawn_menu_active)
1508                                                 continue;
1509
1510                                         /*bool set_camera_point_target =
1511                                                         event.deathscreen.set_camera_point_target;
1512                                         v3f camera_point_target;
1513                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1514                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1515                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1516                                         MainRespawnInitiator *respawner =
1517                                                         new MainRespawnInitiator(
1518                                                                         &respawn_menu_active, &client);
1519                                         GUIDeathScreen *menu =
1520                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1521                                                                 &g_menumgr, respawner);
1522                                         menu->drop();
1523                                         
1524                                         /* Handle visualization */
1525
1526                                         damage_flash_timer = 0;
1527
1528                                         /*LocalPlayer* player = client.getLocalPlayer();
1529                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1530                                         camera.update(player, busytime, screensize);*/
1531                                 }
1532                         }
1533                 }
1534                 
1535                 //TimeTaker //timer2("//timer2");
1536
1537                 LocalPlayer* player = client.getLocalPlayer();
1538                 camera.update(player, busytime, screensize);
1539                 camera.step(dtime);
1540
1541                 v3f player_position = player->getPosition();
1542                 v3f camera_position = camera.getPosition();
1543                 v3f camera_direction = camera.getDirection();
1544                 f32 camera_fov = camera.getFovMax();
1545                 
1546                 if(FIELD_OF_VIEW_TEST)
1547                         client.updateCamera(v3f(0,0,0), v3f(0,0,1), camera_fov);
1548                 else
1549                         client.updateCamera(camera_position,
1550                                 camera_direction, camera_fov);
1551
1552                 //timer2.stop();
1553                 //TimeTaker //timer3("//timer3");
1554
1555                 /*
1556                         Calculate what block is the crosshair pointing to
1557                 */
1558                 
1559                 //u32 t1 = device->getTimer()->getRealTime();
1560                 
1561                 //f32 d = 4; // max. distance
1562                 f32 d = 4; // max. distance
1563                 core::line3d<f32> shootline(camera_position,
1564                                 camera_position + camera_direction * BS * (d+1));
1565
1566                 ClientActiveObject *selected_active_object
1567                                 = client.getSelectedActiveObject
1568                                         (d*BS, camera_position, shootline);
1569                 
1570                 bool left_punch = false;
1571                 bool left_punch_muted = false;
1572
1573                 if(selected_active_object != NULL)
1574                 {
1575                         /* Clear possible cracking animation */
1576                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1577                         {
1578                                 client.clearTempMod(nodepos_old);
1579                                 dig_time = 0.0;
1580                                 nodepos_old = v3s16(-32768,-32768,-32768);
1581                         }
1582
1583                         //infostream<<"Client returned selected_active_object != NULL"<<std::endl;
1584                         
1585                         core::aabbox3d<f32> *selection_box
1586                                         = selected_active_object->getSelectionBox();
1587                         // Box should exist because object was returned in the
1588                         // first place
1589                         assert(selection_box);
1590
1591                         v3f pos = selected_active_object->getPosition();
1592
1593                         core::aabbox3d<f32> box_on_map(
1594                                         selection_box->MinEdge + pos,
1595                                         selection_box->MaxEdge + pos
1596                         );
1597                         
1598                         if(selected_active_object->doShowSelectionBox())
1599                                 hilightboxes.push_back(box_on_map);
1600
1601                         //infotext = narrow_to_wide("A ClientActiveObject");
1602                         infotext = narrow_to_wide(selected_active_object->infoText());
1603
1604                         //if(input->getLeftClicked())
1605                         if(input->getLeftState())
1606                         {
1607                                 bool do_punch = false;
1608                                 bool do_punch_damage = false;
1609                                 if(object_hit_delay_timer <= 0.0){
1610                                         do_punch = true;
1611                                         do_punch_damage = true;
1612                                         object_hit_delay_timer = object_hit_delay;
1613                                 }
1614                                 if(input->getLeftClicked()){
1615                                         do_punch = true;
1616                                 }
1617                                 if(do_punch){
1618                                         infostream<<"Left-clicked object"<<std::endl;
1619                                         left_punch = true;
1620                                 }
1621                                 if(do_punch_damage){
1622                                         client.clickActiveObject(0,
1623                                                         selected_active_object->getId(), g_selected_item);
1624                                 }
1625                         }
1626                         else if(input->getRightClicked())
1627                         {
1628                                 infostream<<"Right-clicked object"<<std::endl;
1629                                 client.clickActiveObject(1,
1630                                                 selected_active_object->getId(), g_selected_item);
1631                         }
1632                 }
1633                 else // selected_object == NULL
1634                 {
1635
1636                 /*
1637                         Find out which node we are pointing at
1638                 */
1639                 
1640                 bool nodefound = false;
1641                 v3s16 nodepos;
1642                 v3s16 neighbourpos;
1643                 core::aabbox3d<f32> nodehilightbox;
1644
1645                 getPointedNode(&client, player_position,
1646                                 camera_direction, camera_position,
1647                                 nodefound, shootline,
1648                                 nodepos, neighbourpos,
1649                                 nodehilightbox, d);
1650         
1651                 if(!nodefound){
1652                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1653                         {
1654                                 client.clearTempMod(nodepos_old);
1655                                 dig_time = 0.0;
1656                                 nodepos_old = v3s16(-32768,-32768,-32768);
1657                         }
1658                 } else {
1659                         /*
1660                                 Visualize selection
1661                         */
1662
1663                         hilightboxes.push_back(nodehilightbox);
1664
1665                         /*
1666                                 Check information text of node
1667                         */
1668
1669                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1670                         if(meta)
1671                         {
1672                                 infotext = narrow_to_wide(meta->infoText());
1673                         }
1674                         
1675                         //MapNode node = client.getNode(nodepos);
1676
1677                         /*
1678                                 Handle digging
1679                         */
1680                         
1681                         if(input->getLeftReleased())
1682                         {
1683                                 client.clearTempMod(nodepos);
1684                                 dig_time = 0.0;
1685                         }
1686                         
1687                         if(nodig_delay_counter > 0.0)
1688                         {
1689                                 nodig_delay_counter -= dtime;
1690                         }
1691                         else
1692                         {
1693                                 if(nodepos != nodepos_old)
1694                                 {
1695                                         infostream<<"Pointing at ("<<nodepos.X<<","
1696                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1697
1698                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1699                                         {
1700                                                 client.clearTempMod(nodepos_old);
1701                                                 dig_time = 0.0;
1702                                                 nodepos_old = v3s16(-32768,-32768,-32768);
1703                                         }
1704                                 }
1705
1706                                 if(input->getLeftClicked() ||
1707                                                 (input->getLeftState() && nodepos != nodepos_old))
1708                                 {
1709                                         infostream<<"Started digging"<<std::endl;
1710                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1711                                 }
1712                                 if(input->getLeftClicked())
1713                                 {
1714                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1715                                 }
1716                                 if(input->getLeftState())
1717                                 {
1718                                         MapNode n = client.getNode(nodepos);
1719                                 
1720                                         // Get tool name. Default is "" = bare hands
1721                                         std::string toolname = "";
1722                                         InventoryList *mlist = local_inventory.getList("main");
1723                                         if(mlist != NULL)
1724                                         {
1725                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1726                                                 if(item && (std::string)item->getName() == "ToolItem")
1727                                                 {
1728                                                         ToolItem *titem = (ToolItem*)item;
1729                                                         toolname = titem->getToolName();
1730                                                 }
1731                                         }
1732
1733                                         // Get digging properties for material and tool
1734                                         content_t material = n.getContent();
1735                                         DiggingProperties prop =
1736                                                         getDiggingProperties(material, toolname);
1737                                         
1738                                         float dig_time_complete = 0.0;
1739
1740                                         if(prop.diggable == false)
1741                                         {
1742                                                 /*infostream<<"Material "<<(int)material
1743                                                                 <<" not diggable with \""
1744                                                                 <<toolname<<"\""<<std::endl;*/
1745                                                 // I guess nobody will wait for this long
1746                                                 dig_time_complete = 10000000.0;
1747                                         }
1748                                         else
1749                                         {
1750                                                 dig_time_complete = prop.time;
1751                                         }
1752                                         
1753                                         if(dig_time_complete >= 0.001)
1754                                         {
1755                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1756                                                                 * dig_time/dig_time_complete);
1757                                         }
1758                                         // This is for torches
1759                                         else
1760                                         {
1761                                                 dig_index = CRACK_ANIMATION_LENGTH;
1762                                         }
1763
1764                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1765                                         {
1766                                                 //TimeTaker timer("client.setTempMod");
1767                                                 //infostream<<"dig_index="<<dig_index<<std::endl;
1768                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1769                                         }
1770                                         else
1771                                         {
1772                                                 infostream<<"Digging completed"<<std::endl;
1773                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1774                                                 client.clearTempMod(nodepos);
1775                                                 client.removeNode(nodepos);
1776
1777                                                 dig_time = 0;
1778
1779                                                 nodig_delay_counter = dig_time_complete
1780                                                                 / (float)CRACK_ANIMATION_LENGTH;
1781
1782                                                 // We don't want a corresponding delay to
1783                                                 // very time consuming nodes
1784                                                 if(nodig_delay_counter > 0.5)
1785                                                 {
1786                                                         nodig_delay_counter = 0.5;
1787                                                 }
1788                                                 // We want a slight delay to very little
1789                                                 // time consuming nodes
1790                                                 float mindelay = 0.15;
1791                                                 if(nodig_delay_counter < mindelay)
1792                                                 {
1793                                                         nodig_delay_counter = mindelay;
1794                                                 }
1795                                         }
1796
1797                                         dig_time += dtime;
1798
1799                                         camera.setDigging(0);  // left click animation
1800                                 }
1801                         }
1802                         
1803                         
1804                         if(input->getRightClicked())
1805                         {
1806                                 infostream<<"Ground right-clicked"<<std::endl;
1807                                 
1808                                 // If metadata provides an inventory view, activate it
1809                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
1810                                 {
1811                                         infostream<<"Launching custom inventory view"<<std::endl;
1812                                         /*
1813                                                 Construct the unique identification string of the node
1814                                         */
1815                                         std::string current_name;
1816                                         current_name += "nodemeta:";
1817                                         current_name += itos(nodepos.X);
1818                                         current_name += ",";
1819                                         current_name += itos(nodepos.Y);
1820                                         current_name += ",";
1821                                         current_name += itos(nodepos.Z);
1822                                         
1823                                         /*
1824                                                 Create menu
1825                                         */
1826
1827                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1828                                         v2s16 invsize =
1829                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
1830                                                         draw_spec,
1831                                                         meta->getInventoryDrawSpecString(),
1832                                                         current_name);
1833
1834                                         GUIInventoryMenu *menu =
1835                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1836                                                         &g_menumgr, invsize,
1837                                                         client.getInventoryContext(),
1838                                                         &client);
1839                                         menu->setDrawSpec(draw_spec);
1840                                         menu->drop();
1841                                 }
1842                                 else if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1843                                 {
1844                                         infostream<<"Sign node right-clicked"<<std::endl;
1845                                         
1846                                         SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1847                                         
1848                                         // Get a new text for it
1849
1850                                         TextDest *dest = new TextDestSignNode(nodepos, &client);
1851
1852                                         std::wstring wtext =
1853                                                         narrow_to_wide(signmeta->getText());
1854
1855                                         (new GUITextInputMenu(guienv, guiroot, -1,
1856                                                         &g_menumgr, dest,
1857                                                         wtext))->drop();
1858                                 }
1859                                 else
1860                                 {
1861                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1862                                         camera.setDigging(1);  // right click animation
1863                                 }
1864                         }
1865                         
1866                         nodepos_old = nodepos;
1867                 }
1868
1869                 } // selected_object == NULL
1870                 
1871                 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
1872                 {
1873                         camera.setDigging(0); // left click animation
1874                 }
1875
1876                 input->resetLeftClicked();
1877                 input->resetRightClicked();
1878                 
1879                 if(input->getLeftReleased())
1880                 {
1881                         infostream<<"Left button released (stopped digging)"
1882                                         <<std::endl;
1883                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1884                 }
1885                 if(input->getRightReleased())
1886                 {
1887                         //inostream<<DTIME<<"Right released"<<std::endl;
1888                         // Nothing here
1889                 }
1890                 
1891                 input->resetLeftReleased();
1892                 input->resetRightReleased();
1893                 
1894                 /*
1895                         Calculate stuff for drawing
1896                 */
1897
1898                 u32 daynight_ratio = client.getDayNightRatio();
1899                 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1900                 video::SColor bgcolor = video::SColor(
1901                                 255,
1902                                 bgcolor_bright.getRed() * l / 255,
1903                                 bgcolor_bright.getGreen() * l / 255,
1904                                 bgcolor_bright.getBlue() * l / 255);
1905                                 /*skycolor.getRed() * l / 255,
1906                                 skycolor.getGreen() * l / 255,
1907                                 skycolor.getBlue() * l / 255);*/
1908
1909                 float brightness = (float)l/255.0;
1910
1911                 /*
1912                         Update skybox
1913                 */
1914                 if(fabs(brightness - old_brightness) > 0.01)
1915                         update_skybox(driver, smgr, skybox, brightness);
1916
1917                 /*
1918                         Update clouds
1919                 */
1920                 if(clouds)
1921                 {
1922                         clouds->step(dtime);
1923                         clouds->update(v2f(player_position.X, player_position.Z),
1924                                         0.05+brightness*0.95);
1925                 }
1926                 
1927                 /*
1928                         Update farmesh
1929                 */
1930                 if(farmesh)
1931                 {
1932                         farmesh_range = draw_control.wanted_range * 10;
1933                         if(draw_control.range_all && farmesh_range < 500)
1934                                 farmesh_range = 500;
1935                         if(farmesh_range > 1000)
1936                                 farmesh_range = 1000;
1937
1938                         farmesh->step(dtime);
1939                         farmesh->update(v2f(player_position.X, player_position.Z),
1940                                         0.05+brightness*0.95, farmesh_range);
1941                 }
1942                 
1943                 // Store brightness value
1944                 old_brightness = brightness;
1945
1946                 /*
1947                         Fog
1948                 */
1949                 
1950                 if(g_settings->getBool("enable_fog") == true)
1951                 {
1952                         f32 range;
1953                         if(farmesh)
1954                         {
1955                                 range = BS*farmesh_range;
1956                         }
1957                         else
1958                         {
1959                                 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
1960                                 if(draw_control.range_all)
1961                                         range = 100000*BS;
1962                                 if(range < 50*BS)
1963                                         range = range * 0.5 + 25*BS;
1964                         }
1965
1966                         driver->setFog(
1967                                 bgcolor,
1968                                 video::EFT_FOG_LINEAR,
1969                                 range*0.4,
1970                                 range*1.0,
1971                                 0.01,
1972                                 false, // pixel fog
1973                                 false // range fog
1974                         );
1975                 }
1976                 else
1977                 {
1978                         driver->setFog(
1979                                 bgcolor,
1980                                 video::EFT_FOG_LINEAR,
1981                                 100000*BS,
1982                                 110000*BS,
1983                                 0.01,
1984                                 false, // pixel fog
1985                                 false // range fog
1986                         );
1987                 }
1988
1989                 /*
1990                         Update gui stuff (0ms)
1991                 */
1992
1993                 //TimeTaker guiupdatetimer("Gui updating");
1994                 
1995                 {
1996                         static float drawtime_avg = 0;
1997                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
1998                         static float beginscenetime_avg = 0;
1999                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2000                         static float scenetime_avg = 0;
2001                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2002                         static float endscenetime_avg = 0;
2003                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
2004                         
2005                         char temptext[300];
2006                         snprintf(temptext, 300, "Minetest-c55 %s ("
2007                                         "R: range_all=%i"
2008                                         ")"
2009                                         " drawtime=%.0f, beginscenetime=%.0f"
2010                                         ", scenetime=%.0f, endscenetime=%.0f",
2011                                         VERSION_STRING,
2012                                         draw_control.range_all,
2013                                         drawtime_avg,
2014                                         beginscenetime_avg,
2015                                         scenetime_avg,
2016                                         endscenetime_avg
2017                                         );
2018                         
2019                         guitext->setText(narrow_to_wide(temptext).c_str());
2020                 }
2021                 
2022                 {
2023                         char temptext[300];
2024                         snprintf(temptext, 300,
2025                                         "(% .1f, % .1f, % .1f)"
2026                                         " (% .3f < btime_jitter < % .3f"
2027                                         ", dtime_jitter = % .1f %%"
2028                                         ", v_range = %.1f, RTT = %.3f)",
2029                                         player_position.X/BS,
2030                                         player_position.Y/BS,
2031                                         player_position.Z/BS,
2032                                         busytime_jitter1_min_sample,
2033                                         busytime_jitter1_max_sample,
2034                                         dtime_jitter1_max_fraction * 100.0,
2035                                         draw_control.wanted_range,
2036                                         client.getRTT()
2037                                         );
2038
2039                         guitext2->setText(narrow_to_wide(temptext).c_str());
2040                 }
2041                 
2042                 {
2043                         guitext_info->setText(infotext.c_str());
2044                 }
2045                 
2046                 /*
2047                         Get chat messages from client
2048                 */
2049                 {
2050                         // Get new messages
2051                         std::wstring message;
2052                         while(client.getChatMessage(message))
2053                         {
2054                                 chat_lines.push_back(ChatLine(message));
2055                                 /*if(chat_lines.size() > 6)
2056                                 {
2057                                         core::list<ChatLine>::Iterator
2058                                                         i = chat_lines.begin();
2059                                         chat_lines.erase(i);
2060                                 }*/
2061                         }
2062                         // Append them to form the whole static text and throw
2063                         // it to the gui element
2064                         std::wstring whole;
2065                         // This will correspond to the line number counted from
2066                         // top to bottom, from size-1 to 0
2067                         s16 line_number = chat_lines.size();
2068                         // Count of messages to be removed from the top
2069                         u16 to_be_removed_count = 0;
2070                         for(core::list<ChatLine>::Iterator
2071                                         i = chat_lines.begin();
2072                                         i != chat_lines.end(); i++)
2073                         {
2074                                 // After this, line number is valid for this loop
2075                                 line_number--;
2076                                 // Increment age
2077                                 (*i).age += dtime;
2078                                 /*
2079                                         This results in a maximum age of 60*6 to the
2080                                         lowermost line and a maximum of 6 lines
2081                                 */
2082                                 float allowed_age = (6-line_number) * 60.0;
2083
2084                                 if((*i).age > allowed_age)
2085                                 {
2086                                         to_be_removed_count++;
2087                                         continue;
2088                                 }
2089                                 whole += (*i).text + L'\n';
2090                         }
2091                         for(u16 i=0; i<to_be_removed_count; i++)
2092                         {
2093                                 core::list<ChatLine>::Iterator
2094                                                 it = chat_lines.begin();
2095                                 chat_lines.erase(it);
2096                         }
2097                         guitext_chat->setText(whole.c_str());
2098
2099                         // Update gui element size and position
2100
2101                         /*core::rect<s32> rect(
2102                                         10,
2103                                         screensize.Y - guitext_chat_pad_bottom
2104                                                         - text_height*chat_lines.size(),
2105                                         screensize.X - 10,
2106                                         screensize.Y - guitext_chat_pad_bottom
2107                         );*/
2108                         core::rect<s32> rect(
2109                                         10,
2110                                         50,
2111                                         screensize.X - 10,
2112                                         50 + guitext_chat->getTextHeight()
2113                         );
2114
2115                         guitext_chat->setRelativePosition(rect);
2116
2117                         if(chat_lines.size() == 0)
2118                                 guitext_chat->setVisible(false);
2119                         else
2120                                 guitext_chat->setVisible(true);
2121                 }
2122
2123                 /*
2124                         Inventory
2125                 */
2126                 
2127                 static u16 old_selected_item = 65535;
2128                 if(client.getLocalInventoryUpdated()
2129                                 || g_selected_item != old_selected_item)
2130                 {
2131                         client.selectPlayerItem(g_selected_item);
2132                         old_selected_item = g_selected_item;
2133                         //infostream<<"Updating local inventory"<<std::endl;
2134                         client.getLocalInventory(local_inventory);
2135
2136                         // Update wielded tool
2137                         InventoryList *mlist = local_inventory.getList("main");
2138                         InventoryItem *item = NULL;
2139                         if(mlist != NULL)
2140                                 item = mlist->getItem(g_selected_item);
2141                         camera.wield(item);
2142                 }
2143                 
2144                 /*
2145                         Send actions returned by the inventory menu
2146                 */
2147                 while(inventory_action_queue.size() != 0)
2148                 {
2149                         InventoryAction *a = inventory_action_queue.pop_front();
2150
2151                         client.sendInventoryAction(a);
2152                         // Eat it
2153                         delete a;
2154                 }
2155
2156                 /*
2157                         Drawing begins
2158                 */
2159
2160                 TimeTaker drawtimer("Drawing");
2161
2162                 
2163                 {
2164                         TimeTaker timer("beginScene");
2165                         driver->beginScene(true, true, bgcolor);
2166                         //driver->beginScene(false, true, bgcolor);
2167                         beginscenetime = timer.stop(true);
2168                 }
2169                 
2170                 //timer3.stop();
2171                 
2172                 //infostream<<"smgr->drawAll()"<<std::endl;
2173                 
2174                 {
2175                         TimeTaker timer("smgr");
2176                         smgr->drawAll();
2177                         scenetime = timer.stop(true);
2178                 }
2179                 
2180                 {
2181                 //TimeTaker timer9("auxiliary drawings");
2182                 // 0ms
2183                 
2184                 //timer9.stop();
2185                 //TimeTaker //timer10("//timer10");
2186                 
2187                 video::SMaterial m;
2188                 //m.Thickness = 10;
2189                 m.Thickness = 3;
2190                 m.Lighting = false;
2191                 driver->setMaterial(m);
2192
2193                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2194
2195                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
2196                                 i != hilightboxes.end(); i++)
2197                 {
2198                         /*infostream<<"hilightbox min="
2199                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2200                                         <<" max="
2201                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2202                                         <<std::endl;*/
2203                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
2204                 }
2205
2206                 /*
2207                         Wielded tool
2208                 */
2209                 {
2210                         // Warning: This clears the Z buffer.
2211                         camera.drawWieldedTool();
2212                 }
2213
2214                 /*
2215                         Post effects
2216                 */
2217                 {
2218                         client.renderPostFx();
2219                 }
2220
2221                 /*
2222                         Frametime log
2223                 */
2224                 if(g_settings->getBool("frametime_graph") == true)
2225                 {
2226                         s32 x = 10;
2227                         for(core::list<float>::Iterator
2228                                         i = frametime_log.begin();
2229                                         i != frametime_log.end();
2230                                         i++)
2231                         {
2232                                 driver->draw2DLine(v2s32(x,50),
2233                                                 v2s32(x,50+(*i)*1000),
2234                                                 video::SColor(255,255,255,255));
2235                                 x++;
2236                         }
2237                 }
2238
2239                 /*
2240                         Draw crosshair
2241                 */
2242                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2243                                 displaycenter + core::vector2d<s32>(10,0),
2244                                 video::SColor(255,255,255,255));
2245                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2246                                 displaycenter + core::vector2d<s32>(0,10),
2247                                 video::SColor(255,255,255,255));
2248
2249                 } // timer
2250
2251                 //timer10.stop();
2252                 //TimeTaker //timer11("//timer11");
2253
2254                 /*
2255                         Draw gui
2256                 */
2257                 // 0-1ms
2258                 guienv->drawAll();
2259
2260                 /*
2261                         Draw hotbar
2262                 */
2263                 {
2264                         draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
2265                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2266                                         client.getHP());
2267                 }
2268
2269                 /*
2270                         Damage flash
2271                 */
2272                 if(damage_flash_timer > 0.0)
2273                 {
2274                         damage_flash_timer -= dtime;
2275                         
2276                         video::SColor color(128,255,0,0);
2277                         driver->draw2DRectangle(color,
2278                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2279                                         NULL);
2280                 }
2281
2282                 /*
2283                         End scene
2284                 */
2285                 {
2286                         TimeTaker timer("endScene");
2287                         endSceneX(driver);
2288                         endscenetime = timer.stop(true);
2289                 }
2290
2291                 drawtime = drawtimer.stop(true);
2292
2293                 /*
2294                         End of drawing
2295                 */
2296
2297                 static s16 lastFPS = 0;
2298                 //u16 fps = driver->getFPS();
2299                 u16 fps = (1.0/dtime_avg1);
2300
2301                 if (lastFPS != fps)
2302                 {
2303                         core::stringw str = L"Minetest [";
2304                         str += driver->getName();
2305                         str += "] FPS=";
2306                         str += fps;
2307
2308                         device->setWindowCaption(str.c_str());
2309                         lastFPS = fps;
2310                 }
2311         }
2312
2313         /*
2314                 Drop stuff
2315         */
2316         if(clouds)
2317                 clouds->drop();
2318         
2319         /*
2320                 Draw a "shutting down" screen, which will be shown while the map
2321                 generator and other stuff quits
2322         */
2323         {
2324                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2325                 draw_load_screen(L"Shutting down stuff...", driver, font);
2326                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2327                 guienv->drawAll();
2328                 driver->endScene();
2329                 gui_shuttingdowntext->remove();*/
2330         }
2331 }
2332
2333