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