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