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