Merge branch 'master' of https://github.com/erlehmann/minetest-delta.git into upstrea...
[oweals/minetest.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                 else if(n.d == CONTENT_RAIL)
538                 {
539                         v3s16 dir = unpackDir(n.dir);
540                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
541                         dir_f *= BS/2 - BS/6 - BS/20;
542                         v3f cpf = npf + dir_f;
543                         f32 distance = (cpf - camera_position).getLength();
544
545                         float d = (float)BS/16;
546                         v3f vertices[4] =
547                         {
548                                 v3f(BS/2, -BS/2+d, -BS/2),
549                                 v3f(-BS/2, -BS/2, BS/2),
550                         };
551
552                         for(s32 i=0; i<2; i++)
553                         {
554                                 vertices[i] += npf;
555                         }
556
557                         core::aabbox3d<f32> box;
558
559                         box = core::aabbox3d<f32>(vertices[0]);
560                         box.addInternalPoint(vertices[1]);
561
562                         if(distance < mindistance)
563                         {
564                                 if(box.intersectsWithLine(shootline))
565                                 {
566                                         nodefound = true;
567                                         nodepos = np;
568                                         neighbourpos = np;
569                                         mindistance = distance;
570                                         nodehilightbox = box;
571                                 }
572                         }
573                 }
574                 /*
575                         Regular blocks
576                 */
577                 else
578                 {
579                         for(u16 i=0; i<6; i++)
580                         {
581                                 v3f dir_f = v3f(dirs[i].X,
582                                                 dirs[i].Y, dirs[i].Z);
583                                 v3f centerpoint = npf + dir_f * BS/2;
584                                 f32 distance =
585                                                 (centerpoint - camera_position).getLength();
586                                 
587                                 if(distance < mindistance)
588                                 {
589                                         core::CMatrix4<f32> m;
590                                         m.buildRotateFromTo(v3f(0,0,1), dir_f);
591
592                                         // This is the back face
593                                         v3f corners[2] = {
594                                                 v3f(BS/2, BS/2, BS/2),
595                                                 v3f(-BS/2, -BS/2, BS/2+d)
596                                         };
597                                         
598                                         for(u16 j=0; j<2; j++)
599                                         {
600                                                 m.rotateVect(corners[j]);
601                                                 corners[j] += npf;
602                                         }
603
604                                         core::aabbox3d<f32> facebox(corners[0]);
605                                         facebox.addInternalPoint(corners[1]);
606
607                                         if(facebox.intersectsWithLine(shootline))
608                                         {
609                                                 nodefound = true;
610                                                 nodepos = np;
611                                                 neighbourpos = np + dirs[i];
612                                                 mindistance = distance;
613
614                                                 //nodehilightbox = facebox;
615
616                                                 const float d = 0.502;
617                                                 core::aabbox3d<f32> nodebox
618                                                                 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
619                                                 v3f nodepos_f = intToFloat(nodepos, BS);
620                                                 nodebox.MinEdge += nodepos_f;
621                                                 nodebox.MaxEdge += nodepos_f;
622                                                 nodehilightbox = nodebox;
623                                         }
624                                 } // if distance < mindistance
625                         } // for dirs
626                 } // regular block
627         } // for coords
628 }
629
630 void update_skybox(video::IVideoDriver* driver,
631                 scene::ISceneManager* smgr, scene::ISceneNode* &skybox,
632                 float brightness)
633 {
634         if(skybox)
635         {
636                 skybox->remove();
637         }
638         
639         /*// Disable skybox if FarMesh is enabled
640         if(g_settings.getBool("enable_farmesh"))
641                 return;*/
642         
643         if(brightness >= 0.5)
644         {
645                 skybox = smgr->addSkyBoxSceneNode(
646                         driver->getTexture(getTexturePath("skybox2.png").c_str()),
647                         driver->getTexture(getTexturePath("skybox3.png").c_str()),
648                         driver->getTexture(getTexturePath("skybox1.png").c_str()),
649                         driver->getTexture(getTexturePath("skybox1.png").c_str()),
650                         driver->getTexture(getTexturePath("skybox1.png").c_str()),
651                         driver->getTexture(getTexturePath("skybox1.png").c_str()));
652         }
653         else if(brightness >= 0.2)
654         {
655                 skybox = smgr->addSkyBoxSceneNode(
656                         driver->getTexture(getTexturePath("skybox2_dawn.png").c_str()),
657                         driver->getTexture(getTexturePath("skybox3_dawn.png").c_str()),
658                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()),
659                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()),
660                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()),
661                         driver->getTexture(getTexturePath("skybox1_dawn.png").c_str()));
662         }
663         else
664         {
665                 skybox = smgr->addSkyBoxSceneNode(
666                         driver->getTexture(getTexturePath("skybox2_night.png").c_str()),
667                         driver->getTexture(getTexturePath("skybox3_night.png").c_str()),
668                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()),
669                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()),
670                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()),
671                         driver->getTexture(getTexturePath("skybox1_night.png").c_str()));
672         }
673 }
674
675 void the_game(
676         bool &kill,
677         bool random_input,
678         InputHandler *input,
679         IrrlichtDevice *device,
680         gui::IGUIFont* font,
681         std::string map_dir,
682         std::string playername,
683         std::string password,
684         std::string address,
685         u16 port,
686         std::wstring &error_message
687 )
688 {
689         video::IVideoDriver* driver = device->getVideoDriver();
690         scene::ISceneManager* smgr = device->getSceneManager();
691
692         v2u32 screensize(0,0);
693         v2u32 last_screensize(0,0);
694         screensize = driver->getScreenSize();
695
696         const s32 hotbar_itemcount = 8;
697         const s32 hotbar_imagesize = 36;
698         
699         // The color of the sky
700
701         //video::SColor skycolor = video::SColor(255,140,186,250);
702
703         video::SColor bgcolor_bright = video::SColor(255,170,200,230);
704
705         /*
706                 Draw "Loading" screen
707         */
708         const wchar_t *loadingtext = L"Loading and connecting...";
709         u32 text_height = font->getDimension(loadingtext).Height;
710         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
711         core::vector2d<s32> textsize(300, text_height);
712         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
713
714         gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText(
715                         loadingtext, textrect, false, false);
716         gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
717
718         driver->beginScene(true, true, video::SColor(255,0,0,0));
719         guienv->drawAll();
720         driver->endScene();
721
722         
723         /*
724                 Create server.
725                 SharedPtr will delete it when it goes out of scope.
726         */
727         SharedPtr<Server> server;
728         if(address == ""){
729                 std::cout<<DTIME<<"Creating server"<<std::endl;
730                 server = new Server(map_dir);
731                 server->start(port);
732         }
733         
734         /*
735                 Create client
736         */
737
738         std::cout<<DTIME<<"Creating client"<<std::endl;
739         Client client(device, playername.c_str(), password, draw_control);
740                         
741         Address connect_address(0,0,0,0, port);
742         try{
743                 if(address == "")
744                         //connect_address.Resolve("localhost");
745                         connect_address.setAddress(127,0,0,1);
746                 else
747                         connect_address.Resolve(address.c_str());
748         }
749         catch(ResolveError &e)
750         {
751                 std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;
752                 //return 0;
753                 error_message = L"Couldn't resolve address";
754                 gui_loadingtext->remove();
755                 return;
756         }
757
758         /*
759                 Attempt to connect to the server
760         */
761         
762         dstream<<DTIME<<"Connecting to server at ";
763         connect_address.print(&dstream);
764         dstream<<std::endl;
765         client.connect(connect_address);
766
767         bool could_connect = false;
768         
769         try{
770                 float time_counter = 0.0;
771                 for(;;)
772                 {
773                         if(client.connectedAndInitialized())
774                         {
775                                 could_connect = true;
776                                 break;
777                         }
778                         if(client.accessDenied())
779                         {
780                                 break;
781                         }
782                         // Wait for 10 seconds
783                         if(time_counter >= 10.0)
784                         {
785                                 break;
786                         }
787
788                         // Update screen
789                         driver->beginScene(true, true, video::SColor(255,0,0,0));
790                         guienv->drawAll();
791                         driver->endScene();
792
793                         // Update client and server
794
795                         client.step(0.1);
796
797                         if(server != NULL)
798                                 server->step(0.1);
799                         
800                         // Delay a bit
801                         sleep_ms(100);
802                         time_counter += 0.1;
803                 }
804         }
805         catch(con::PeerNotFoundException &e)
806         {}
807
808         if(could_connect == false)
809         {
810                 if(client.accessDenied())
811                 {
812                         error_message = L"Access denied. Reason: "
813                                         +client.accessDeniedReason();
814                         std::cout<<DTIME<<wide_to_narrow(error_message)<<std::endl;
815                 }
816                 else
817                 {
818                         error_message = L"Connection timed out.";
819                         std::cout<<DTIME<<"Timed out."<<std::endl;
820                 }
821                 gui_loadingtext->remove();
822                 return;
823         }
824
825         /*
826                 Create skybox
827         */
828         float old_brightness = 1.0;
829         scene::ISceneNode* skybox = NULL;
830         update_skybox(driver, smgr, skybox, 1.0);
831         
832         /*
833                 Create the camera node
834         */
835
836         scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(
837                 0, // Camera parent
838                 v3f(BS*100, BS*2, BS*100), // Look from
839                 v3f(BS*100+1, BS*2, BS*100), // Look to
840                 -1 // Camera ID
841         );
842
843         if(camera == NULL)
844         {
845                 error_message = L"Failed to create the camera node";
846                 return;
847         }
848
849         camera->setFOV(FOV_ANGLE);
850
851         // Just so big a value that everything rendered is visible
852         camera->setFarValue(100000*BS);
853         
854         f32 camera_yaw = 0; // "right/left"
855         f32 camera_pitch = 0; // "up/down"
856
857         /*
858                 Clouds
859         */
860         
861         float cloud_height = BS*100;
862         Clouds *clouds = NULL;
863         if(g_settings.getBool("enable_clouds"))
864         {
865                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
866                                 cloud_height, time(0));
867         }
868         
869         /*
870                 FarMesh
871         */
872
873         FarMesh *farmesh = NULL;
874         if(g_settings.getBool("enable_farmesh"))
875         {
876                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
877         }
878
879         /*
880                 Move into game
881         */
882         
883         gui_loadingtext->remove();
884
885         /*
886                 Add some gui stuff
887         */
888
889         // First line of debug text
890         gui::IGUIStaticText *guitext = guienv->addStaticText(
891                         L"Minetest-c55",
892                         core::rect<s32>(5, 5, 795, 5+text_height),
893                         false, false);
894         // Second line of debug text
895         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
896                         L"",
897                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
898                         false, false);
899         
900         // At the middle of the screen
901         // Object infos are shown in this
902         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
903                         L"",
904                         core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
905                         false, false);
906         
907         // Chat text
908         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
909                         L"",
910                         core::rect<s32>(0,0,0,0),
911                         //false, false); // Disable word wrap as of now
912                         false, true);
913         //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
914         core::list<ChatLine> chat_lines;
915         
916         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
917                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
918         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
919                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
920         
921         // Test the text input system
922         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
923                         NULL))->drop();*/
924         /*GUIMessageMenu *menu =
925                         new GUIMessageMenu(guienv, guiroot, -1, 
926                                 &g_menumgr,
927                                 L"Asd");
928         menu->drop();*/
929         
930         // Launch pause menu
931         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
932                         &g_menumgr))->drop();
933         
934         // Enable texts
935         /*guitext2->setVisible(true);
936         guitext_info->setVisible(true);
937         guitext_chat->setVisible(true);*/
938
939         //s32 guitext_chat_pad_bottom = 70;
940
941         /*
942                 Some statistics are collected in these
943         */
944         u32 drawtime = 0;
945         u32 beginscenetime = 0;
946         u32 scenetime = 0;
947         u32 endscenetime = 0;
948         
949         // A test
950         //throw con::PeerNotFoundException("lol");
951
952         core::list<float> frametime_log;
953
954         float damage_flash_timer = 0;
955         s16 farmesh_range = 20*MAP_BLOCKSIZE;
956         
957         bool invert_mouse = g_settings.getBool("invert_mouse");
958
959         /*
960                 Main loop
961         */
962
963         bool first_loop_after_window_activation = true;
964
965         // TODO: Convert the static interval timers to these
966         // Interval limiter for profiler
967         IntervalLimiter m_profiler_interval;
968
969         // Time is in milliseconds
970         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
971         // NOTE: So we have to use getTime() and call run()s between them
972         u32 lasttime = device->getTimer()->getTime();
973
974         while(device->run() && kill == false)
975         {
976                 if(g_gamecallback->disconnect_requested)
977                 {
978                         g_gamecallback->disconnect_requested = false;
979                         break;
980                 }
981
982                 if(g_gamecallback->changepassword_requested)
983                 {
984                         (new GUIPasswordChange(guienv, guiroot, -1,
985                                 &g_menumgr, &client))->drop();
986                         g_gamecallback->changepassword_requested = false;
987                 }
988
989                 /*
990                         Process TextureSource's queue
991                 */
992                 ((TextureSource*)g_texturesource)->processQueue();
993
994                 /*
995                         Random calculations
996                 */
997                 last_screensize = screensize;
998                 screensize = driver->getScreenSize();
999                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1000                 //bool screensize_changed = screensize != last_screensize;
1001                 
1002                 // Hilight boxes collected during the loop and displayed
1003                 core::list< core::aabbox3d<f32> > hilightboxes;
1004                 
1005                 // Info text
1006                 std::wstring infotext;
1007
1008                 // When screen size changes, update positions and sizes of stuff
1009                 /*if(screensize_changed)
1010                 {
1011                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
1012                         quick_inventory->updatePosition(pos);
1013                 }*/
1014
1015                 //TimeTaker //timer1("//timer1");
1016                 
1017                 // Time of frame without fps limit
1018                 float busytime;
1019                 u32 busytime_u32;
1020                 {
1021                         // not using getRealTime is necessary for wine
1022                         u32 time = device->getTimer()->getTime();
1023                         if(time > lasttime)
1024                                 busytime_u32 = time - lasttime;
1025                         else
1026                                 busytime_u32 = 0;
1027                         busytime = busytime_u32 / 1000.0;
1028                 }
1029
1030                 //std::cout<<"busytime_u32="<<busytime_u32<<std::endl;
1031         
1032                 // Necessary for device->getTimer()->getTime()
1033                 device->run();
1034
1035                 /*
1036                         Viewing range
1037                 */
1038                 
1039                 updateViewingRange(busytime, &client);
1040                 
1041                 /*
1042                         FPS limiter
1043                 */
1044
1045                 {
1046                         float fps_max = g_settings.getFloat("fps_max");
1047                         u32 frametime_min = 1000./fps_max;
1048                         
1049                         if(busytime_u32 < frametime_min)
1050                         {
1051                                 u32 sleeptime = frametime_min - busytime_u32;
1052                                 device->sleep(sleeptime);
1053                         }
1054                 }
1055
1056                 // Necessary for device->getTimer()->getTime()
1057                 device->run();
1058
1059                 /*
1060                         Time difference calculation
1061                 */
1062                 f32 dtime; // in seconds
1063                 
1064                 u32 time = device->getTimer()->getTime();
1065                 if(time > lasttime)
1066                         dtime = (time - lasttime) / 1000.0;
1067                 else
1068                         dtime = 0;
1069                 lasttime = time;
1070
1071                 /*
1072                         Log frametime for visualization
1073                 */
1074                 frametime_log.push_back(dtime);
1075                 if(frametime_log.size() > 100)
1076                 {
1077                         core::list<float>::Iterator i = frametime_log.begin();
1078                         frametime_log.erase(i);
1079                 }
1080
1081                 /*
1082                         Visualize frametime in terminal
1083                 */
1084                 /*for(u32 i=0; i<dtime*400; i++)
1085                         std::cout<<"X";
1086                 std::cout<<std::endl;*/
1087
1088                 /*
1089                         Time average and jitter calculation
1090                 */
1091
1092                 static f32 dtime_avg1 = 0.0;
1093                 dtime_avg1 = dtime_avg1 * 0.98 + dtime * 0.02;
1094                 f32 dtime_jitter1 = dtime - dtime_avg1;
1095
1096                 static f32 dtime_jitter1_max_sample = 0.0;
1097                 static f32 dtime_jitter1_max_fraction = 0.0;
1098                 {
1099                         static f32 jitter1_max = 0.0;
1100                         static f32 counter = 0.0;
1101                         if(dtime_jitter1 > jitter1_max)
1102                                 jitter1_max = dtime_jitter1;
1103                         counter += dtime;
1104                         if(counter > 0.0)
1105                         {
1106                                 counter -= 3.0;
1107                                 dtime_jitter1_max_sample = jitter1_max;
1108                                 dtime_jitter1_max_fraction
1109                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1110                                 jitter1_max = 0.0;
1111                         }
1112                 }
1113                 
1114                 /*
1115                         Busytime average and jitter calculation
1116                 */
1117
1118                 static f32 busytime_avg1 = 0.0;
1119                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1120                 f32 busytime_jitter1 = busytime - busytime_avg1;
1121                 
1122                 static f32 busytime_jitter1_max_sample = 0.0;
1123                 static f32 busytime_jitter1_min_sample = 0.0;
1124                 {
1125                         static f32 jitter1_max = 0.0;
1126                         static f32 jitter1_min = 0.0;
1127                         static f32 counter = 0.0;
1128                         if(busytime_jitter1 > jitter1_max)
1129                                 jitter1_max = busytime_jitter1;
1130                         if(busytime_jitter1 < jitter1_min)
1131                                 jitter1_min = busytime_jitter1;
1132                         counter += dtime;
1133                         if(counter > 0.0){
1134                                 counter -= 3.0;
1135                                 busytime_jitter1_max_sample = jitter1_max;
1136                                 busytime_jitter1_min_sample = jitter1_min;
1137                                 jitter1_max = 0.0;
1138                                 jitter1_min = 0.0;
1139                         }
1140                 }
1141                 
1142                 /*
1143                         Debug info for client
1144                 */
1145                 {
1146                         static float counter = 0.0;
1147                         counter -= dtime;
1148                         if(counter < 0)
1149                         {
1150                                 counter = 30.0;
1151                                 client.printDebugInfo(std::cout);
1152                         }
1153                 }
1154
1155                 /*
1156                         Profiler
1157                 */
1158                 float profiler_print_interval =
1159                                 g_settings.getFloat("profiler_print_interval");
1160                 if(profiler_print_interval != 0)
1161                 {
1162                         if(m_profiler_interval.step(0.030, profiler_print_interval))
1163                         {
1164                                 dstream<<"Profiler:"<<std::endl;
1165                                 g_profiler.print(dstream);
1166                                 g_profiler.clear();
1167                         }
1168                 }
1169
1170                 /*
1171                         Direct handling of user input
1172                 */
1173                 
1174                 // Reset input if window not active or some menu is active
1175                 if(device->isWindowActive() == false || noMenuActive() == false)
1176                 {
1177                         input->clear();
1178                 }
1179
1180                 // Input handler step() (used by the random input generator)
1181                 input->step(dtime);
1182
1183                 /*
1184                         Launch menus according to keys
1185                 */
1186                 if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1187                 {
1188                         dstream<<DTIME<<"the_game: "
1189                                         <<"Launching inventory"<<std::endl;
1190                         
1191                         GUIInventoryMenu *menu =
1192                                 new GUIInventoryMenu(guienv, guiroot, -1,
1193                                         &g_menumgr, v2s16(8,7),
1194                                         client.getInventoryContext(),
1195                                         &client);
1196
1197                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1198                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1199                                         "list", "current_player", "main",
1200                                         v2s32(0, 3), v2s32(8, 4)));
1201                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1202                                         "list", "current_player", "craft",
1203                                         v2s32(3, 0), v2s32(3, 3)));
1204                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1205                                         "list", "current_player", "craftresult",
1206                                         v2s32(7, 1), v2s32(1, 1)));
1207
1208                         menu->setDrawSpec(draw_spec);
1209
1210                         menu->drop();
1211                 }
1212                 else if(input->wasKeyDown(KEY_ESCAPE))
1213                 {
1214                         dstream<<DTIME<<"the_game: "
1215                                         <<"Launching pause menu"<<std::endl;
1216                         // It will delete itself by itself
1217                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1218                                         &g_menumgr))->drop();
1219
1220                         // Move mouse cursor on top of the disconnect button
1221                         input->setMousePos(displaycenter.X, displaycenter.Y+25);
1222                 }
1223                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1224                 {
1225                         TextDest *dest = new TextDestChat(&client);
1226
1227                         (new GUITextInputMenu(guienv, guiroot, -1,
1228                                         &g_menumgr, dest,
1229                                         L""))->drop();
1230                 }
1231                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1232                 {
1233                         if(g_settings.getBool("free_move"))
1234                         {
1235                                 g_settings.set("free_move","false");
1236                                 chat_lines.push_back(ChatLine(L"free_move disabled"));
1237                         }
1238                         else
1239                         {
1240                                 g_settings.set("free_move","true");
1241                                 chat_lines.push_back(ChatLine(L"free_move enabled"));
1242                         }
1243                 }
1244                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1245                 {
1246                         if(g_settings.getBool("fast_move"))
1247                         {
1248                                 g_settings.set("fast_move","false");
1249                                 chat_lines.push_back(ChatLine(L"fast_move disabled"));
1250                         }
1251                         else
1252                         {
1253                                 g_settings.set("fast_move","true");
1254                                 chat_lines.push_back(ChatLine(L"fast_move enabled"));
1255                         }
1256                 }
1257
1258                 // Item selection with mouse wheel
1259                 {
1260                         s32 wheel = input->getMouseWheel();
1261                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1262                                         hotbar_itemcount-1);
1263
1264                         if(wheel < 0)
1265                         {
1266                                 if(g_selected_item < max_item)
1267                                         g_selected_item++;
1268                                 else
1269                                         g_selected_item = 0;
1270                         }
1271                         else if(wheel > 0)
1272                         {
1273                                 if(g_selected_item > 0)
1274                                         g_selected_item--;
1275                                 else
1276                                         g_selected_item = max_item;
1277                         }
1278                 }
1279                 
1280                 // Item selection
1281                 for(u16 i=0; i<10; i++)
1282                 {
1283                         s32 keycode = irr::KEY_KEY_1 + i;
1284                         if(i == 9)
1285                                 keycode = irr::KEY_KEY_0;
1286                         if(input->wasKeyDown((irr::EKEY_CODE)keycode))
1287                         {
1288                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1289                                 {
1290                                         g_selected_item = i;
1291
1292                                         dstream<<DTIME<<"Selected item: "
1293                                                         <<g_selected_item<<std::endl;
1294                                 }
1295                         }
1296                 }
1297
1298                 // Viewing range selection
1299                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1300                 {
1301                         if(draw_control.range_all)
1302                         {
1303                                 draw_control.range_all = false;
1304                                 dstream<<DTIME<<"Disabled full viewing range"<<std::endl;
1305                         }
1306                         else
1307                         {
1308                                 draw_control.range_all = true;
1309                                 dstream<<DTIME<<"Enabled full viewing range"<<std::endl;
1310                         }
1311                 }
1312
1313                 // Print debug stacks
1314                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1315                 {
1316                         dstream<<"-----------------------------------------"
1317                                         <<std::endl;
1318                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1319                         dstream<<"-----------------------------------------"
1320                                         <<std::endl;
1321                         debug_stacks_print();
1322                 }
1323
1324                 /*
1325                         Player speed control
1326                         TODO: Cache the keycodes from getKeySetting
1327                 */
1328                 
1329                 {
1330                         /*bool a_up,
1331                         bool a_down,
1332                         bool a_left,
1333                         bool a_right,
1334                         bool a_jump,
1335                         bool a_superspeed,
1336                         bool a_sneak,
1337                         float a_pitch,
1338                         float a_yaw*/
1339                         PlayerControl control(
1340                                 input->isKeyDown(getKeySetting("keymap_forward")),
1341                                 input->isKeyDown(getKeySetting("keymap_backward")),
1342                                 input->isKeyDown(getKeySetting("keymap_left")),
1343                                 input->isKeyDown(getKeySetting("keymap_right")),
1344                                 input->isKeyDown(getKeySetting("keymap_jump")),
1345                                 input->isKeyDown(getKeySetting("keymap_special1")),
1346                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1347                                 camera_pitch,
1348                                 camera_yaw
1349                         );
1350                         client.setPlayerControl(control);
1351                 }
1352                 
1353                 /*
1354                         Run server
1355                 */
1356
1357                 if(server != NULL)
1358                 {
1359                         //TimeTaker timer("server->step(dtime)");
1360                         server->step(dtime);
1361                 }
1362
1363                 /*
1364                         Process environment
1365                 */
1366                 
1367                 {
1368                         //TimeTaker timer("client.step(dtime)");
1369                         client.step(dtime);
1370                         //client.step(dtime_avg1);
1371                 }
1372
1373                 // Read client events
1374                 for(;;)
1375                 {
1376                         ClientEvent event = client.getClientEvent();
1377                         if(event.type == CE_NONE)
1378                         {
1379                                 break;
1380                         }
1381                         else if(event.type == CE_PLAYER_DAMAGE)
1382                         {
1383                                 //u16 damage = event.player_damage.amount;
1384                                 //dstream<<"Player damage: "<<damage<<std::endl;
1385                                 damage_flash_timer = 0.05;
1386                         }
1387                         else if(event.type == CE_PLAYER_FORCE_MOVE)
1388                         {
1389                                 camera_yaw = event.player_force_move.yaw;
1390                                 camera_pitch = event.player_force_move.pitch;
1391                         }
1392                 }
1393                 
1394                 // Get player position
1395                 v3f player_position = client.getPlayerPosition();
1396
1397                 //TimeTaker //timer2("//timer2");
1398
1399                 /*
1400                         Mouse and camera control
1401                 */
1402                 
1403                 if((device->isWindowActive() && noMenuActive()) || random_input)
1404                 {
1405                         if(!random_input)
1406                         {
1407                                 // Mac OSX gets upset if this is set every frame
1408                                 if(device->getCursorControl()->isVisible())
1409                                         device->getCursorControl()->setVisible(false);
1410                         }
1411
1412                         if(first_loop_after_window_activation){
1413                                 //std::cout<<"window active, first loop"<<std::endl;
1414                                 first_loop_after_window_activation = false;
1415                         }
1416                         else{
1417                                 s32 dx = input->getMousePos().X - displaycenter.X;
1418                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1419                                 if(invert_mouse)
1420                                         dy = -dy;
1421                                 //std::cout<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1422                                 
1423                                 /*const float keyspeed = 500;
1424                                 if(input->isKeyDown(irr::KEY_UP))
1425                                         dy -= dtime * keyspeed;
1426                                 if(input->isKeyDown(irr::KEY_DOWN))
1427                                         dy += dtime * keyspeed;
1428                                 if(input->isKeyDown(irr::KEY_LEFT))
1429                                         dx -= dtime * keyspeed;
1430                                 if(input->isKeyDown(irr::KEY_RIGHT))
1431                                         dx += dtime * keyspeed;*/
1432
1433                                 camera_yaw -= dx*0.2;
1434                                 camera_pitch += dy*0.2;
1435                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1436                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1437                         }
1438                         input->setMousePos(displaycenter.X, displaycenter.Y);
1439                 }
1440                 else{
1441                         // Mac OSX gets upset if this is set every frame
1442                         if(device->getCursorControl()->isVisible() == false)
1443                                 device->getCursorControl()->setVisible(true);
1444
1445                         //std::cout<<"window inactive"<<std::endl;
1446                         first_loop_after_window_activation = true;
1447                 }
1448
1449                 camera_yaw = wrapDegrees(camera_yaw);
1450                 camera_pitch = wrapDegrees(camera_pitch);
1451                 
1452                 v3f camera_direction = v3f(0,0,1);
1453                 camera_direction.rotateYZBy(camera_pitch);
1454                 camera_direction.rotateXZBy(camera_yaw);
1455                 
1456                 // This is at the height of the eyes of the current figure
1457                 //v3f camera_position = player_position + v3f(0, BS+BS/2, 0);
1458                 // This is more like in minecraft
1459                 v3f camera_position = player_position + v3f(0, BS+BS*0.625, 0);
1460
1461                 camera->setPosition(camera_position);
1462                 // *100.0 helps in large map coordinates
1463                 camera->setTarget(camera_position + camera_direction * 100.0);
1464
1465                 if(FIELD_OF_VIEW_TEST){
1466                         client.updateCamera(v3f(0,0,0), v3f(0,0,1));
1467                 }
1468                 else{
1469                         //TimeTaker timer("client.updateCamera");
1470                         client.updateCamera(camera_position, camera_direction);
1471                 }
1472                 
1473                 //timer2.stop();
1474                 //TimeTaker //timer3("//timer3");
1475
1476                 /*
1477                         Calculate what block is the crosshair pointing to
1478                 */
1479                 
1480                 //u32 t1 = device->getTimer()->getRealTime();
1481                 
1482                 //f32 d = 4; // max. distance
1483                 f32 d = 4; // max. distance
1484                 core::line3d<f32> shootline(camera_position,
1485                                 camera_position + camera_direction * BS * (d+1));
1486
1487                 MapBlockObject *selected_object = client.getSelectedObject
1488                                 (d*BS, camera_position, shootline);
1489
1490                 ClientActiveObject *selected_active_object
1491                                 = client.getSelectedActiveObject
1492                                         (d*BS, camera_position, shootline);
1493
1494                 if(selected_object != NULL)
1495                 {
1496                         //dstream<<"Client returned selected_object != NULL"<<std::endl;
1497
1498                         core::aabbox3d<f32> box_on_map
1499                                         = selected_object->getSelectionBoxOnMap();
1500
1501                         hilightboxes.push_back(box_on_map);
1502
1503                         infotext = narrow_to_wide(selected_object->infoText());
1504
1505                         if(input->getLeftClicked())
1506                         {
1507                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1508                                 client.clickObject(0, selected_object->getBlock()->getPos(),
1509                                                 selected_object->getId(), g_selected_item);
1510                         }
1511                         else if(input->getRightClicked())
1512                         {
1513                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1514                                 /*
1515                                         Check if we want to modify the object ourselves
1516                                 */
1517                                 if(selected_object->getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN)
1518                                 {
1519                                         dstream<<"Sign object right-clicked"<<std::endl;
1520                                         
1521                                         if(random_input == false)
1522                                         {
1523                                                 // Get a new text for it
1524
1525                                                 TextDest *dest = new TextDestSign(
1526                                                                 selected_object->getBlock()->getPos(),
1527                                                                 selected_object->getId(),
1528                                                                 &client);
1529
1530                                                 SignObject *sign_object = (SignObject*)selected_object;
1531
1532                                                 std::wstring wtext =
1533                                                                 narrow_to_wide(sign_object->getText());
1534
1535                                                 (new GUITextInputMenu(guienv, guiroot, -1,
1536                                                                 &g_menumgr, dest,
1537                                                                 wtext))->drop();
1538                                         }
1539                                 }
1540                                 /*
1541                                         Otherwise pass the event to the server as-is
1542                                 */
1543                                 else
1544                                 {
1545                                         client.clickObject(1, selected_object->getBlock()->getPos(),
1546                                                         selected_object->getId(), g_selected_item);
1547                                 }
1548                         }
1549                 }
1550                 else if(selected_active_object != NULL)
1551                 {
1552                         //dstream<<"Client returned selected_active_object != NULL"<<std::endl;
1553                         
1554                         core::aabbox3d<f32> *selection_box
1555                                         = selected_active_object->getSelectionBox();
1556                         // Box should exist because object was returned in the
1557                         // first place
1558                         assert(selection_box);
1559
1560                         v3f pos = selected_active_object->getPosition();
1561
1562                         core::aabbox3d<f32> box_on_map(
1563                                         selection_box->MinEdge + pos,
1564                                         selection_box->MaxEdge + pos
1565                         );
1566
1567                         hilightboxes.push_back(box_on_map);
1568
1569                         //infotext = narrow_to_wide("A ClientActiveObject");
1570                         infotext = narrow_to_wide(selected_active_object->infoText());
1571
1572                         if(input->getLeftClicked())
1573                         {
1574                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1575                                 client.clickActiveObject(0,
1576                                                 selected_active_object->getId(), g_selected_item);
1577                         }
1578                         else if(input->getRightClicked())
1579                         {
1580                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1581                         }
1582                 }
1583                 else // selected_object == NULL
1584                 {
1585
1586                 /*
1587                         Find out which node we are pointing at
1588                 */
1589                 
1590                 bool nodefound = false;
1591                 v3s16 nodepos;
1592                 v3s16 neighbourpos;
1593                 core::aabbox3d<f32> nodehilightbox;
1594
1595                 getPointedNode(&client, player_position,
1596                                 camera_direction, camera_position,
1597                                 nodefound, shootline,
1598                                 nodepos, neighbourpos,
1599                                 nodehilightbox, d);
1600         
1601                 static float nodig_delay_counter = 0.0;
1602
1603                 if(nodefound)
1604                 {
1605                         static v3s16 nodepos_old(-32768,-32768,-32768);
1606
1607                         static float dig_time = 0.0;
1608                         static u16 dig_index = 0;
1609                         
1610                         /*
1611                                 Visualize selection
1612                         */
1613
1614                         hilightboxes.push_back(nodehilightbox);
1615
1616                         /*
1617                                 Check information text of node
1618                         */
1619
1620                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1621                         if(meta)
1622                         {
1623                                 infotext = narrow_to_wide(meta->infoText());
1624                         }
1625                         
1626                         //MapNode node = client.getNode(nodepos);
1627
1628                         /*
1629                                 Handle digging
1630                         */
1631                         
1632                         if(input->getLeftReleased())
1633                         {
1634                                 client.clearTempMod(nodepos);
1635                                 dig_time = 0.0;
1636                         }
1637                         
1638                         if(nodig_delay_counter > 0.0)
1639                         {
1640                                 nodig_delay_counter -= dtime;
1641                         }
1642                         else
1643                         {
1644                                 if(nodepos != nodepos_old)
1645                                 {
1646                                         std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","
1647                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1648
1649                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1650                                         {
1651                                                 client.clearTempMod(nodepos_old);
1652                                                 dig_time = 0.0;
1653                                         }
1654                                 }
1655
1656                                 if(input->getLeftClicked() ||
1657                                                 (input->getLeftState() && nodepos != nodepos_old))
1658                                 {
1659                                         dstream<<DTIME<<"Started digging"<<std::endl;
1660                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1661                                 }
1662                                 if(input->getLeftClicked())
1663                                 {
1664                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1665                                 }
1666                                 if(input->getLeftState())
1667                                 {
1668                                         MapNode n = client.getNode(nodepos);
1669                                 
1670                                         // Get tool name. Default is "" = bare hands
1671                                         std::string toolname = "";
1672                                         InventoryList *mlist = local_inventory.getList("main");
1673                                         if(mlist != NULL)
1674                                         {
1675                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1676                                                 if(item && (std::string)item->getName() == "ToolItem")
1677                                                 {
1678                                                         ToolItem *titem = (ToolItem*)item;
1679                                                         toolname = titem->getToolName();
1680                                                 }
1681                                         }
1682
1683                                         // Get digging properties for material and tool
1684                                         u8 material = n.d;
1685                                         DiggingProperties prop =
1686                                                         getDiggingProperties(material, toolname);
1687                                         
1688                                         float dig_time_complete = 0.0;
1689
1690                                         if(prop.diggable == false)
1691                                         {
1692                                                 /*dstream<<"Material "<<(int)material
1693                                                                 <<" not diggable with \""
1694                                                                 <<toolname<<"\""<<std::endl;*/
1695                                                 // I guess nobody will wait for this long
1696                                                 dig_time_complete = 10000000.0;
1697                                         }
1698                                         else
1699                                         {
1700                                                 dig_time_complete = prop.time;
1701                                         }
1702                                         
1703                                         if(dig_time_complete >= 0.001)
1704                                         {
1705                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1706                                                                 * dig_time/dig_time_complete);
1707                                         }
1708                                         // This is for torches
1709                                         else
1710                                         {
1711                                                 dig_index = CRACK_ANIMATION_LENGTH;
1712                                         }
1713
1714                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1715                                         {
1716                                                 //TimeTaker timer("client.setTempMod");
1717                                                 //dstream<<"dig_index="<<dig_index<<std::endl;
1718                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1719                                         }
1720                                         else
1721                                         {
1722                                                 dstream<<DTIME<<"Digging completed"<<std::endl;
1723                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1724                                                 client.clearTempMod(nodepos);
1725                                                 client.removeNode(nodepos);
1726
1727                                                 dig_time = 0;
1728
1729                                                 nodig_delay_counter = dig_time_complete
1730                                                                 / (float)CRACK_ANIMATION_LENGTH;
1731
1732                                                 // We don't want a corresponding delay to
1733                                                 // very time consuming nodes
1734                                                 if(nodig_delay_counter > 0.5)
1735                                                 {
1736                                                         nodig_delay_counter = 0.5;
1737                                                 }
1738                                                 // We want a slight delay to very little
1739                                                 // time consuming nodes
1740                                                 float mindelay = 0.15;
1741                                                 if(nodig_delay_counter < mindelay)
1742                                                 {
1743                                                         nodig_delay_counter = mindelay;
1744                                                 }
1745                                         }
1746
1747                                         dig_time += dtime;
1748                                 }
1749                         }
1750                         
1751                         if(input->getRightClicked())
1752                         {
1753                                 std::cout<<DTIME<<"Ground right-clicked"<<std::endl;
1754                                 
1755                                 // If metadata provides an inventory view, activate it
1756                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
1757                                 {
1758                                         dstream<<DTIME<<"Launching custom inventory view"<<std::endl;
1759                                         /*
1760                                                 Construct the unique identification string of the node
1761                                         */
1762                                         std::string current_name;
1763                                         current_name += "nodemeta:";
1764                                         current_name += itos(nodepos.X);
1765                                         current_name += ",";
1766                                         current_name += itos(nodepos.Y);
1767                                         current_name += ",";
1768                                         current_name += itos(nodepos.Z);
1769                                         
1770                                         /*
1771                                                 Create menu
1772                                         */
1773
1774                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1775                                         v2s16 invsize =
1776                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
1777                                                         draw_spec,
1778                                                         meta->getInventoryDrawSpecString(),
1779                                                         current_name);
1780
1781                                         GUIInventoryMenu *menu =
1782                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1783                                                         &g_menumgr, invsize,
1784                                                         client.getInventoryContext(),
1785                                                         &client);
1786                                         menu->setDrawSpec(draw_spec);
1787                                         menu->drop();
1788                                 }
1789                                 else if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1790                                 {
1791                                         dstream<<"Sign node right-clicked"<<std::endl;
1792                                         
1793                                         SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1794                                         
1795                                         // Get a new text for it
1796
1797                                         TextDest *dest = new TextDestSignNode(nodepos, &client);
1798
1799                                         std::wstring wtext =
1800                                                         narrow_to_wide(signmeta->getText());
1801
1802                                         (new GUITextInputMenu(guienv, guiroot, -1,
1803                                                         &g_menumgr, dest,
1804                                                         wtext))->drop();
1805                                 }
1806                                 else
1807                                 {
1808                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1809                                 }
1810                         }
1811                         
1812                         nodepos_old = nodepos;
1813                 }
1814                 else{
1815                 }
1816
1817                 } // selected_object == NULL
1818                 
1819                 input->resetLeftClicked();
1820                 input->resetRightClicked();
1821                 
1822                 if(input->getLeftReleased())
1823                 {
1824                         std::cout<<DTIME<<"Left button released (stopped digging)"
1825                                         <<std::endl;
1826                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1827                 }
1828                 if(input->getRightReleased())
1829                 {
1830                         //std::cout<<DTIME<<"Right released"<<std::endl;
1831                         // Nothing here
1832                 }
1833                 
1834                 input->resetLeftReleased();
1835                 input->resetRightReleased();
1836                 
1837                 /*
1838                         Calculate stuff for drawing
1839                 */
1840
1841                 camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);
1842                 
1843                 u32 daynight_ratio = client.getDayNightRatio();
1844                 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1845                 video::SColor bgcolor = video::SColor(
1846                                 255,
1847                                 bgcolor_bright.getRed() * l / 255,
1848                                 bgcolor_bright.getGreen() * l / 255,
1849                                 bgcolor_bright.getBlue() * l / 255);
1850                                 /*skycolor.getRed() * l / 255,
1851                                 skycolor.getGreen() * l / 255,
1852                                 skycolor.getBlue() * l / 255);*/
1853
1854                 float brightness = (float)l/255.0;
1855
1856                 /*
1857                         Update skybox
1858                 */
1859                 if(fabs(brightness - old_brightness) > 0.01)
1860                         update_skybox(driver, smgr, skybox, brightness);
1861
1862                 /*
1863                         Update coulds
1864                 */
1865                 if(clouds)
1866                 {
1867                         clouds->step(dtime);
1868                         clouds->update(v2f(player_position.X, player_position.Z),
1869                                         0.05+brightness*0.95);
1870                 }
1871                 
1872                 /*
1873                         Update farmesh
1874                 */
1875                 if(farmesh)
1876                 {
1877                         farmesh_range = draw_control.wanted_range * 10;
1878                         if(draw_control.range_all && farmesh_range < 500)
1879                                 farmesh_range = 500;
1880                         if(farmesh_range > 1000)
1881                                 farmesh_range = 1000;
1882
1883                         farmesh->step(dtime);
1884                         farmesh->update(v2f(player_position.X, player_position.Z),
1885                                         0.05+brightness*0.95, farmesh_range);
1886                 }
1887                 
1888                 // Store brightness value
1889                 old_brightness = brightness;
1890
1891                 /*
1892                         Fog
1893                 */
1894                 
1895                 if(g_settings.getBool("enable_fog") == true)
1896                 {
1897                         f32 range;
1898                         if(farmesh)
1899                         {
1900                                 range = BS*farmesh_range;
1901                         }
1902                         else
1903                         {
1904                                 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
1905                                 if(draw_control.range_all)
1906                                         range = 100000*BS;
1907                                 if(range < 50*BS)
1908                                         range = range * 0.5 + 25*BS;
1909                         }
1910
1911                         driver->setFog(
1912                                 bgcolor,
1913                                 video::EFT_FOG_LINEAR,
1914                                 range*0.4,
1915                                 range*1.0,
1916                                 0.01,
1917                                 false, // pixel fog
1918                                 false // range fog
1919                         );
1920                 }
1921                 else
1922                 {
1923                         driver->setFog(
1924                                 bgcolor,
1925                                 video::EFT_FOG_LINEAR,
1926                                 100000*BS,
1927                                 110000*BS,
1928                                 0.01,
1929                                 false, // pixel fog
1930                                 false // range fog
1931                         );
1932                 }
1933
1934
1935                 /*
1936                         Update gui stuff (0ms)
1937                 */
1938
1939                 //TimeTaker guiupdatetimer("Gui updating");
1940                 
1941                 {
1942                         static float drawtime_avg = 0;
1943                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
1944                         static float beginscenetime_avg = 0;
1945                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
1946                         static float scenetime_avg = 0;
1947                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
1948                         static float endscenetime_avg = 0;
1949                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
1950                         
1951                         char temptext[300];
1952                         snprintf(temptext, 300, "Minetest-c55 %s ("
1953                                         "R: range_all=%i"
1954                                         ")"
1955                                         " drawtime=%.0f, beginscenetime=%.0f"
1956                                         ", scenetime=%.0f, endscenetime=%.0f",
1957                                         VERSION_STRING,
1958                                         draw_control.range_all,
1959                                         drawtime_avg,
1960                                         beginscenetime_avg,
1961                                         scenetime_avg,
1962                                         endscenetime_avg
1963                                         );
1964                         
1965                         guitext->setText(narrow_to_wide(temptext).c_str());
1966                 }
1967                 
1968                 {
1969                         char temptext[300];
1970                         snprintf(temptext, 300,
1971                                         "(% .1f, % .1f, % .1f)"
1972                                         " (% .3f < btime_jitter < % .3f"
1973                                         ", dtime_jitter = % .1f %%"
1974                                         ", v_range = %.1f)",
1975                                         player_position.X/BS,
1976                                         player_position.Y/BS,
1977                                         player_position.Z/BS,
1978                                         busytime_jitter1_min_sample,
1979                                         busytime_jitter1_max_sample,
1980                                         dtime_jitter1_max_fraction * 100.0,
1981                                         draw_control.wanted_range
1982                                         );
1983
1984                         guitext2->setText(narrow_to_wide(temptext).c_str());
1985                 }
1986                 
1987                 {
1988                         guitext_info->setText(infotext.c_str());
1989                 }
1990                 
1991                 /*
1992                         Get chat messages from client
1993                 */
1994                 {
1995                         // Get new messages
1996                         std::wstring message;
1997                         while(client.getChatMessage(message))
1998                         {
1999                                 chat_lines.push_back(ChatLine(message));
2000                                 /*if(chat_lines.size() > 6)
2001                                 {
2002                                         core::list<ChatLine>::Iterator
2003                                                         i = chat_lines.begin();
2004                                         chat_lines.erase(i);
2005                                 }*/
2006                         }
2007                         // Append them to form the whole static text and throw
2008                         // it to the gui element
2009                         std::wstring whole;
2010                         // This will correspond to the line number counted from
2011                         // top to bottom, from size-1 to 0
2012                         s16 line_number = chat_lines.size();
2013                         // Count of messages to be removed from the top
2014                         u16 to_be_removed_count = 0;
2015                         for(core::list<ChatLine>::Iterator
2016                                         i = chat_lines.begin();
2017                                         i != chat_lines.end(); i++)
2018                         {
2019                                 // After this, line number is valid for this loop
2020                                 line_number--;
2021                                 // Increment age
2022                                 (*i).age += dtime;
2023                                 /*
2024                                         This results in a maximum age of 60*6 to the
2025                                         lowermost line and a maximum of 6 lines
2026                                 */
2027                                 float allowed_age = (6-line_number) * 60.0;
2028
2029                                 if((*i).age > allowed_age)
2030                                 {
2031                                         to_be_removed_count++;
2032                                         continue;
2033                                 }
2034                                 whole += (*i).text + L'\n';
2035                         }
2036                         for(u16 i=0; i<to_be_removed_count; i++)
2037                         {
2038                                 core::list<ChatLine>::Iterator
2039                                                 it = chat_lines.begin();
2040                                 chat_lines.erase(it);
2041                         }
2042                         guitext_chat->setText(whole.c_str());
2043
2044                         // Update gui element size and position
2045
2046                         /*core::rect<s32> rect(
2047                                         10,
2048                                         screensize.Y - guitext_chat_pad_bottom
2049                                                         - text_height*chat_lines.size(),
2050                                         screensize.X - 10,
2051                                         screensize.Y - guitext_chat_pad_bottom
2052                         );*/
2053                         core::rect<s32> rect(
2054                                         10,
2055                                         50,
2056                                         screensize.X - 10,
2057                                         50 + guitext_chat->getTextHeight()
2058                         );
2059
2060                         guitext_chat->setRelativePosition(rect);
2061
2062                         if(chat_lines.size() == 0)
2063                                 guitext_chat->setVisible(false);
2064                         else
2065                                 guitext_chat->setVisible(true);
2066                 }
2067
2068                 /*
2069                         Inventory
2070                 */
2071                 
2072                 static u16 old_selected_item = 65535;
2073                 if(client.getLocalInventoryUpdated()
2074                                 || g_selected_item != old_selected_item)
2075                 {
2076                         old_selected_item = g_selected_item;
2077                         //std::cout<<"Updating local inventory"<<std::endl;
2078                         client.getLocalInventory(local_inventory);
2079                 }
2080                 
2081                 /*
2082                         Send actions returned by the inventory menu
2083                 */
2084                 while(inventory_action_queue.size() != 0)
2085                 {
2086                         InventoryAction *a = inventory_action_queue.pop_front();
2087
2088                         client.sendInventoryAction(a);
2089                         // Eat it
2090                         delete a;
2091                 }
2092
2093                 /*
2094                         Drawing begins
2095                 */
2096
2097                 TimeTaker drawtimer("Drawing");
2098
2099                 
2100                 {
2101                         TimeTaker timer("beginScene");
2102                         driver->beginScene(true, true, bgcolor);
2103                         //driver->beginScene(false, true, bgcolor);
2104                         beginscenetime = timer.stop(true);
2105                 }
2106                 
2107                 //timer3.stop();
2108                 
2109                 //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;
2110                 
2111                 {
2112                         TimeTaker timer("smgr");
2113                         smgr->drawAll();
2114                         scenetime = timer.stop(true);
2115                 }
2116                 
2117                 {
2118                 //TimeTaker timer9("auxiliary drawings");
2119                 // 0ms
2120                 
2121                 //timer9.stop();
2122                 //TimeTaker //timer10("//timer10");
2123                 
2124                 video::SMaterial m;
2125                 //m.Thickness = 10;
2126                 m.Thickness = 3;
2127                 m.Lighting = false;
2128                 driver->setMaterial(m);
2129
2130                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2131
2132                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
2133                                 i != hilightboxes.end(); i++)
2134                 {
2135                         /*std::cout<<"hilightbox min="
2136                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2137                                         <<" max="
2138                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2139                                         <<std::endl;*/
2140                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
2141                 }
2142
2143                 /*
2144                         Frametime log
2145                 */
2146                 if(g_settings.getBool("frametime_graph") == true)
2147                 {
2148                         s32 x = 10;
2149                         for(core::list<float>::Iterator
2150                                         i = frametime_log.begin();
2151                                         i != frametime_log.end();
2152                                         i++)
2153                         {
2154                                 driver->draw2DLine(v2s32(x,50),
2155                                                 v2s32(x,50+(*i)*1000),
2156                                                 video::SColor(255,255,255,255));
2157                                 x++;
2158                         }
2159                 }
2160
2161                 /*
2162                         Draw crosshair
2163                 */
2164                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2165                                 displaycenter + core::vector2d<s32>(10,0),
2166                                 video::SColor(255,255,255,255));
2167                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2168                                 displaycenter + core::vector2d<s32>(0,10),
2169                                 video::SColor(255,255,255,255));
2170
2171                 } // timer
2172
2173                 //timer10.stop();
2174                 //TimeTaker //timer11("//timer11");
2175
2176                 /*
2177                         Draw gui
2178                 */
2179                 // 0-1ms
2180                 guienv->drawAll();
2181
2182                 /*
2183                         Draw hotbar
2184                 */
2185                 {
2186                         draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
2187                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2188                                         client.getHP());
2189                 }
2190
2191                 /*
2192                         Damage flash
2193                 */
2194                 if(damage_flash_timer > 0.0)
2195                 {
2196                         damage_flash_timer -= dtime;
2197                         
2198                         video::SColor color(128,255,0,0);
2199                         driver->draw2DRectangle(color,
2200                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2201                                         NULL);
2202                 }
2203                 
2204                 /*
2205                         End scene
2206                 */
2207                 {
2208                         TimeTaker timer("endScene");
2209                         endSceneX(driver);
2210                         endscenetime = timer.stop(true);
2211                 }
2212
2213                 drawtime = drawtimer.stop(true);
2214
2215                 /*
2216                         End of drawing
2217                 */
2218
2219                 static s16 lastFPS = 0;
2220                 //u16 fps = driver->getFPS();
2221                 u16 fps = (1.0/dtime_avg1);
2222
2223                 if (lastFPS != fps)
2224                 {
2225                         core::stringw str = L"Minetest [";
2226                         str += driver->getName();
2227                         str += "] FPS=";
2228                         str += fps;
2229
2230                         device->setWindowCaption(str.c_str());
2231                         lastFPS = fps;
2232                 }
2233         }
2234
2235         /*
2236                 Drop stuff
2237         */
2238         if(clouds)
2239                 clouds->drop();
2240         
2241         /*
2242                 Draw a "shutting down" screen, which will be shown while the map
2243                 generator and other stuff quits
2244         */
2245         {
2246                 const wchar_t *shuttingdowntext = L"Shutting down stuff...";
2247                 gui::IGUIStaticText *gui_shuttingdowntext = guienv->addStaticText(
2248                                 shuttingdowntext, textrect, false, false);
2249                 gui_shuttingdowntext->setTextAlignment(gui::EGUIA_CENTER,
2250                                 gui::EGUIA_UPPERLEFT);
2251                 driver->beginScene(true, true, video::SColor(255,0,0,0));
2252                 guienv->drawAll();
2253                 driver->endScene();
2254                 gui_shuttingdowntext->remove();
2255         }
2256 }
2257
2258