d39b5b7ba215a8851e7b4758f0ac2a0af30f0c8b
[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);
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         
1040         bool invert_mouse = g_settings->getBool("invert_mouse");
1041
1042         bool respawn_menu_active = false;
1043         bool update_wielded_item_trigger = false;
1044
1045         bool show_hud = true;
1046         bool show_chat = true;
1047         bool force_fog_off = false;
1048         bool disable_camera_update = false;
1049         bool show_debug = g_settings->getBool("show_debug");
1050         bool show_debug_frametime = false;
1051         u32 show_profiler = 0;
1052         u32 show_profiler_max = 3;  // Number of pages
1053
1054         /*
1055                 Main loop
1056         */
1057
1058         bool first_loop_after_window_activation = true;
1059
1060         // TODO: Convert the static interval timers to these
1061         // Interval limiter for profiler
1062         IntervalLimiter m_profiler_interval;
1063
1064         // Time is in milliseconds
1065         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1066         // NOTE: So we have to use getTime() and call run()s between them
1067         u32 lasttime = device->getTimer()->getTime();
1068
1069         while(device->run() && kill == false)
1070         {
1071                 //std::cerr<<"frame"<<std::endl;
1072
1073                 if(client.accessDenied())
1074                 {
1075                         error_message = L"Access denied. Reason: "
1076                                         +client.accessDeniedReason();
1077                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1078                         break;
1079                 }
1080
1081                 if(g_gamecallback->disconnect_requested)
1082                 {
1083                         g_gamecallback->disconnect_requested = false;
1084                         break;
1085                 }
1086
1087                 if(g_gamecallback->changepassword_requested)
1088                 {
1089                         (new GUIPasswordChange(guienv, guiroot, -1,
1090                                 &g_menumgr, &client))->drop();
1091                         g_gamecallback->changepassword_requested = false;
1092                 }
1093
1094                 /*
1095                         Process TextureSource's queue
1096                 */
1097                 tsrc->processQueue();
1098
1099                 /*
1100                         Random calculations
1101                 */
1102                 last_screensize = screensize;
1103                 screensize = driver->getScreenSize();
1104                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1105                 //bool screensize_changed = screensize != last_screensize;
1106
1107                 // Resize hotbar
1108                 if(screensize.Y <= 800)
1109                         hotbar_imagesize = 32;
1110                 else if(screensize.Y <= 1280)
1111                         hotbar_imagesize = 48;
1112                 else
1113                         hotbar_imagesize = 64;
1114                 
1115                 // Hilight boxes collected during the loop and displayed
1116                 core::list< core::aabbox3d<f32> > hilightboxes;
1117                 
1118                 // Info text
1119                 std::wstring infotext;
1120
1121                 // When screen size changes, update positions and sizes of stuff
1122                 /*if(screensize_changed)
1123                 {
1124                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
1125                         quick_inventory->updatePosition(pos);
1126                 }*/
1127
1128                 //TimeTaker //timer1("//timer1");
1129                 
1130                 // Time of frame without fps limit
1131                 float busytime;
1132                 u32 busytime_u32;
1133                 {
1134                         // not using getRealTime is necessary for wine
1135                         u32 time = device->getTimer()->getTime();
1136                         if(time > lasttime)
1137                                 busytime_u32 = time - lasttime;
1138                         else
1139                                 busytime_u32 = 0;
1140                         busytime = busytime_u32 / 1000.0;
1141                 }
1142
1143                 //infostream<<"busytime_u32="<<busytime_u32<<std::endl;
1144         
1145                 // Necessary for device->getTimer()->getTime()
1146                 device->run();
1147
1148                 /*
1149                         FPS limiter
1150                 */
1151
1152                 {
1153                         float fps_max = g_settings->getFloat("fps_max");
1154                         u32 frametime_min = 1000./fps_max;
1155                         
1156                         if(busytime_u32 < frametime_min)
1157                         {
1158                                 u32 sleeptime = frametime_min - busytime_u32;
1159                                 device->sleep(sleeptime);
1160                         }
1161                 }
1162
1163                 // Necessary for device->getTimer()->getTime()
1164                 device->run();
1165
1166                 /*
1167                         Time difference calculation
1168                 */
1169                 f32 dtime; // in seconds
1170                 
1171                 u32 time = device->getTimer()->getTime();
1172                 if(time > lasttime)
1173                         dtime = (time - lasttime) / 1000.0;
1174                 else
1175                         dtime = 0;
1176                 lasttime = time;
1177
1178                 /* Run timers */
1179
1180                 if(nodig_delay_timer >= 0)
1181                         nodig_delay_timer -= dtime;
1182                 if(object_hit_delay_timer >= 0)
1183                         object_hit_delay_timer -= dtime;
1184
1185                 g_profiler->add("Elapsed time", dtime);
1186                 g_profiler->avg("FPS", 1./dtime);
1187
1188                 /*
1189                         Log frametime for visualization
1190                 */
1191                 frametime_log.push_back(dtime);
1192                 if(frametime_log.size() > 100)
1193                 {
1194                         core::list<float>::Iterator i = frametime_log.begin();
1195                         frametime_log.erase(i);
1196                 }
1197
1198                 /*
1199                         Visualize frametime in terminal
1200                 */
1201                 /*for(u32 i=0; i<dtime*400; i++)
1202                         infostream<<"X";
1203                 infostream<<std::endl;*/
1204
1205                 /*
1206                         Time average and jitter calculation
1207                 */
1208
1209                 static f32 dtime_avg1 = 0.0;
1210                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1211                 f32 dtime_jitter1 = dtime - dtime_avg1;
1212
1213                 static f32 dtime_jitter1_max_sample = 0.0;
1214                 static f32 dtime_jitter1_max_fraction = 0.0;
1215                 {
1216                         static f32 jitter1_max = 0.0;
1217                         static f32 counter = 0.0;
1218                         if(dtime_jitter1 > jitter1_max)
1219                                 jitter1_max = dtime_jitter1;
1220                         counter += dtime;
1221                         if(counter > 0.0)
1222                         {
1223                                 counter -= 3.0;
1224                                 dtime_jitter1_max_sample = jitter1_max;
1225                                 dtime_jitter1_max_fraction
1226                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1227                                 jitter1_max = 0.0;
1228                         }
1229                 }
1230                 
1231                 /*
1232                         Busytime average and jitter calculation
1233                 */
1234
1235                 static f32 busytime_avg1 = 0.0;
1236                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1237                 f32 busytime_jitter1 = busytime - busytime_avg1;
1238                 
1239                 static f32 busytime_jitter1_max_sample = 0.0;
1240                 static f32 busytime_jitter1_min_sample = 0.0;
1241                 {
1242                         static f32 jitter1_max = 0.0;
1243                         static f32 jitter1_min = 0.0;
1244                         static f32 counter = 0.0;
1245                         if(busytime_jitter1 > jitter1_max)
1246                                 jitter1_max = busytime_jitter1;
1247                         if(busytime_jitter1 < jitter1_min)
1248                                 jitter1_min = busytime_jitter1;
1249                         counter += dtime;
1250                         if(counter > 0.0){
1251                                 counter -= 3.0;
1252                                 busytime_jitter1_max_sample = jitter1_max;
1253                                 busytime_jitter1_min_sample = jitter1_min;
1254                                 jitter1_max = 0.0;
1255                                 jitter1_min = 0.0;
1256                         }
1257                 }
1258                 
1259                 /*
1260                         Debug info for client
1261                 */
1262                 {
1263                         static float counter = 0.0;
1264                         counter -= dtime;
1265                         if(counter < 0)
1266                         {
1267                                 counter = 30.0;
1268                                 client.printDebugInfo(infostream);
1269                         }
1270                 }
1271
1272                 /*
1273                         Profiler
1274                 */
1275                 float profiler_print_interval =
1276                                 g_settings->getFloat("profiler_print_interval");
1277                 bool print_to_log = true;
1278                 if(profiler_print_interval == 0){
1279                         print_to_log = false;
1280                         profiler_print_interval = 5;
1281                 }
1282                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1283                 {
1284                         if(print_to_log){
1285                                 infostream<<"Profiler:"<<std::endl;
1286                                 g_profiler->print(infostream);
1287                         }
1288
1289                         update_profiler_gui(guitext_profiler, font, text_height,
1290                                         show_profiler, show_profiler_max);
1291
1292                         g_profiler->clear();
1293                 }
1294
1295                 /*
1296                         Direct handling of user input
1297                 */
1298                 
1299                 // Reset input if window not active or some menu is active
1300                 if(device->isWindowActive() == false || noMenuActive() == false)
1301                 {
1302                         input->clear();
1303                 }
1304
1305                 // Input handler step() (used by the random input generator)
1306                 input->step(dtime);
1307
1308                 /*
1309                         Launch menus and trigger stuff according to keys
1310                 */
1311                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1312                 {
1313                         // drop selected item
1314                         IDropAction *a = new IDropAction();
1315                         a->count = 0;
1316                         a->from_inv.setCurrentPlayer();
1317                         a->from_list = "main";
1318                         a->from_i = client.getPlayerItem();
1319                         client.inventoryAction(a);
1320                 }
1321                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1322                 {
1323                         infostream<<"the_game: "
1324                                         <<"Launching inventory"<<std::endl;
1325                         
1326                         GUIInventoryMenu *menu =
1327                                 new GUIInventoryMenu(guienv, guiroot, -1,
1328                                         &g_menumgr, v2s16(8,7),
1329                                         &client, gamedef);
1330
1331                         InventoryLocation inventoryloc;
1332                         inventoryloc.setCurrentPlayer();
1333
1334                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1335                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1336                                         "list", inventoryloc, "main",
1337                                         v2s32(0, 3), v2s32(8, 4)));
1338                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1339                                         "list", inventoryloc, "craft",
1340                                         v2s32(3, 0), v2s32(3, 3)));
1341                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1342                                         "list", inventoryloc, "craftpreview",
1343                                         v2s32(7, 1), v2s32(1, 1)));
1344
1345                         menu->setDrawSpec(draw_spec);
1346
1347                         menu->drop();
1348                 }
1349                 else if(input->wasKeyDown(EscapeKey))
1350                 {
1351                         infostream<<"the_game: "
1352                                         <<"Launching pause menu"<<std::endl;
1353                         // It will delete itself by itself
1354                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1355                                         &g_menumgr))->drop();
1356
1357                         // Move mouse cursor on top of the disconnect button
1358                         input->setMousePos(displaycenter.X, displaycenter.Y+25);
1359                 }
1360                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1361                 {
1362                         TextDest *dest = new TextDestChat(&client);
1363
1364                         (new GUITextInputMenu(guienv, guiroot, -1,
1365                                         &g_menumgr, dest,
1366                                         L""))->drop();
1367                 }
1368                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1369                 {
1370                         TextDest *dest = new TextDestChat(&client);
1371
1372                         (new GUITextInputMenu(guienv, guiroot, -1,
1373                                         &g_menumgr, dest,
1374                                         L"/"))->drop();
1375                 }
1376                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1377                 {
1378                         if(g_settings->getBool("free_move"))
1379                         {
1380                                 g_settings->set("free_move","false");
1381                                 statustext = L"free_move disabled";
1382                                 statustext_time = 0;
1383                         }
1384                         else
1385                         {
1386                                 g_settings->set("free_move","true");
1387                                 statustext = L"free_move enabled";
1388                                 statustext_time = 0;
1389                         }
1390                 }
1391                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1392                 {
1393                         if(g_settings->getBool("fast_move"))
1394                         {
1395                                 g_settings->set("fast_move","false");
1396                                 statustext = L"fast_move disabled";
1397                                 statustext_time = 0;
1398                         }
1399                         else
1400                         {
1401                                 g_settings->set("fast_move","true");
1402                                 statustext = L"fast_move enabled";
1403                                 statustext_time = 0;
1404                         }
1405                 }
1406                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1407                 {
1408                         irr::video::IImage* const image = driver->createScreenShot(); 
1409                         if (image) { 
1410                                 irr::c8 filename[256]; 
1411                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1412                                                  g_settings->get("screenshot_path").c_str(),
1413                                                  device->getTimer()->getRealTime()); 
1414                                 if (driver->writeImageToFile(image, filename)) {
1415                                         std::wstringstream sstr;
1416                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1417                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1418                                         statustext = sstr.str();
1419                                         statustext_time = 0;
1420                                 } else{
1421                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1422                                 }
1423                                 image->drop(); 
1424                         }                        
1425                 }
1426                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1427                 {
1428                         show_hud = !show_hud;
1429                         if(show_hud)
1430                                 statustext = L"HUD shown";
1431                         else
1432                                 statustext = L"HUD hidden";
1433                         statustext_time = 0;
1434                 }
1435                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1436                 {
1437                         show_chat = !show_chat;
1438                         if(show_chat)
1439                                 statustext = L"Chat shown";
1440                         else
1441                                 statustext = L"Chat hidden";
1442                         statustext_time = 0;
1443                 }
1444                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1445                 {
1446                         force_fog_off = !force_fog_off;
1447                         if(force_fog_off)
1448                                 statustext = L"Fog disabled";
1449                         else
1450                                 statustext = L"Fog enabled";
1451                         statustext_time = 0;
1452                 }
1453                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1454                 {
1455                         disable_camera_update = !disable_camera_update;
1456                         if(disable_camera_update)
1457                                 statustext = L"Camera update disabled";
1458                         else
1459                                 statustext = L"Camera update enabled";
1460                         statustext_time = 0;
1461                 }
1462                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1463                 {
1464                         // Initial / 3x toggle: Chat only
1465                         // 1x toggle: Debug text with chat
1466                         // 2x toggle: Debug text with frametime
1467                         if(!show_debug)
1468                         {
1469                                 show_debug = true;
1470                                 show_debug_frametime = false;
1471                                 statustext = L"Debug info shown";
1472                                 statustext_time = 0;
1473                         }
1474                         else if(show_debug_frametime)
1475                         {
1476                                 show_debug = false;
1477                                 show_debug_frametime = false;
1478                                 statustext = L"Debug info and frametime graph hidden";
1479                                 statustext_time = 0;
1480                         }
1481                         else
1482                         {
1483                                 show_debug_frametime = true;
1484                                 statustext = L"Frametime graph shown";
1485                                 statustext_time = 0;
1486                         }
1487                 }
1488                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1489                 {
1490                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1491
1492                         // FIXME: This updates the profiler with incomplete values
1493                         update_profiler_gui(guitext_profiler, font, text_height,
1494                                         show_profiler, show_profiler_max);
1495
1496                         if(show_profiler != 0)
1497                         {
1498                                 std::wstringstream sstr;
1499                                 sstr<<"Profiler shown (page "<<show_profiler
1500                                         <<" of "<<show_profiler_max<<")";
1501                                 statustext = sstr.str();
1502                                 statustext_time = 0;
1503                         }
1504                         else
1505                         {
1506                                 statustext = L"Profiler hidden";
1507                                 statustext_time = 0;
1508                         }
1509                 }
1510                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1511                 {
1512                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1513                         s16 range_new = range + 10;
1514                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1515                         statustext = narrow_to_wide(
1516                                         "Minimum viewing range changed to "
1517                                         + itos(range_new));
1518                         statustext_time = 0;
1519                 }
1520                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1521                 {
1522                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1523                         s16 range_new = range - 10;
1524                         if(range_new < 0)
1525                                 range_new = range;
1526                         g_settings->set("viewing_range_nodes_min",
1527                                         itos(range_new));
1528                         statustext = narrow_to_wide(
1529                                         "Minimum viewing range changed to "
1530                                         + itos(range_new));
1531                         statustext_time = 0;
1532                 }
1533
1534                 // Item selection with mouse wheel
1535                 u16 new_playeritem = client.getPlayerItem();
1536                 {
1537                         s32 wheel = input->getMouseWheel();
1538                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1539                                         hotbar_itemcount-1);
1540
1541                         if(wheel < 0)
1542                         {
1543                                 if(new_playeritem < max_item)
1544                                         new_playeritem++;
1545                                 else
1546                                         new_playeritem = 0;
1547                         }
1548                         else if(wheel > 0)
1549                         {
1550                                 if(new_playeritem > 0)
1551                                         new_playeritem--;
1552                                 else
1553                                         new_playeritem = max_item;
1554                         }
1555                 }
1556                 
1557                 // Item selection
1558                 for(u16 i=0; i<10; i++)
1559                 {
1560                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1561                         if(input->wasKeyDown(*kp))
1562                         {
1563                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1564                                 {
1565                                         new_playeritem = i;
1566
1567                                         infostream<<"Selected item: "
1568                                                         <<new_playeritem<<std::endl;
1569                                 }
1570                         }
1571                 }
1572
1573                 // Viewing range selection
1574                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1575                 {
1576                         draw_control.range_all = !draw_control.range_all;
1577                         if(draw_control.range_all)
1578                         {
1579                                 infostream<<"Enabled full viewing range"<<std::endl;
1580                                 statustext = L"Enabled full viewing range";
1581                                 statustext_time = 0;
1582                         }
1583                         else
1584                         {
1585                                 infostream<<"Disabled full viewing range"<<std::endl;
1586                                 statustext = L"Disabled full viewing range";
1587                                 statustext_time = 0;
1588                         }
1589                 }
1590
1591                 // Print debug stacks
1592                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1593                 {
1594                         dstream<<"-----------------------------------------"
1595                                         <<std::endl;
1596                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1597                         dstream<<"-----------------------------------------"
1598                                         <<std::endl;
1599                         debug_stacks_print();
1600                 }
1601
1602                 /*
1603                         Mouse and camera control
1604                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1605                 */
1606                 
1607                 if((device->isWindowActive() && noMenuActive()) || random_input)
1608                 {
1609                         if(!random_input)
1610                         {
1611                                 // Mac OSX gets upset if this is set every frame
1612                                 if(device->getCursorControl()->isVisible())
1613                                         device->getCursorControl()->setVisible(false);
1614                         }
1615
1616                         if(first_loop_after_window_activation){
1617                                 //infostream<<"window active, first loop"<<std::endl;
1618                                 first_loop_after_window_activation = false;
1619                         }
1620                         else{
1621                                 s32 dx = input->getMousePos().X - displaycenter.X;
1622                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1623                                 if(invert_mouse)
1624                                         dy = -dy;
1625                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1626                                 
1627                                 /*const float keyspeed = 500;
1628                                 if(input->isKeyDown(irr::KEY_UP))
1629                                         dy -= dtime * keyspeed;
1630                                 if(input->isKeyDown(irr::KEY_DOWN))
1631                                         dy += dtime * keyspeed;
1632                                 if(input->isKeyDown(irr::KEY_LEFT))
1633                                         dx -= dtime * keyspeed;
1634                                 if(input->isKeyDown(irr::KEY_RIGHT))
1635                                         dx += dtime * keyspeed;*/
1636
1637                                 camera_yaw -= dx*0.2;
1638                                 camera_pitch += dy*0.2;
1639                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1640                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1641                         }
1642                         input->setMousePos(displaycenter.X, displaycenter.Y);
1643                 }
1644                 else{
1645                         // Mac OSX gets upset if this is set every frame
1646                         if(device->getCursorControl()->isVisible() == false)
1647                                 device->getCursorControl()->setVisible(true);
1648
1649                         //infostream<<"window inactive"<<std::endl;
1650                         first_loop_after_window_activation = true;
1651                 }
1652
1653                 /*
1654                         Player speed control
1655                 */
1656                 
1657                 if(!noMenuActive() || !device->isWindowActive())
1658                 {
1659                         PlayerControl control(
1660                                 false,
1661                                 false,
1662                                 false,
1663                                 false,
1664                                 false,
1665                                 false,
1666                                 false,
1667                                 camera_pitch,
1668                                 camera_yaw
1669                         );
1670                         client.setPlayerControl(control);
1671                 }
1672                 else
1673                 {
1674                         /*bool a_up,
1675                         bool a_down,
1676                         bool a_left,
1677                         bool a_right,
1678                         bool a_jump,
1679                         bool a_superspeed,
1680                         bool a_sneak,
1681                         float a_pitch,
1682                         float a_yaw*/
1683                         PlayerControl control(
1684                                 input->isKeyDown(getKeySetting("keymap_forward")),
1685                                 input->isKeyDown(getKeySetting("keymap_backward")),
1686                                 input->isKeyDown(getKeySetting("keymap_left")),
1687                                 input->isKeyDown(getKeySetting("keymap_right")),
1688                                 input->isKeyDown(getKeySetting("keymap_jump")),
1689                                 input->isKeyDown(getKeySetting("keymap_special1")),
1690                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1691                                 camera_pitch,
1692                                 camera_yaw
1693                         );
1694                         client.setPlayerControl(control);
1695                 }
1696                 
1697                 /*
1698                         Run server
1699                 */
1700
1701                 if(server != NULL)
1702                 {
1703                         //TimeTaker timer("server->step(dtime)");
1704                         server->step(dtime);
1705                 }
1706
1707                 /*
1708                         Process environment
1709                 */
1710                 
1711                 {
1712                         //TimeTaker timer("client.step(dtime)");
1713                         client.step(dtime);
1714                         //client.step(dtime_avg1);
1715                 }
1716
1717                 {
1718                         // Read client events
1719                         for(;;)
1720                         {
1721                                 ClientEvent event = client.getClientEvent();
1722                                 if(event.type == CE_NONE)
1723                                 {
1724                                         break;
1725                                 }
1726                                 else if(event.type == CE_PLAYER_DAMAGE)
1727                                 {
1728                                         //u16 damage = event.player_damage.amount;
1729                                         //infostream<<"Player damage: "<<damage<<std::endl;
1730                                         damage_flash_timer = 0.05;
1731                                         if(event.player_damage.amount >= 2){
1732                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1733                                         }
1734                                 }
1735                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1736                                 {
1737                                         camera_yaw = event.player_force_move.yaw;
1738                                         camera_pitch = event.player_force_move.pitch;
1739                                 }
1740                                 else if(event.type == CE_DEATHSCREEN)
1741                                 {
1742                                         if(respawn_menu_active)
1743                                                 continue;
1744
1745                                         /*bool set_camera_point_target =
1746                                                         event.deathscreen.set_camera_point_target;
1747                                         v3f camera_point_target;
1748                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1749                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1750                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1751                                         MainRespawnInitiator *respawner =
1752                                                         new MainRespawnInitiator(
1753                                                                         &respawn_menu_active, &client);
1754                                         GUIDeathScreen *menu =
1755                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1756                                                                 &g_menumgr, respawner);
1757                                         menu->drop();
1758                                         
1759                                         /* Handle visualization */
1760
1761                                         damage_flash_timer = 0;
1762
1763                                         /*LocalPlayer* player = client.getLocalPlayer();
1764                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1765                                         camera.update(player, busytime, screensize);*/
1766                                 }
1767                                 else if(event.type == CE_TEXTURES_UPDATED)
1768                                 {
1769                                         update_skybox(driver, tsrc, smgr, skybox, brightness);
1770                                         
1771                                         update_wielded_item_trigger = true;
1772                                 }
1773                         }
1774                 }
1775                 
1776                 //TimeTaker //timer2("//timer2");
1777
1778                 LocalPlayer* player = client.getLocalPlayer();
1779                 camera.update(player, busytime, screensize);
1780                 camera.step(dtime);
1781
1782                 v3f player_position = player->getPosition();
1783                 v3f camera_position = camera.getPosition();
1784                 v3f camera_direction = camera.getDirection();
1785                 f32 camera_fov = camera.getFovMax();
1786                 
1787                 if(!disable_camera_update){
1788                         client.updateCamera(camera_position,
1789                                 camera_direction, camera_fov);
1790                 }
1791
1792                 //timer2.stop();
1793                 //TimeTaker //timer3("//timer3");
1794
1795                 /*
1796                         For interaction purposes, get info about the held item
1797                         - What item is it?
1798                         - Is it a usable item?
1799                         - Can it point to liquids?
1800                 */
1801                 ItemStack playeritem;
1802                 bool playeritem_usable = false;
1803                 bool playeritem_liquids_pointable = false;
1804                 {
1805                         InventoryList *mlist = local_inventory.getList("main");
1806                         if(mlist != NULL)
1807                         {
1808                                 playeritem = mlist->getItem(client.getPlayerItem());
1809                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1810                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1811                         }
1812                 }
1813
1814                 /*
1815                         Calculate what block is the crosshair pointing to
1816                 */
1817                 
1818                 //u32 t1 = device->getTimer()->getRealTime();
1819                 
1820                 f32 d = 4; // max. distance
1821                 core::line3d<f32> shootline(camera_position,
1822                                 camera_position + camera_direction * BS * (d+1));
1823
1824                 core::aabbox3d<f32> hilightbox;
1825                 bool should_show_hilightbox = false;
1826                 ClientActiveObject *selected_object = NULL;
1827
1828                 PointedThing pointed = getPointedThing(
1829                                 // input
1830                                 &client, player_position, camera_direction,
1831                                 camera_position, shootline, d,
1832                                 playeritem_liquids_pointable, !ldown_for_dig,
1833                                 // output
1834                                 hilightbox, should_show_hilightbox,
1835                                 selected_object);
1836
1837                 if(pointed != pointed_old)
1838                 {
1839                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1840                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1841                 }
1842
1843                 /*
1844                         Visualize selection
1845                 */
1846                 if(should_show_hilightbox)
1847                         hilightboxes.push_back(hilightbox);
1848
1849                 /*
1850                         Stop digging when
1851                         - releasing left mouse button
1852                         - pointing away from node
1853                 */
1854                 if(digging)
1855                 {
1856                         if(input->getLeftReleased())
1857                         {
1858                                 infostream<<"Left button released"
1859                                         <<" (stopped digging)"<<std::endl;
1860                                 digging = false;
1861                         }
1862                         else if(pointed != pointed_old)
1863                         {
1864                                 if (pointed.type == POINTEDTHING_NODE
1865                                         && pointed_old.type == POINTEDTHING_NODE
1866                                         && pointed.node_undersurface == pointed_old.node_undersurface)
1867                                 {
1868                                         // Still pointing to the same node,
1869                                         // but a different face. Don't reset.
1870                                 }
1871                                 else
1872                                 {
1873                                         infostream<<"Pointing away from node"
1874                                                 <<" (stopped digging)"<<std::endl;
1875                                         digging = false;
1876                                 }
1877                         }
1878                         if(!digging)
1879                         {
1880                                 client.interact(1, pointed_old);
1881                                 client.clearTempMod(pointed_old.node_undersurface);
1882                                 dig_time = 0.0;
1883                         }
1884                 }
1885                 if(!digging && ldown_for_dig && !input->getLeftState())
1886                 {
1887                         ldown_for_dig = false;
1888                 }
1889
1890                 bool left_punch = false;
1891                 bool left_punch_muted = false;
1892
1893                 if(playeritem_usable && input->getLeftState())
1894                 {
1895                         if(input->getLeftClicked())
1896                                 client.interact(4, pointed);
1897                 }
1898                 else if(pointed.type == POINTEDTHING_NODE)
1899                 {
1900                         v3s16 nodepos = pointed.node_undersurface;
1901                         v3s16 neighbourpos = pointed.node_abovesurface;
1902
1903                         /*
1904                                 Check information text of node
1905                         */
1906
1907                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1908                         if(meta)
1909                         {
1910                                 infotext = narrow_to_wide(meta->infoText());
1911                         }
1912                         else
1913                         {
1914                                 MapNode n = client.getNode(nodepos);
1915                                 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
1916                                         infotext = L"Unknown node: ";
1917                                         infotext += narrow_to_wide(nodedef->get(n).name);
1918                                 }
1919                         }
1920                         
1921                         /*
1922                                 Handle digging
1923                         */
1924                         
1925                         
1926                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
1927                         {
1928                                 if(!digging)
1929                                 {
1930                                         infostream<<"Started digging"<<std::endl;
1931                                         client.interact(0, pointed);
1932                                         digging = true;
1933                                         ldown_for_dig = true;
1934                                 }
1935                                 MapNode n = client.getNode(nodepos);
1936
1937                                 // Get digging properties for material and tool
1938                                 ToolCapabilities tp = playeritem.getToolCapabilities(itemdef);
1939                                 DigParams params = getDigParams(nodedef->get(n).groups, &tp);
1940                                 // If can't dig, try hand
1941                                 if(!params.diggable){
1942                                         const ItemDefinition &hand = itemdef->get("");
1943                                         const ToolCapabilities *tp = hand.tool_capabilities;
1944                                         if(tp)
1945                                                 params = getDigParams(nodedef->get(n).groups, tp);
1946                                 }
1947
1948                                 float dig_time_complete = 0.0;
1949
1950                                 if(params.diggable == false)
1951                                 {
1952                                         // I guess nobody will wait for this long
1953                                         dig_time_complete = 10000000.0;
1954                                 }
1955                                 else
1956                                 {
1957                                         dig_time_complete = params.time;
1958                                 }
1959
1960                                 if(dig_time_complete >= 0.001)
1961                                 {
1962                                         dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1963                                                         * dig_time/dig_time_complete);
1964                                 }
1965                                 // This is for torches
1966                                 else
1967                                 {
1968                                         dig_index = CRACK_ANIMATION_LENGTH;
1969                                 }
1970                                 
1971                                 // Don't show cracks if not diggable
1972                                 if(dig_time_complete >= 100000.0)
1973                                 {
1974                                 }
1975                                 else if(dig_index < CRACK_ANIMATION_LENGTH)
1976                                 {
1977                                         //TimeTaker timer("client.setTempMod");
1978                                         //infostream<<"dig_index="<<dig_index<<std::endl;
1979                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1980                                 }
1981                                 else
1982                                 {
1983                                         infostream<<"Digging completed"<<std::endl;
1984                                         client.interact(2, pointed);
1985                                         client.clearTempMod(nodepos);
1986                                         client.removeNode(nodepos);
1987
1988                                         dig_time = 0;
1989                                         digging = false;
1990
1991                                         nodig_delay_timer = dig_time_complete
1992                                                         / (float)CRACK_ANIMATION_LENGTH;
1993
1994                                         // We don't want a corresponding delay to
1995                                         // very time consuming nodes
1996                                         if(nodig_delay_timer > 0.5)
1997                                         {
1998                                                 nodig_delay_timer = 0.5;
1999                                         }
2000                                         // We want a slight delay to very little
2001                                         // time consuming nodes
2002                                         float mindelay = 0.15;
2003                                         if(nodig_delay_timer < mindelay)
2004                                         {
2005                                                 nodig_delay_timer = mindelay;
2006                                         }
2007                                 }
2008
2009                                 dig_time += dtime;
2010
2011                                 camera.setDigging(0);  // left click animation
2012                         }
2013
2014                         if(input->getRightClicked())
2015                         {
2016                                 infostream<<"Ground right-clicked"<<std::endl;
2017                                 
2018                                 // If metadata provides an inventory view, activate it
2019                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2020                                 {
2021                                         infostream<<"Launching custom inventory view"<<std::endl;
2022
2023                                         InventoryLocation inventoryloc;
2024                                         inventoryloc.setNodeMeta(nodepos);
2025                                         
2026
2027                                         /*
2028                                                 Create menu
2029                                         */
2030
2031                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2032                                         v2s16 invsize =
2033                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
2034                                                         draw_spec,
2035                                                         meta->getInventoryDrawSpecString(),
2036                                                         inventoryloc);
2037
2038                                         GUIInventoryMenu *menu =
2039                                                 new GUIInventoryMenu(guienv, guiroot, -1,
2040                                                         &g_menumgr, invsize,
2041                                                         &client, gamedef);
2042                                         menu->setDrawSpec(draw_spec);
2043                                         menu->drop();
2044                                 }
2045                                 // If metadata provides text input, activate text input
2046                                 else if(meta && meta->allowsTextInput() && !random_input)
2047                                 {
2048                                         infostream<<"Launching metadata text input"<<std::endl;
2049                                         
2050                                         // Get a new text for it
2051
2052                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2053
2054                                         std::wstring wtext = narrow_to_wide(meta->getText());
2055
2056                                         (new GUITextInputMenu(guienv, guiroot, -1,
2057                                                         &g_menumgr, dest,
2058                                                         wtext))->drop();
2059                                 }
2060                                 // Otherwise report right click to server
2061                                 else
2062                                 {
2063                                         client.interact(3, pointed);
2064                                         camera.setDigging(1);  // right click animation
2065                                 }
2066                         }
2067                 }
2068                 else if(pointed.type == POINTEDTHING_OBJECT)
2069                 {
2070                         infotext = narrow_to_wide(selected_object->infoText());
2071
2072                         if(infotext == L"" && show_debug){
2073                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2074                         }
2075
2076                         //if(input->getLeftClicked())
2077                         if(input->getLeftState())
2078                         {
2079                                 bool do_punch = false;
2080                                 bool do_punch_damage = false;
2081                                 if(object_hit_delay_timer <= 0.0){
2082                                         do_punch = true;
2083                                         do_punch_damage = true;
2084                                         object_hit_delay_timer = object_hit_delay;
2085                                 }
2086                                 if(input->getLeftClicked()){
2087                                         do_punch = true;
2088                                 }
2089                                 if(do_punch){
2090                                         infostream<<"Left-clicked object"<<std::endl;
2091                                         left_punch = true;
2092                                 }
2093                                 if(do_punch_damage){
2094                                         // Report direct punch
2095                                         v3f objpos = selected_object->getPosition();
2096                                         v3f dir = (objpos - player_position).normalize();
2097                                         
2098                                         // TODO: Get time_from_last_punch from somewhere
2099                                         float time_from_last_punch = 1000000;
2100                                         bool disable_send = selected_object->directReportPunch(
2101                                                         dir, &playeritem, time_from_last_punch);
2102                                         if(!disable_send)
2103                                                 client.interact(0, pointed);
2104                                 }
2105                         }
2106                         else if(input->getRightClicked())
2107                         {
2108                                 infostream<<"Right-clicked object"<<std::endl;
2109                                 client.interact(3, pointed);  // place
2110                         }
2111                 }
2112
2113                 pointed_old = pointed;
2114                 
2115                 if(left_punch || (input->getLeftClicked() && !left_punch_muted))
2116                 {
2117                         camera.setDigging(0); // left click animation
2118                 }
2119
2120                 input->resetLeftClicked();
2121                 input->resetRightClicked();
2122
2123                 input->resetLeftReleased();
2124                 input->resetRightReleased();
2125                 
2126                 /*
2127                         Calculate stuff for drawing
2128                 */
2129                 
2130                 /*
2131                         Calculate general brightness
2132                 */
2133                 u32 daynight_ratio = client.getDayNightRatio();
2134                 u8 light8 = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
2135                 brightness = (float)light8/255.0;
2136                 // Make night look good
2137                 brightness = brightness * 1.15 - 0.15;
2138                 video::SColor bgcolor;
2139                 if(brightness >= 0.2 && brightness < 0.7)
2140                         bgcolor = video::SColor(
2141                                         255,
2142                                         bgcolor_bright.getRed() * brightness,
2143                                         bgcolor_bright.getGreen() * brightness*0.7,
2144                                         bgcolor_bright.getBlue() * brightness*0.5);
2145                 else
2146                         bgcolor = video::SColor(
2147                                         255,
2148                                         bgcolor_bright.getRed() * brightness,
2149                                         bgcolor_bright.getGreen() * brightness,
2150                                         bgcolor_bright.getBlue() * brightness);
2151
2152                 /*
2153                         Update skybox
2154                 */
2155                 if(fabs(brightness - old_brightness) > 0.01)
2156                         update_skybox(driver, tsrc, smgr, skybox, brightness);
2157
2158                 /*
2159                         Update clouds
2160                 */
2161                 if(clouds)
2162                 {
2163                         clouds->step(dtime);
2164                         clouds->update(v2f(player_position.X, player_position.Z),
2165                                         brightness);
2166                 }
2167                 
2168                 /*
2169                         Update farmesh
2170                 */
2171                 if(farmesh)
2172                 {
2173                         farmesh_range = draw_control.wanted_range * 10;
2174                         if(draw_control.range_all && farmesh_range < 500)
2175                                 farmesh_range = 500;
2176                         if(farmesh_range > 1000)
2177                                 farmesh_range = 1000;
2178
2179                         farmesh->step(dtime);
2180                         farmesh->update(v2f(player_position.X, player_position.Z),
2181                                         brightness, farmesh_range);
2182                 }
2183                 
2184                 // Store brightness value
2185                 old_brightness = brightness;
2186
2187                 /*
2188                         Fog
2189                 */
2190                 
2191                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2192                 {
2193                         f32 range;
2194                         if(farmesh)
2195                         {
2196                                 range = BS*farmesh_range;
2197                         }
2198                         else
2199                         {
2200                                 range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2201                                 range *= 0.9;
2202                                 if(draw_control.range_all)
2203                                         range = 100000*BS;
2204                                 /*if(range < 50*BS)
2205                                         range = range * 0.5 + 25*BS;*/
2206                         }
2207
2208                         driver->setFog(
2209                                 bgcolor,
2210                                 video::EFT_FOG_LINEAR,
2211                                 range*0.4,
2212                                 range*1.0,
2213                                 0.01,
2214                                 false, // pixel fog
2215                                 false // range fog
2216                         );
2217                 }
2218                 else
2219                 {
2220                         driver->setFog(
2221                                 bgcolor,
2222                                 video::EFT_FOG_LINEAR,
2223                                 100000*BS,
2224                                 110000*BS,
2225                                 0.01,
2226                                 false, // pixel fog
2227                                 false // range fog
2228                         );
2229                 }
2230
2231                 /*
2232                         Update gui stuff (0ms)
2233                 */
2234
2235                 //TimeTaker guiupdatetimer("Gui updating");
2236                 
2237                 const char program_name_and_version[] =
2238                         "Minetest-c55 " VERSION_STRING;
2239
2240                 if(show_debug)
2241                 {
2242                         static float drawtime_avg = 0;
2243                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2244                         /*static float beginscenetime_avg = 0;
2245                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2246                         static float scenetime_avg = 0;
2247                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2248                         static float endscenetime_avg = 0;
2249                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2250                         
2251                         char temptext[300];
2252                         snprintf(temptext, 300, "%s ("
2253                                         "R: range_all=%i"
2254                                         ")"
2255                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2256                                         ", v_range = %.1f, RTT = %.3f",
2257                                         program_name_and_version,
2258                                         draw_control.range_all,
2259                                         drawtime_avg,
2260                                         dtime_jitter1_max_fraction * 100.0,
2261                                         draw_control.wanted_range,
2262                                         client.getRTT()
2263                                         );
2264                         
2265                         guitext->setText(narrow_to_wide(temptext).c_str());
2266                         guitext->setVisible(true);
2267                 }
2268                 else if(show_hud || show_chat)
2269                 {
2270                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2271                         guitext->setVisible(true);
2272                 }
2273                 else
2274                 {
2275                         guitext->setVisible(false);
2276                 }
2277                 
2278                 if(show_debug)
2279                 {
2280                         char temptext[300];
2281                         snprintf(temptext, 300,
2282                                         "(% .1f, % .1f, % .1f)"
2283                                         " (yaw = %.1f)",
2284                                         player_position.X/BS,
2285                                         player_position.Y/BS,
2286                                         player_position.Z/BS,
2287                                         wrapDegrees_0_360(camera_yaw));
2288
2289                         guitext2->setText(narrow_to_wide(temptext).c_str());
2290                         guitext2->setVisible(true);
2291                 }
2292                 else
2293                 {
2294                         guitext2->setVisible(false);
2295                 }
2296                 
2297                 {
2298                         guitext_info->setText(infotext.c_str());
2299                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2300                 }
2301
2302                 {
2303                         float statustext_time_max = 3.0;
2304                         if(!statustext.empty())
2305                         {
2306                                 statustext_time += dtime;
2307                                 if(statustext_time >= statustext_time_max)
2308                                 {
2309                                         statustext = L"";
2310                                         statustext_time = 0;
2311                                 }
2312                         }
2313                         guitext_status->setText(statustext.c_str());
2314                         guitext_status->setVisible(!statustext.empty());
2315
2316                         if(!statustext.empty())
2317                         {
2318                                 s32 status_y = screensize.Y - 130;
2319                                 core::rect<s32> rect(
2320                                                 10,
2321                                                 status_y - guitext_status->getTextHeight(),
2322                                                 screensize.X - 10,
2323                                                 status_y
2324                                 );
2325                                 guitext_status->setRelativePosition(rect);
2326
2327                                 // Fade out
2328                                 video::SColor initial_color(255,0,0,0);
2329                                 if(guienv->getSkin())
2330                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2331                                 video::SColor final_color = initial_color;
2332                                 final_color.setAlpha(0);
2333                                 video::SColor fade_color =
2334                                         initial_color.getInterpolated_quadratic(
2335                                                 initial_color,
2336                                                 final_color,
2337                                                 statustext_time / (float) statustext_time_max);
2338                                 guitext_status->setOverrideColor(fade_color);
2339                                 guitext_status->enableOverrideColor(true);
2340                         }
2341                 }
2342                 
2343                 /*
2344                         Get chat messages from client
2345                 */
2346                 {
2347                         // Get new messages from error log buffer
2348                         while(!chat_log_error_buf.empty())
2349                         {
2350                                 chat_lines.push_back(ChatLine(narrow_to_wide(
2351                                                 chat_log_error_buf.get())));
2352                         }
2353                         // Get new messages from client
2354                         std::wstring message;
2355                         while(client.getChatMessage(message))
2356                         {
2357                                 chat_lines.push_back(ChatLine(message));
2358                                 /*if(chat_lines.size() > 6)
2359                                 {
2360                                         core::list<ChatLine>::Iterator
2361                                                         i = chat_lines.begin();
2362                                         chat_lines.erase(i);
2363                                 }*/
2364                         }
2365                         // Append them to form the whole static text and throw
2366                         // it to the gui element
2367                         std::wstring whole;
2368                         // This will correspond to the line number counted from
2369                         // top to bottom, from size-1 to 0
2370                         s16 line_number = chat_lines.size();
2371                         // Count of messages to be removed from the top
2372                         u16 to_be_removed_count = 0;
2373                         for(core::list<ChatLine>::Iterator
2374                                         i = chat_lines.begin();
2375                                         i != chat_lines.end(); i++)
2376                         {
2377                                 // After this, line number is valid for this loop
2378                                 line_number--;
2379                                 // Increment age
2380                                 (*i).age += dtime;
2381                                 /*
2382                                         This results in a maximum age of 60*6 to the
2383                                         lowermost line and a maximum of 6 lines
2384                                 */
2385                                 float allowed_age = (6-line_number) * 60.0;
2386
2387                                 if((*i).age > allowed_age)
2388                                 {
2389                                         to_be_removed_count++;
2390                                         continue;
2391                                 }
2392                                 whole += (*i).text + L'\n';
2393                         }
2394                         for(u16 i=0; i<to_be_removed_count; i++)
2395                         {
2396                                 core::list<ChatLine>::Iterator
2397                                                 it = chat_lines.begin();
2398                                 chat_lines.erase(it);
2399                         }
2400                         guitext_chat->setText(whole.c_str());
2401
2402                         // Update gui element size and position
2403
2404                         /*core::rect<s32> rect(
2405                                         10,
2406                                         screensize.Y - guitext_chat_pad_bottom
2407                                                         - text_height*chat_lines.size(),
2408                                         screensize.X - 10,
2409                                         screensize.Y - guitext_chat_pad_bottom
2410                         );*/
2411
2412                         s32 chat_y = 5+(text_height+5);
2413                         if(show_debug)
2414                                 chat_y += (text_height+5);
2415                         core::rect<s32> rect(
2416                                         10,
2417                                         chat_y,
2418                                         screensize.X - 10,
2419                                         chat_y + guitext_chat->getTextHeight()
2420                         );
2421
2422                         guitext_chat->setRelativePosition(rect);
2423
2424                         // Don't show chat if empty or profiler or debug is enabled
2425                         guitext_chat->setVisible(chat_lines.size() != 0
2426                                         && show_chat && show_profiler == 0);
2427                 }
2428
2429                 /*
2430                         Inventory
2431                 */
2432                 
2433                 if(client.getPlayerItem() != new_playeritem)
2434                 {
2435                         client.selectPlayerItem(new_playeritem);
2436                 }
2437                 if(client.getLocalInventoryUpdated())
2438                 {
2439                         //infostream<<"Updating local inventory"<<std::endl;
2440                         client.getLocalInventory(local_inventory);
2441                         
2442                         update_wielded_item_trigger = true;
2443                 }
2444                 if(update_wielded_item_trigger)
2445                 {
2446                         update_wielded_item_trigger = false;
2447                         // Update wielded tool
2448                         InventoryList *mlist = local_inventory.getList("main");
2449                         ItemStack item;
2450                         if(mlist != NULL)
2451                                 item = mlist->getItem(client.getPlayerItem());
2452                         camera.wield(item, gamedef);
2453                 }
2454                 
2455                 /*
2456                         Drawing begins
2457                 */
2458
2459                 TimeTaker drawtimer("Drawing");
2460
2461                 
2462                 {
2463                         TimeTaker timer("beginScene");
2464                         driver->beginScene(false, true, bgcolor);
2465                         //driver->beginScene(false, true, bgcolor);
2466                         beginscenetime = timer.stop(true);
2467                 }
2468                 
2469                 //timer3.stop();
2470                 
2471                 //infostream<<"smgr->drawAll()"<<std::endl;
2472                 
2473                 {
2474                         TimeTaker timer("smgr");
2475                         smgr->drawAll();
2476                         scenetime = timer.stop(true);
2477                 }
2478                 
2479                 {
2480                 //TimeTaker timer9("auxiliary drawings");
2481                 // 0ms
2482                 
2483                 //timer9.stop();
2484                 //TimeTaker //timer10("//timer10");
2485                 
2486                 video::SMaterial m;
2487                 //m.Thickness = 10;
2488                 m.Thickness = 3;
2489                 m.Lighting = false;
2490                 driver->setMaterial(m);
2491
2492                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2493
2494                 if(show_hud)
2495                 {
2496                         for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2497                                         i != hilightboxes.end(); i++)
2498                         {
2499                                 /*infostream<<"hilightbox min="
2500                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2501                                                 <<" max="
2502                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2503                                                 <<std::endl;*/
2504                                 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2505                         }
2506                 }
2507
2508                 /*
2509                         Wielded tool
2510                 */
2511                 if(show_hud)
2512                 {
2513                         // Warning: This clears the Z buffer.
2514                         camera.drawWieldedTool();
2515                 }
2516
2517                 /*
2518                         Post effects
2519                 */
2520                 {
2521                         client.renderPostFx();
2522                 }
2523
2524                 /*
2525                         Frametime log
2526                 */
2527                 if(show_debug_frametime)
2528                 {
2529                         s32 x = 10;
2530                         s32 y = screensize.Y - 10;
2531                         for(core::list<float>::Iterator
2532                                         i = frametime_log.begin();
2533                                         i != frametime_log.end();
2534                                         i++)
2535                         {
2536                                 driver->draw2DLine(v2s32(x,y),
2537                                                 v2s32(x,y-(*i)*1000),
2538                                                 video::SColor(255,255,255,255));
2539                                 x++;
2540                         }
2541                 }
2542
2543                 /*
2544                         Draw crosshair
2545                 */
2546                 if(show_hud)
2547                 {
2548                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2549                                         displaycenter + core::vector2d<s32>(10,0),
2550                                         video::SColor(255,255,255,255));
2551                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2552                                         displaycenter + core::vector2d<s32>(0,10),
2553                                         video::SColor(255,255,255,255));
2554                 }
2555
2556                 } // timer
2557
2558                 //timer10.stop();
2559                 //TimeTaker //timer11("//timer11");
2560
2561                 /*
2562                         Draw gui
2563                 */
2564                 // 0-1ms
2565                 guienv->drawAll();
2566
2567                 /*
2568                         Draw hotbar
2569                 */
2570                 if(show_hud)
2571                 {
2572                         draw_hotbar(driver, font, gamedef,
2573                                         v2s32(displaycenter.X, screensize.Y),
2574                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2575                                         client.getHP(), client.getPlayerItem());
2576                 }
2577
2578                 /*
2579                         Damage flash
2580                 */
2581                 if(damage_flash_timer > 0.0)
2582                 {
2583                         damage_flash_timer -= dtime;
2584                         
2585                         video::SColor color(128,255,0,0);
2586                         driver->draw2DRectangle(color,
2587                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2588                                         NULL);
2589                 }
2590
2591                 /*
2592                         End scene
2593                 */
2594                 {
2595                         TimeTaker timer("endScene");
2596                         endSceneX(driver);
2597                         endscenetime = timer.stop(true);
2598                 }
2599
2600                 drawtime = drawtimer.stop(true);
2601
2602                 /*
2603                         End of drawing
2604                 */
2605
2606                 static s16 lastFPS = 0;
2607                 //u16 fps = driver->getFPS();
2608                 u16 fps = (1.0/dtime_avg1);
2609
2610                 if (lastFPS != fps)
2611                 {
2612                         core::stringw str = L"Minetest [";
2613                         str += driver->getName();
2614                         str += "] FPS=";
2615                         str += fps;
2616
2617                         device->setWindowCaption(str.c_str());
2618                         lastFPS = fps;
2619                 }
2620         }
2621
2622         /*
2623                 Drop stuff
2624         */
2625         if(clouds)
2626                 clouds->drop();
2627         
2628         /*
2629                 Draw a "shutting down" screen, which will be shown while the map
2630                 generator and other stuff quits
2631         */
2632         {
2633                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2634                 draw_load_screen(L"Shutting down stuff...", driver, font);
2635                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2636                 guienv->drawAll();
2637                 driver->endScene();
2638                 gui_shuttingdowntext->remove();*/
2639         }
2640
2641         } // Client scope (must be destructed before destructing *def and tsrc
2642
2643         delete tsrc;
2644         delete nodedef;
2645         delete itemdef;
2646 }
2647
2648