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