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