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