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