]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
5ed479386d199bc75d9fb342e39cda45861093af
[dragonfireclient.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                         video::SColor(255,255,150,50),
671                         video::SColor(255,220,220,100)
672                 };
673                 static const u32 usable_colors_count =
674                                 sizeof(usable_colors) / sizeof(*usable_colors);
675                 u32 next_color_i = 0;
676                 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
677                                 i != m_meta.end(); i++){
678                         Meta &meta = i->second;
679                         video::SColor color(255,200,200,200);
680                         if(next_color_i < usable_colors_count)
681                                 color = usable_colors[next_color_i++];
682                         meta.color = color;
683                 }
684
685                 s32 graphh = 50;
686                 s32 textx = x_left + m_log_max_size + 15;
687                 s32 textx2 = textx + 200 - 15;
688                 
689                 // Draw background
690                 /*{
691                         u32 num_graphs = m_meta.size();
692                         core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
693                                         textx2, y_bottom);
694                         video::SColor bgcolor(120,0,0,0);
695                         driver->draw2DRectangle(bgcolor, rect, NULL);
696                 }*/
697                 
698                 s32 meta_i = 0;
699                 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
700                                 i != m_meta.end(); i++){
701                         const std::string &id = i->first;
702                         const Meta &meta = i->second;
703                         s32 x = x_left;
704                         s32 y = y_bottom - meta_i * 50;
705                         float show_min = meta.min;
706                         float show_max = meta.max;
707                         if(show_min >= -0.0001 && show_max >= -0.0001){
708                                 if(show_min <= show_max * 0.5)
709                                         show_min = 0;
710                         }
711                         s32 texth = 15;
712                         char buf[10];
713                         snprintf(buf, 10, "%.3g", show_max);
714                         font->draw(narrow_to_wide(buf).c_str(),
715                                         core::rect<s32>(textx, y - graphh,
716                                         textx2, y - graphh + texth),
717                                         meta.color);
718                         snprintf(buf, 10, "%.3g", show_min);
719                         font->draw(narrow_to_wide(buf).c_str(),
720                                         core::rect<s32>(textx, y - texth,
721                                         textx2, y),
722                                         meta.color);
723                         font->draw(narrow_to_wide(id).c_str(),
724                                         core::rect<s32>(textx, y - graphh/2 - texth/2,
725                                         textx2, y - graphh/2 + texth/2),
726                                         meta.color);
727                         s32 graph1y = y;
728                         s32 graph1h = graphh;
729                         bool relativegraph = (show_min != 0 && show_min != show_max);
730                         float lastscaledvalue = 0.0;
731                         bool lastscaledvalue_exists = false;
732                         for(std::list<Piece>::const_iterator j = m_log.begin();
733                                         j != m_log.end(); j++)
734                         {
735                                 const Piece &piece = *j;
736                                 float value = 0;
737                                 bool value_exists = false;
738                                 Profiler::GraphValues::const_iterator k =
739                                                 piece.values.find(id);
740                                 if(k != piece.values.end()){
741                                         value = k->second;
742                                         value_exists = true;
743                                 }
744                                 if(!value_exists){
745                                         x++;
746                                         lastscaledvalue_exists = false;
747                                         continue;
748                                 }
749                                 float scaledvalue = 1.0;
750                                 if(show_max != show_min)
751                                         scaledvalue = (value - show_min) / (show_max - show_min);
752                                 if(scaledvalue == 1.0 && value == 0){
753                                         x++;
754                                         lastscaledvalue_exists = false;
755                                         continue;
756                                 }
757                                 if(relativegraph){
758                                         if(lastscaledvalue_exists){
759                                                 s32 ivalue1 = lastscaledvalue * graph1h;
760                                                 s32 ivalue2 = scaledvalue * graph1h;
761                                                 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
762                                                                 v2s32(x, graph1y - ivalue2), meta.color);
763                                         }
764                                         lastscaledvalue = scaledvalue;
765                                         lastscaledvalue_exists = true;
766                                 } else{
767                                         s32 ivalue = scaledvalue * graph1h;
768                                         driver->draw2DLine(v2s32(x, graph1y),
769                                                         v2s32(x, graph1y - ivalue), meta.color);
770                                 }
771                                 x++;
772                         }
773                         meta_i++;
774                 }
775         }
776 };
777
778 void the_game(
779         bool &kill,
780         bool random_input,
781         InputHandler *input,
782         IrrlichtDevice *device,
783         gui::IGUIFont* font,
784         std::string map_dir,
785         std::string playername,
786         std::string password,
787         std::string address, // If "", local server is used
788         u16 port,
789         std::wstring &error_message,
790         std::string configpath,
791         ChatBackend &chat_backend,
792         const SubgameSpec &gamespec, // Used for local game,
793         bool simple_singleplayer_mode
794 )
795 {
796         video::IVideoDriver* driver = device->getVideoDriver();
797         scene::ISceneManager* smgr = device->getSceneManager();
798         
799         // Calculate text height using the font
800         u32 text_height = font->getDimension(L"Random test string").Height;
801
802         v2u32 screensize(0,0);
803         v2u32 last_screensize(0,0);
804         screensize = driver->getScreenSize();
805
806         const s32 hotbar_itemcount = 8;
807         //const s32 hotbar_imagesize = 36;
808         //const s32 hotbar_imagesize = 64;
809         s32 hotbar_imagesize = 48;
810         
811         /*
812                 Draw "Loading" screen
813         */
814
815         draw_load_screen(L"Loading...", driver, font);
816         
817         // Create texture source
818         IWritableTextureSource *tsrc = createTextureSource(device);
819         
820         // These will be filled by data received from the server
821         // Create item definition manager
822         IWritableItemDefManager *itemdef = createItemDefManager();
823         // Create node definition manager
824         IWritableNodeDefManager *nodedef = createNodeDefManager();
825
826         // Add chat log output for errors to be shown in chat
827         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
828
829         // Create UI for modifying quicktune values
830         QuicktuneShortcutter quicktune;
831
832         /*
833                 Create server.
834                 SharedPtr will delete it when it goes out of scope.
835         */
836         SharedPtr<Server> server;
837         if(address == ""){
838                 draw_load_screen(L"Creating server...", driver, font);
839                 infostream<<"Creating server"<<std::endl;
840                 server = new Server(map_dir, configpath, gamespec,
841                                 simple_singleplayer_mode);
842                 server->start(port);
843         }
844
845         do{ // Client scope (breakable do-while(0))
846         
847         /*
848                 Create client
849         */
850
851         draw_load_screen(L"Creating client...", driver, font);
852         infostream<<"Creating client"<<std::endl;
853         
854         MapDrawControl draw_control;
855
856         Client client(device, playername.c_str(), password, draw_control,
857                         tsrc, itemdef, nodedef);
858         
859         // Client acts as our GameDef
860         IGameDef *gamedef = &client;
861                         
862         draw_load_screen(L"Resolving address...", driver, font);
863         Address connect_address(0,0,0,0, port);
864         try{
865                 if(address == "")
866                         //connect_address.Resolve("localhost");
867                         connect_address.setAddress(127,0,0,1);
868                 else
869                         connect_address.Resolve(address.c_str());
870         }
871         catch(ResolveError &e)
872         {
873                 error_message = L"Couldn't resolve address";
874                 errorstream<<wide_to_narrow(error_message)<<std::endl;
875                 // Break out of client scope
876                 break;
877         }
878
879         /*
880                 Attempt to connect to the server
881         */
882         
883         infostream<<"Connecting to server at ";
884         connect_address.print(&infostream);
885         infostream<<std::endl;
886         client.connect(connect_address);
887         
888         /*
889                 Wait for server to accept connection
890         */
891         bool could_connect = false;
892         bool connect_aborted = false;
893         try{
894                 float frametime = 0.033;
895                 float time_counter = 0.0;
896                 input->clear();
897                 while(device->run())
898                 {
899                         // Update client and server
900                         client.step(frametime);
901                         if(server != NULL)
902                                 server->step(frametime);
903                         
904                         // End condition
905                         if(client.connectedAndInitialized()){
906                                 could_connect = true;
907                                 break;
908                         }
909                         // Break conditions
910                         if(client.accessDenied()){
911                                 error_message = L"Access denied. Reason: "
912                                                 +client.accessDeniedReason();
913                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
914                                 break;
915                         }
916                         if(input->wasKeyDown(EscapeKey)){
917                                 connect_aborted = true;
918                                 infostream<<"Connect aborted [Escape]"<<std::endl;
919                                 break;
920                         }
921                         
922                         // Display status
923                         std::wostringstream ss;
924                         ss<<L"Connecting to server... (press Escape to cancel)\n";
925                         std::wstring animation = L"/-\\|";
926                         ss<<animation[(int)(time_counter/0.2)%4];
927                         draw_load_screen(ss.str(), driver, font);
928                         
929                         // Delay a bit
930                         sleep_ms(1000*frametime);
931                         time_counter += frametime;
932                 }
933         }
934         catch(con::PeerNotFoundException &e)
935         {}
936         
937         /*
938                 Handle failure to connect
939         */
940         if(!could_connect){
941                 if(error_message == L"" && !connect_aborted){
942                         error_message = L"Connection failed";
943                         errorstream<<wide_to_narrow(error_message)<<std::endl;
944                 }
945                 // Break out of client scope
946                 break;
947         }
948         
949         /*
950                 Wait until content has been received
951         */
952         bool got_content = false;
953         bool content_aborted = false;
954         {
955                 float frametime = 0.033;
956                 float time_counter = 0.0;
957                 input->clear();
958                 while(device->run())
959                 {
960                         // Update client and server
961                         client.step(frametime);
962                         if(server != NULL)
963                                 server->step(frametime);
964                         
965                         // End condition
966                         if(client.texturesReceived() &&
967                                         client.itemdefReceived() &&
968                                         client.nodedefReceived()){
969                                 got_content = true;
970                                 break;
971                         }
972                         // Break conditions
973                         if(!client.connectedAndInitialized()){
974                                 error_message = L"Client disconnected";
975                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
976                                 break;
977                         }
978                         if(input->wasKeyDown(EscapeKey)){
979                                 content_aborted = true;
980                                 infostream<<"Connect aborted [Escape]"<<std::endl;
981                                 break;
982                         }
983                         
984                         // Display status
985                         std::wostringstream ss;
986                         ss<<L"Waiting content... (press Escape to cancel)\n";
987
988                         ss<<(client.itemdefReceived()?L"[X]":L"[  ]");
989                         ss<<L" Item definitions\n";
990                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
991                         ss<<L" Node definitions\n";
992                         //ss<<(client.texturesReceived()?L"[X]":L"[  ]");
993                         ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
994                         ss<<L" Textures\n";
995
996                         draw_load_screen(ss.str(), driver, font);
997                         
998                         // Delay a bit
999                         sleep_ms(1000*frametime);
1000                         time_counter += frametime;
1001                 }
1002         }
1003
1004         if(!got_content){
1005                 if(error_message == L"" && !content_aborted){
1006                         error_message = L"Something failed";
1007                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1008                 }
1009                 // Break out of client scope
1010                 break;
1011         }
1012
1013         /*
1014                 After all content has been received:
1015                 Update cached textures, meshes and materials
1016         */
1017         client.afterContentReceived();
1018
1019         /*
1020                 Create the camera node
1021         */
1022         Camera camera(smgr, draw_control);
1023         if (!camera.successfullyCreated(error_message))
1024                 return;
1025
1026         f32 camera_yaw = 0; // "right/left"
1027         f32 camera_pitch = 0; // "up/down"
1028
1029         /*
1030                 Clouds
1031         */
1032         
1033         Clouds *clouds = NULL;
1034         if(g_settings->getBool("enable_clouds"))
1035         {
1036                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1037         }
1038
1039         /*
1040                 Skybox thingy
1041         */
1042
1043         Sky *sky = NULL;
1044         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1045         
1046         /*
1047                 FarMesh
1048         */
1049
1050         FarMesh *farmesh = NULL;
1051         if(g_settings->getBool("enable_farmesh"))
1052         {
1053                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1054         }
1055
1056         /*
1057                 A copy of the local inventory
1058         */
1059         Inventory local_inventory(itemdef);
1060
1061         /*
1062                 Add some gui stuff
1063         */
1064
1065         // First line of debug text
1066         gui::IGUIStaticText *guitext = guienv->addStaticText(
1067                         L"Minetest-c55",
1068                         core::rect<s32>(5, 5, 795, 5+text_height),
1069                         false, false);
1070         // Second line of debug text
1071         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1072                         L"",
1073                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1074                         false, false);
1075         // At the middle of the screen
1076         // Object infos are shown in this
1077         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1078                         L"",
1079                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1080                         false, false);
1081         
1082         // Status text (displays info when showing and hiding GUI stuff, etc.)
1083         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1084                         L"<Status>",
1085                         core::rect<s32>(0,0,0,0),
1086                         false, false);
1087         guitext_status->setVisible(false);
1088         
1089         std::wstring statustext;
1090         float statustext_time = 0;
1091         
1092         // Chat text
1093         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1094                         L"",
1095                         core::rect<s32>(0,0,0,0),
1096                         //false, false); // Disable word wrap as of now
1097                         false, true);
1098         // Remove stale "recent" chat messages from previous connections
1099         chat_backend.clearRecentChat();
1100         // Chat backend and console
1101         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1102         
1103         // Profiler text (size is updated when text is updated)
1104         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1105                         L"<Profiler>",
1106                         core::rect<s32>(0,0,0,0),
1107                         false, false);
1108         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1109         guitext_profiler->setVisible(false);
1110         
1111         /*
1112                 Some statistics are collected in these
1113         */
1114         u32 drawtime = 0;
1115         u32 beginscenetime = 0;
1116         u32 scenetime = 0;
1117         u32 endscenetime = 0;
1118         
1119         float recent_turn_speed = 0.0;
1120         
1121         ProfilerGraph graph;
1122         // Initially clear the profiler
1123         Profiler::GraphValues dummyvalues;
1124         g_profiler->graphGet(dummyvalues);
1125
1126         float nodig_delay_timer = 0.0;
1127         float dig_time = 0.0;
1128         u16 dig_index = 0;
1129         PointedThing pointed_old;
1130         bool digging = false;
1131         bool ldown_for_dig = false;
1132
1133         float damage_flash_timer = 0;
1134         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1135
1136         const float object_hit_delay = 0.2;
1137         float object_hit_delay_timer = 0.0;
1138         float time_from_last_punch = 10;
1139
1140         bool invert_mouse = g_settings->getBool("invert_mouse");
1141
1142         bool respawn_menu_active = false;
1143         bool update_wielded_item_trigger = false;
1144
1145         bool show_hud = true;
1146         bool show_chat = true;
1147         bool force_fog_off = false;
1148         bool disable_camera_update = false;
1149         bool show_debug = g_settings->getBool("show_debug");
1150         bool show_profiler_graph = false;
1151         u32 show_profiler = 0;
1152         u32 show_profiler_max = 3;  // Number of pages
1153
1154         float time_of_day = 0;
1155         float time_of_day_smooth = 0;
1156
1157         /*
1158                 Main loop
1159         */
1160
1161         bool first_loop_after_window_activation = true;
1162
1163         // TODO: Convert the static interval timers to these
1164         // Interval limiter for profiler
1165         IntervalLimiter m_profiler_interval;
1166
1167         // Time is in milliseconds
1168         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1169         // NOTE: So we have to use getTime() and call run()s between them
1170         u32 lasttime = device->getTimer()->getTime();
1171
1172         for(;;)
1173         {
1174                 if(device->run() == false || kill == true)
1175                         break;
1176
1177                 // Time of frame without fps limit
1178                 float busytime;
1179                 u32 busytime_u32;
1180                 {
1181                         // not using getRealTime is necessary for wine
1182                         u32 time = device->getTimer()->getTime();
1183                         if(time > lasttime)
1184                                 busytime_u32 = time - lasttime;
1185                         else
1186                                 busytime_u32 = 0;
1187                         busytime = busytime_u32 / 1000.0;
1188                 }
1189                 
1190                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1191
1192                 // Necessary for device->getTimer()->getTime()
1193                 device->run();
1194
1195                 /*
1196                         FPS limiter
1197                 */
1198
1199                 {
1200                         float fps_max = g_settings->getFloat("fps_max");
1201                         u32 frametime_min = 1000./fps_max;
1202                         
1203                         if(busytime_u32 < frametime_min)
1204                         {
1205                                 u32 sleeptime = frametime_min - busytime_u32;
1206                                 device->sleep(sleeptime);
1207                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1208                         }
1209                 }
1210
1211                 // Necessary for device->getTimer()->getTime()
1212                 device->run();
1213
1214                 /*
1215                         Time difference calculation
1216                 */
1217                 f32 dtime; // in seconds
1218                 
1219                 u32 time = device->getTimer()->getTime();
1220                 if(time > lasttime)
1221                         dtime = (time - lasttime) / 1000.0;
1222                 else
1223                         dtime = 0;
1224                 lasttime = time;
1225
1226                 g_profiler->graphAdd("mainloop_dtime", dtime);
1227
1228                 /* Run timers */
1229
1230                 if(nodig_delay_timer >= 0)
1231                         nodig_delay_timer -= dtime;
1232                 if(object_hit_delay_timer >= 0)
1233                         object_hit_delay_timer -= dtime;
1234                 time_from_last_punch += dtime;
1235
1236                 g_profiler->add("Elapsed time", dtime);
1237                 g_profiler->avg("FPS", 1./dtime);
1238
1239                 /*
1240                         Time average and jitter calculation
1241                 */
1242
1243                 static f32 dtime_avg1 = 0.0;
1244                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1245                 f32 dtime_jitter1 = dtime - dtime_avg1;
1246
1247                 static f32 dtime_jitter1_max_sample = 0.0;
1248                 static f32 dtime_jitter1_max_fraction = 0.0;
1249                 {
1250                         static f32 jitter1_max = 0.0;
1251                         static f32 counter = 0.0;
1252                         if(dtime_jitter1 > jitter1_max)
1253                                 jitter1_max = dtime_jitter1;
1254                         counter += dtime;
1255                         if(counter > 0.0)
1256                         {
1257                                 counter -= 3.0;
1258                                 dtime_jitter1_max_sample = jitter1_max;
1259                                 dtime_jitter1_max_fraction
1260                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1261                                 jitter1_max = 0.0;
1262                         }
1263                 }
1264                 
1265                 /*
1266                         Busytime average and jitter calculation
1267                 */
1268
1269                 static f32 busytime_avg1 = 0.0;
1270                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1271                 f32 busytime_jitter1 = busytime - busytime_avg1;
1272                 
1273                 static f32 busytime_jitter1_max_sample = 0.0;
1274                 static f32 busytime_jitter1_min_sample = 0.0;
1275                 {
1276                         static f32 jitter1_max = 0.0;
1277                         static f32 jitter1_min = 0.0;
1278                         static f32 counter = 0.0;
1279                         if(busytime_jitter1 > jitter1_max)
1280                                 jitter1_max = busytime_jitter1;
1281                         if(busytime_jitter1 < jitter1_min)
1282                                 jitter1_min = busytime_jitter1;
1283                         counter += dtime;
1284                         if(counter > 0.0){
1285                                 counter -= 3.0;
1286                                 busytime_jitter1_max_sample = jitter1_max;
1287                                 busytime_jitter1_min_sample = jitter1_min;
1288                                 jitter1_max = 0.0;
1289                                 jitter1_min = 0.0;
1290                         }
1291                 }
1292
1293                 /*
1294                         Handle miscellaneous stuff
1295                 */
1296                 
1297                 if(client.accessDenied())
1298                 {
1299                         error_message = L"Access denied. Reason: "
1300                                         +client.accessDeniedReason();
1301                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1302                         break;
1303                 }
1304
1305                 if(g_gamecallback->disconnect_requested)
1306                 {
1307                         g_gamecallback->disconnect_requested = false;
1308                         break;
1309                 }
1310
1311                 if(g_gamecallback->changepassword_requested)
1312                 {
1313                         (new GUIPasswordChange(guienv, guiroot, -1,
1314                                 &g_menumgr, &client))->drop();
1315                         g_gamecallback->changepassword_requested = false;
1316                 }
1317
1318                 /*
1319                         Process TextureSource's queue
1320                 */
1321                 tsrc->processQueue();
1322
1323                 /*
1324                         Random calculations
1325                 */
1326                 last_screensize = screensize;
1327                 screensize = driver->getScreenSize();
1328                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1329                 //bool screensize_changed = screensize != last_screensize;
1330
1331                 // Resize hotbar
1332                 if(screensize.Y <= 800)
1333                         hotbar_imagesize = 32;
1334                 else if(screensize.Y <= 1280)
1335                         hotbar_imagesize = 48;
1336                 else
1337                         hotbar_imagesize = 64;
1338                 
1339                 // Hilight boxes collected during the loop and displayed
1340                 core::list< core::aabbox3d<f32> > hilightboxes;
1341                 
1342                 // Info text
1343                 std::wstring infotext;
1344
1345                 /*
1346                         Debug info for client
1347                 */
1348                 {
1349                         static float counter = 0.0;
1350                         counter -= dtime;
1351                         if(counter < 0)
1352                         {
1353                                 counter = 30.0;
1354                                 client.printDebugInfo(infostream);
1355                         }
1356                 }
1357
1358                 /*
1359                         Profiler
1360                 */
1361                 float profiler_print_interval =
1362                                 g_settings->getFloat("profiler_print_interval");
1363                 bool print_to_log = true;
1364                 if(profiler_print_interval == 0){
1365                         print_to_log = false;
1366                         profiler_print_interval = 5;
1367                 }
1368                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1369                 {
1370                         if(print_to_log){
1371                                 infostream<<"Profiler:"<<std::endl;
1372                                 g_profiler->print(infostream);
1373                         }
1374
1375                         update_profiler_gui(guitext_profiler, font, text_height,
1376                                         show_profiler, show_profiler_max);
1377
1378                         g_profiler->clear();
1379                 }
1380
1381                 /*
1382                         Direct handling of user input
1383                 */
1384                 
1385                 // Reset input if window not active or some menu is active
1386                 if(device->isWindowActive() == false
1387                                 || noMenuActive() == false
1388                                 || guienv->hasFocus(gui_chat_console))
1389                 {
1390                         input->clear();
1391                 }
1392
1393                 // Input handler step() (used by the random input generator)
1394                 input->step(dtime);
1395
1396                 /*
1397                         Launch menus and trigger stuff according to keys
1398                 */
1399                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1400                 {
1401                         // drop selected item
1402                         IDropAction *a = new IDropAction();
1403                         a->count = 0;
1404                         a->from_inv.setCurrentPlayer();
1405                         a->from_list = "main";
1406                         a->from_i = client.getPlayerItem();
1407                         client.inventoryAction(a);
1408                 }
1409                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1410                 {
1411                         infostream<<"the_game: "
1412                                         <<"Launching inventory"<<std::endl;
1413                         
1414                         GUIInventoryMenu *menu =
1415                                 new GUIInventoryMenu(guienv, guiroot, -1,
1416                                         &g_menumgr, v2s16(8,7),
1417                                         &client, gamedef);
1418
1419                         InventoryLocation inventoryloc;
1420                         inventoryloc.setCurrentPlayer();
1421
1422                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1423                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1424                                         "list", inventoryloc, "main",
1425                                         v2s32(0, 3), v2s32(8, 4)));
1426                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1427                                         "list", inventoryloc, "craft",
1428                                         v2s32(3, 0), v2s32(3, 3)));
1429                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1430                                         "list", inventoryloc, "craftpreview",
1431                                         v2s32(7, 1), v2s32(1, 1)));
1432
1433                         menu->setDrawSpec(draw_spec);
1434
1435                         menu->drop();
1436                 }
1437                 else if(input->wasKeyDown(EscapeKey))
1438                 {
1439                         infostream<<"the_game: "
1440                                         <<"Launching pause menu"<<std::endl;
1441                         // It will delete itself by itself
1442                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1443                                         &g_menumgr, simple_singleplayer_mode))->drop();
1444
1445                         // Move mouse cursor on top of the disconnect button
1446                         if(simple_singleplayer_mode)
1447                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1448                         else
1449                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1450                 }
1451                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1452                 {
1453                         TextDest *dest = new TextDestChat(&client);
1454
1455                         (new GUITextInputMenu(guienv, guiroot, -1,
1456                                         &g_menumgr, dest,
1457                                         L""))->drop();
1458                 }
1459                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1460                 {
1461                         TextDest *dest = new TextDestChat(&client);
1462
1463                         (new GUITextInputMenu(guienv, guiroot, -1,
1464                                         &g_menumgr, dest,
1465                                         L"/"))->drop();
1466                 }
1467                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1468                 {
1469                         if (!gui_chat_console->isOpenInhibited())
1470                         {
1471                                 // Open up to over half of the screen
1472                                 gui_chat_console->openConsole(0.6);
1473                                 guienv->setFocus(gui_chat_console);
1474                         }
1475                 }
1476                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1477                 {
1478                         if(g_settings->getBool("free_move"))
1479                         {
1480                                 g_settings->set("free_move","false");
1481                                 statustext = L"free_move disabled";
1482                                 statustext_time = 0;
1483                         }
1484                         else
1485                         {
1486                                 g_settings->set("free_move","true");
1487                                 statustext = L"free_move enabled";
1488                                 statustext_time = 0;
1489                         }
1490                 }
1491                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1492                 {
1493                         if(g_settings->getBool("fast_move"))
1494                         {
1495                                 g_settings->set("fast_move","false");
1496                                 statustext = L"fast_move disabled";
1497                                 statustext_time = 0;
1498                         }
1499                         else
1500                         {
1501                                 g_settings->set("fast_move","true");
1502                                 statustext = L"fast_move enabled";
1503                                 statustext_time = 0;
1504                         }
1505                 }
1506                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1507                 {
1508                         irr::video::IImage* const image = driver->createScreenShot(); 
1509                         if (image) { 
1510                                 irr::c8 filename[256]; 
1511                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1512                                                  g_settings->get("screenshot_path").c_str(),
1513                                                  device->getTimer()->getRealTime()); 
1514                                 if (driver->writeImageToFile(image, filename)) {
1515                                         std::wstringstream sstr;
1516                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1517                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1518                                         statustext = sstr.str();
1519                                         statustext_time = 0;
1520                                 } else{
1521                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1522                                 }
1523                                 image->drop(); 
1524                         }                        
1525                 }
1526                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1527                 {
1528                         show_hud = !show_hud;
1529                         if(show_hud)
1530                                 statustext = L"HUD shown";
1531                         else
1532                                 statustext = L"HUD hidden";
1533                         statustext_time = 0;
1534                 }
1535                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1536                 {
1537                         show_chat = !show_chat;
1538                         if(show_chat)
1539                                 statustext = L"Chat shown";
1540                         else
1541                                 statustext = L"Chat hidden";
1542                         statustext_time = 0;
1543                 }
1544                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1545                 {
1546                         force_fog_off = !force_fog_off;
1547                         if(force_fog_off)
1548                                 statustext = L"Fog disabled";
1549                         else
1550                                 statustext = L"Fog enabled";
1551                         statustext_time = 0;
1552                 }
1553                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1554                 {
1555                         disable_camera_update = !disable_camera_update;
1556                         if(disable_camera_update)
1557                                 statustext = L"Camera update disabled";
1558                         else
1559                                 statustext = L"Camera update enabled";
1560                         statustext_time = 0;
1561                 }
1562                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1563                 {
1564                         // Initial / 3x toggle: Chat only
1565                         // 1x toggle: Debug text with chat
1566                         // 2x toggle: Debug text with profiler graph
1567                         if(!show_debug)
1568                         {
1569                                 show_debug = true;
1570                                 show_profiler_graph = false;
1571                                 statustext = L"Debug info shown";
1572                                 statustext_time = 0;
1573                         }
1574                         else if(show_profiler_graph)
1575                         {
1576                                 show_debug = false;
1577                                 show_profiler_graph = false;
1578                                 statustext = L"Debug info and profiler graph hidden";
1579                                 statustext_time = 0;
1580                         }
1581                         else
1582                         {
1583                                 show_profiler_graph = true;
1584                                 statustext = L"Profiler graph shown";
1585                                 statustext_time = 0;
1586                         }
1587                 }
1588                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1589                 {
1590                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1591
1592                         // FIXME: This updates the profiler with incomplete values
1593                         update_profiler_gui(guitext_profiler, font, text_height,
1594                                         show_profiler, show_profiler_max);
1595
1596                         if(show_profiler != 0)
1597                         {
1598                                 std::wstringstream sstr;
1599                                 sstr<<"Profiler shown (page "<<show_profiler
1600                                         <<" of "<<show_profiler_max<<")";
1601                                 statustext = sstr.str();
1602                                 statustext_time = 0;
1603                         }
1604                         else
1605                         {
1606                                 statustext = L"Profiler hidden";
1607                                 statustext_time = 0;
1608                         }
1609                 }
1610                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1611                 {
1612                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1613                         s16 range_new = range + 10;
1614                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1615                         statustext = narrow_to_wide(
1616                                         "Minimum viewing range changed to "
1617                                         + itos(range_new));
1618                         statustext_time = 0;
1619                 }
1620                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1621                 {
1622                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1623                         s16 range_new = range - 10;
1624                         if(range_new < 0)
1625                                 range_new = range;
1626                         g_settings->set("viewing_range_nodes_min",
1627                                         itos(range_new));
1628                         statustext = narrow_to_wide(
1629                                         "Minimum viewing range changed to "
1630                                         + itos(range_new));
1631                         statustext_time = 0;
1632                 }
1633                 
1634                 // Handle QuicktuneShortcutter
1635                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1636                         quicktune.next();
1637                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1638                         quicktune.prev();
1639                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1640                         quicktune.inc();
1641                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1642                         quicktune.dec();
1643                 {
1644                         std::string msg = quicktune.getMessage();
1645                         if(msg != ""){
1646                                 statustext = narrow_to_wide(msg);
1647                                 statustext_time = 0;
1648                         }
1649                 }
1650
1651                 // Item selection with mouse wheel
1652                 u16 new_playeritem = client.getPlayerItem();
1653                 {
1654                         s32 wheel = input->getMouseWheel();
1655                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1656                                         hotbar_itemcount-1);
1657
1658                         if(wheel < 0)
1659                         {
1660                                 if(new_playeritem < max_item)
1661                                         new_playeritem++;
1662                                 else
1663                                         new_playeritem = 0;
1664                         }
1665                         else if(wheel > 0)
1666                         {
1667                                 if(new_playeritem > 0)
1668                                         new_playeritem--;
1669                                 else
1670                                         new_playeritem = max_item;
1671                         }
1672                 }
1673                 
1674                 // Item selection
1675                 for(u16 i=0; i<10; i++)
1676                 {
1677                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1678                         if(input->wasKeyDown(*kp))
1679                         {
1680                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1681                                 {
1682                                         new_playeritem = i;
1683
1684                                         infostream<<"Selected item: "
1685                                                         <<new_playeritem<<std::endl;
1686                                 }
1687                         }
1688                 }
1689
1690                 // Viewing range selection
1691                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1692                 {
1693                         draw_control.range_all = !draw_control.range_all;
1694                         if(draw_control.range_all)
1695                         {
1696                                 infostream<<"Enabled full viewing range"<<std::endl;
1697                                 statustext = L"Enabled full viewing range";
1698                                 statustext_time = 0;
1699                         }
1700                         else
1701                         {
1702                                 infostream<<"Disabled full viewing range"<<std::endl;
1703                                 statustext = L"Disabled full viewing range";
1704                                 statustext_time = 0;
1705                         }
1706                 }
1707
1708                 // Print debug stacks
1709                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1710                 {
1711                         dstream<<"-----------------------------------------"
1712                                         <<std::endl;
1713                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1714                         dstream<<"-----------------------------------------"
1715                                         <<std::endl;
1716                         debug_stacks_print();
1717                 }
1718
1719                 /*
1720                         Mouse and camera control
1721                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1722                 */
1723                 
1724                 float turn_amount = 0;
1725                 if((device->isWindowActive() && noMenuActive()) || random_input)
1726                 {
1727                         if(!random_input)
1728                         {
1729                                 // Mac OSX gets upset if this is set every frame
1730                                 if(device->getCursorControl()->isVisible())
1731                                         device->getCursorControl()->setVisible(false);
1732                         }
1733
1734                         if(first_loop_after_window_activation){
1735                                 //infostream<<"window active, first loop"<<std::endl;
1736                                 first_loop_after_window_activation = false;
1737                         }
1738                         else{
1739                                 s32 dx = input->getMousePos().X - displaycenter.X;
1740                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1741                                 if(invert_mouse)
1742                                         dy = -dy;
1743                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1744                                 
1745                                 /*const float keyspeed = 500;
1746                                 if(input->isKeyDown(irr::KEY_UP))
1747                                         dy -= dtime * keyspeed;
1748                                 if(input->isKeyDown(irr::KEY_DOWN))
1749                                         dy += dtime * keyspeed;
1750                                 if(input->isKeyDown(irr::KEY_LEFT))
1751                                         dx -= dtime * keyspeed;
1752                                 if(input->isKeyDown(irr::KEY_RIGHT))
1753                                         dx += dtime * keyspeed;*/
1754                                 
1755                                 float d = 0.2;
1756                                 camera_yaw -= dx*d;
1757                                 camera_pitch += dy*d;
1758                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1759                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1760                                 
1761                                 turn_amount = v2f(dx, dy).getLength() * d;
1762                         }
1763                         input->setMousePos(displaycenter.X, displaycenter.Y);
1764                 }
1765                 else{
1766                         // Mac OSX gets upset if this is set every frame
1767                         if(device->getCursorControl()->isVisible() == false)
1768                                 device->getCursorControl()->setVisible(true);
1769
1770                         //infostream<<"window inactive"<<std::endl;
1771                         first_loop_after_window_activation = true;
1772                 }
1773                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1774                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1775
1776                 /*
1777                         Player speed control
1778                 */
1779                 {
1780                         /*bool a_up,
1781                         bool a_down,
1782                         bool a_left,
1783                         bool a_right,
1784                         bool a_jump,
1785                         bool a_superspeed,
1786                         bool a_sneak,
1787                         float a_pitch,
1788                         float a_yaw*/
1789                         PlayerControl control(
1790                                 input->isKeyDown(getKeySetting("keymap_forward")),
1791                                 input->isKeyDown(getKeySetting("keymap_backward")),
1792                                 input->isKeyDown(getKeySetting("keymap_left")),
1793                                 input->isKeyDown(getKeySetting("keymap_right")),
1794                                 input->isKeyDown(getKeySetting("keymap_jump")),
1795                                 input->isKeyDown(getKeySetting("keymap_special1")),
1796                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1797                                 camera_pitch,
1798                                 camera_yaw
1799                         );
1800                         client.setPlayerControl(control);
1801                 }
1802                 
1803                 /*
1804                         Run server
1805                 */
1806
1807                 if(server != NULL)
1808                 {
1809                         //TimeTaker timer("server->step(dtime)");
1810                         server->step(dtime);
1811                 }
1812
1813                 /*
1814                         Process environment
1815                 */
1816                 
1817                 {
1818                         //TimeTaker timer("client.step(dtime)");
1819                         client.step(dtime);
1820                         //client.step(dtime_avg1);
1821                 }
1822
1823                 {
1824                         // Read client events
1825                         for(;;)
1826                         {
1827                                 ClientEvent event = client.getClientEvent();
1828                                 if(event.type == CE_NONE)
1829                                 {
1830                                         break;
1831                                 }
1832                                 else if(event.type == CE_PLAYER_DAMAGE)
1833                                 {
1834                                         //u16 damage = event.player_damage.amount;
1835                                         //infostream<<"Player damage: "<<damage<<std::endl;
1836                                         damage_flash_timer = 0.05;
1837                                         if(event.player_damage.amount >= 2){
1838                                                 damage_flash_timer += 0.05 * event.player_damage.amount;
1839                                         }
1840                                 }
1841                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
1842                                 {
1843                                         camera_yaw = event.player_force_move.yaw;
1844                                         camera_pitch = event.player_force_move.pitch;
1845                                 }
1846                                 else if(event.type == CE_DEATHSCREEN)
1847                                 {
1848                                         if(respawn_menu_active)
1849                                                 continue;
1850
1851                                         /*bool set_camera_point_target =
1852                                                         event.deathscreen.set_camera_point_target;
1853                                         v3f camera_point_target;
1854                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
1855                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
1856                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1857                                         MainRespawnInitiator *respawner =
1858                                                         new MainRespawnInitiator(
1859                                                                         &respawn_menu_active, &client);
1860                                         GUIDeathScreen *menu =
1861                                                         new GUIDeathScreen(guienv, guiroot, -1, 
1862                                                                 &g_menumgr, respawner);
1863                                         menu->drop();
1864                                         
1865                                         chat_backend.addMessage(L"", L"You died.");
1866
1867                                         /* Handle visualization */
1868
1869                                         damage_flash_timer = 0;
1870
1871                                         /*LocalPlayer* player = client.getLocalPlayer();
1872                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
1873                                         camera.update(player, busytime, screensize);*/
1874                                 }
1875                                 else if(event.type == CE_TEXTURES_UPDATED)
1876                                 {
1877                                         update_wielded_item_trigger = true;
1878                                 }
1879                         }
1880                 }
1881                 
1882                 //TimeTaker //timer2("//timer2");
1883
1884                 /*
1885                         For interaction purposes, get info about the held item
1886                         - What item is it?
1887                         - Is it a usable item?
1888                         - Can it point to liquids?
1889                 */
1890                 ItemStack playeritem;
1891                 bool playeritem_usable = false;
1892                 bool playeritem_liquids_pointable = false;
1893                 {
1894                         InventoryList *mlist = local_inventory.getList("main");
1895                         if(mlist != NULL)
1896                         {
1897                                 playeritem = mlist->getItem(client.getPlayerItem());
1898                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1899                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1900                         }
1901                 }
1902                 ToolCapabilities playeritem_toolcap =
1903                                 playeritem.getToolCapabilities(itemdef);
1904                 
1905                 /*
1906                         Update camera
1907                 */
1908
1909                 LocalPlayer* player = client.getEnv().getLocalPlayer();
1910                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1911                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1912                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1913                 camera.update(player, busytime, screensize, tool_reload_ratio);
1914                 camera.step(dtime);
1915
1916                 v3f player_position = player->getPosition();
1917                 v3f camera_position = camera.getPosition();
1918                 v3f camera_direction = camera.getDirection();
1919                 f32 camera_fov = camera.getFovMax();
1920                 
1921                 if(!disable_camera_update){
1922                         client.getEnv().getClientMap().updateCamera(camera_position,
1923                                 camera_direction, camera_fov);
1924                 }
1925
1926                 //timer2.stop();
1927                 //TimeTaker //timer3("//timer3");
1928
1929                 /*
1930                         Calculate what block is the crosshair pointing to
1931                 */
1932                 
1933                 //u32 t1 = device->getTimer()->getRealTime();
1934                 
1935                 f32 d = 4; // max. distance
1936                 core::line3d<f32> shootline(camera_position,
1937                                 camera_position + camera_direction * BS * (d+1));
1938
1939                 core::aabbox3d<f32> hilightbox;
1940                 bool should_show_hilightbox = false;
1941                 ClientActiveObject *selected_object = NULL;
1942
1943                 PointedThing pointed = getPointedThing(
1944                                 // input
1945                                 &client, player_position, camera_direction,
1946                                 camera_position, shootline, d,
1947                                 playeritem_liquids_pointable, !ldown_for_dig,
1948                                 // output
1949                                 hilightbox, should_show_hilightbox,
1950                                 selected_object);
1951
1952                 if(pointed != pointed_old)
1953                 {
1954                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1955                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1956                 }
1957
1958                 /*
1959                         Visualize selection
1960                 */
1961                 if(should_show_hilightbox)
1962                         hilightboxes.push_back(hilightbox);
1963
1964                 /*
1965                         Stop digging when
1966                         - releasing left mouse button
1967                         - pointing away from node
1968                 */
1969                 if(digging)
1970                 {
1971                         if(input->getLeftReleased())
1972                         {
1973                                 infostream<<"Left button released"
1974                                         <<" (stopped digging)"<<std::endl;
1975                                 digging = false;
1976                         }
1977                         else if(pointed != pointed_old)
1978                         {
1979                                 if (pointed.type == POINTEDTHING_NODE
1980                                         && pointed_old.type == POINTEDTHING_NODE
1981                                         && pointed.node_undersurface == pointed_old.node_undersurface)
1982                                 {
1983                                         // Still pointing to the same node,
1984                                         // but a different face. Don't reset.
1985                                 }
1986                                 else
1987                                 {
1988                                         infostream<<"Pointing away from node"
1989                                                 <<" (stopped digging)"<<std::endl;
1990                                         digging = false;
1991                                 }
1992                         }
1993                         if(!digging)
1994                         {
1995                                 client.interact(1, pointed_old);
1996                                 client.setCrack(-1, v3s16(0,0,0));
1997                                 dig_time = 0.0;
1998                         }
1999                 }
2000                 if(!digging && ldown_for_dig && !input->getLeftState())
2001                 {
2002                         ldown_for_dig = false;
2003                 }
2004
2005                 bool left_punch = false;
2006
2007                 if(playeritem_usable && input->getLeftState())
2008                 {
2009                         if(input->getLeftClicked())
2010                                 client.interact(4, pointed);
2011                 }
2012                 else if(pointed.type == POINTEDTHING_NODE)
2013                 {
2014                         v3s16 nodepos = pointed.node_undersurface;
2015                         v3s16 neighbourpos = pointed.node_abovesurface;
2016
2017                         /*
2018                                 Check information text of node
2019                         */
2020                         
2021                         ClientMap &map = client.getEnv().getClientMap();
2022                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2023                         if(meta){
2024                                 infotext = narrow_to_wide(meta->infoText());
2025                         } else {
2026                                 MapNode n = map.getNode(nodepos);
2027                                 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2028                                         infotext = L"Unknown node: ";
2029                                         infotext += narrow_to_wide(nodedef->get(n).name);
2030                                 }
2031                         }
2032                         
2033                         /*
2034                                 Handle digging
2035                         */
2036                         
2037                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
2038                         {
2039                                 if(!digging)
2040                                 {
2041                                         infostream<<"Started digging"<<std::endl;
2042                                         client.interact(0, pointed);
2043                                         digging = true;
2044                                         ldown_for_dig = true;
2045                                 }
2046                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2047
2048                                 // Get digging parameters
2049                                 DigParams params = getDigParams(nodedef->get(n).groups,
2050                                                 &playeritem_toolcap);
2051                                 // If can't dig, try hand
2052                                 if(!params.diggable){
2053                                         const ItemDefinition &hand = itemdef->get("");
2054                                         const ToolCapabilities *tp = hand.tool_capabilities;
2055                                         if(tp)
2056                                                 params = getDigParams(nodedef->get(n).groups, tp);
2057                                 }
2058
2059                                 float dig_time_complete = 0.0;
2060
2061                                 if(params.diggable == false)
2062                                 {
2063                                         // I guess nobody will wait for this long
2064                                         dig_time_complete = 10000000.0;
2065                                 }
2066                                 else
2067                                 {
2068                                         dig_time_complete = params.time;
2069                                 }
2070
2071                                 if(dig_time_complete >= 0.001)
2072                                 {
2073                                         dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2074                                                         * dig_time/dig_time_complete);
2075                                 }
2076                                 // This is for torches
2077                                 else
2078                                 {
2079                                         dig_index = CRACK_ANIMATION_LENGTH;
2080                                 }
2081                                 
2082                                 // Don't show cracks if not diggable
2083                                 if(dig_time_complete >= 100000.0)
2084                                 {
2085                                 }
2086                                 else if(dig_index < CRACK_ANIMATION_LENGTH)
2087                                 {
2088                                         //TimeTaker timer("client.setTempMod");
2089                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2090                                         client.setCrack(dig_index, nodepos);
2091                                 }
2092                                 else
2093                                 {
2094                                         infostream<<"Digging completed"<<std::endl;
2095                                         client.interact(2, pointed);
2096                                         client.setCrack(-1, v3s16(0,0,0));
2097                                         client.removeNode(nodepos);
2098
2099                                         dig_time = 0;
2100                                         digging = false;
2101
2102                                         nodig_delay_timer = dig_time_complete
2103                                                         / (float)CRACK_ANIMATION_LENGTH;
2104
2105                                         // We don't want a corresponding delay to
2106                                         // very time consuming nodes
2107                                         if(nodig_delay_timer > 0.5)
2108                                         {
2109                                                 nodig_delay_timer = 0.5;
2110                                         }
2111                                         // We want a slight delay to very little
2112                                         // time consuming nodes
2113                                         float mindelay = 0.15;
2114                                         if(nodig_delay_timer < mindelay)
2115                                         {
2116                                                 nodig_delay_timer = mindelay;
2117                                         }
2118                                 }
2119
2120                                 dig_time += dtime;
2121
2122                                 camera.setDigging(0);  // left click animation
2123                         }
2124
2125                         if(input->getRightClicked())
2126                         {
2127                                 infostream<<"Ground right-clicked"<<std::endl;
2128                                 
2129                                 // If metadata provides an inventory view, activate it
2130                                 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2131                                 {
2132                                         infostream<<"Launching custom inventory view"<<std::endl;
2133
2134                                         InventoryLocation inventoryloc;
2135                                         inventoryloc.setNodeMeta(nodepos);
2136                                         
2137
2138                                         /*
2139                                                 Create menu
2140                                         */
2141
2142                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2143                                         v2s16 invsize =
2144                                                 GUIInventoryMenu::makeDrawSpecArrayFromString(
2145                                                         draw_spec,
2146                                                         meta->getInventoryDrawSpecString(),
2147                                                         inventoryloc);
2148
2149                                         GUIInventoryMenu *menu =
2150                                                 new GUIInventoryMenu(guienv, guiroot, -1,
2151                                                         &g_menumgr, invsize,
2152                                                         &client, gamedef);
2153                                         menu->setDrawSpec(draw_spec);
2154                                         menu->drop();
2155                                 }
2156                                 // If metadata provides text input, activate text input
2157                                 else if(meta && meta->allowsTextInput() && !random_input)
2158                                 {
2159                                         infostream<<"Launching metadata text input"<<std::endl;
2160                                         
2161                                         // Get a new text for it
2162
2163                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2164
2165                                         std::wstring wtext = narrow_to_wide(meta->getText());
2166
2167                                         (new GUITextInputMenu(guienv, guiroot, -1,
2168                                                         &g_menumgr, dest,
2169                                                         wtext))->drop();
2170                                 }
2171                                 // Otherwise report right click to server
2172                                 else
2173                                 {
2174                                         client.interact(3, pointed);
2175                                         camera.setDigging(1);  // right click animation
2176                                 }
2177                         }
2178                 }
2179                 else if(pointed.type == POINTEDTHING_OBJECT)
2180                 {
2181                         infotext = narrow_to_wide(selected_object->infoText());
2182
2183                         if(infotext == L"" && show_debug){
2184                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2185                         }
2186
2187                         //if(input->getLeftClicked())
2188                         if(input->getLeftState())
2189                         {
2190                                 bool do_punch = false;
2191                                 bool do_punch_damage = false;
2192                                 if(object_hit_delay_timer <= 0.0){
2193                                         do_punch = true;
2194                                         do_punch_damage = true;
2195                                         object_hit_delay_timer = object_hit_delay;
2196                                 }
2197                                 if(input->getLeftClicked()){
2198                                         do_punch = true;
2199                                 }
2200                                 if(do_punch){
2201                                         infostream<<"Left-clicked object"<<std::endl;
2202                                         left_punch = true;
2203                                 }
2204                                 if(do_punch_damage){
2205                                         // Report direct punch
2206                                         v3f objpos = selected_object->getPosition();
2207                                         v3f dir = (objpos - player_position).normalize();
2208                                         
2209                                         bool disable_send = selected_object->directReportPunch(
2210                                                         dir, &playeritem, time_from_last_punch);
2211                                         time_from_last_punch = 0;
2212                                         if(!disable_send)
2213                                                 client.interact(0, pointed);
2214                                 }
2215                         }
2216                         else if(input->getRightClicked())
2217                         {
2218                                 infostream<<"Right-clicked object"<<std::endl;
2219                                 client.interact(3, pointed);  // place
2220                         }
2221                 }
2222                 else if(input->getLeftState())
2223                 {
2224                         // When button is held down in air, show continuous animation
2225                         left_punch = true;
2226                 }
2227
2228                 pointed_old = pointed;
2229                 
2230                 if(left_punch || input->getLeftClicked())
2231                 {
2232                         camera.setDigging(0); // left click animation
2233                 }
2234
2235                 input->resetLeftClicked();
2236                 input->resetRightClicked();
2237
2238                 input->resetLeftReleased();
2239                 input->resetRightReleased();
2240                 
2241                 /*
2242                         Calculate stuff for drawing
2243                 */
2244
2245                 /*
2246                         Fog range
2247                 */
2248         
2249                 f32 fog_range;
2250                 if(farmesh)
2251                 {
2252                         fog_range = BS*farmesh_range;
2253                 }
2254                 else
2255                 {
2256                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2257                         fog_range *= 0.9;
2258                         if(draw_control.range_all)
2259                                 fog_range = 100000*BS;
2260                 }
2261
2262                 /*
2263                         Calculate general brightness
2264                 */
2265                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2266                 float time_brightness = (float)decode_light(
2267                                 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2268                 float direct_brightness = 0;
2269                 bool sunlight_seen = false;
2270                 if(g_settings->getBool("free_move")){
2271                         direct_brightness = time_brightness;
2272                         sunlight_seen = true;
2273                 } else {
2274                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2275                         float old_brightness = sky->getBrightness();
2276                         direct_brightness = (float)client.getEnv().getClientMap()
2277                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2278                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2279                                         / 255.0;
2280                 }
2281                 
2282                 time_of_day = client.getEnv().getTimeOfDayF();
2283                 float maxsm = 0.05;
2284                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2285                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2286                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2287                         time_of_day_smooth = time_of_day;
2288                 float todsm = 0.05;
2289                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2290                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2291                                         + (time_of_day+1.0) * todsm;
2292                 else
2293                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2294                                         + time_of_day * todsm;
2295                         
2296                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2297                                 sunlight_seen);
2298                 
2299                 float brightness = sky->getBrightness();
2300                 video::SColor bgcolor = sky->getBgColor();
2301                 video::SColor skycolor = sky->getSkyColor();
2302
2303                 /*
2304                         Update clouds
2305                 */
2306                 if(clouds){
2307                         if(sky->getCloudsVisible()){
2308                                 clouds->setVisible(true);
2309                                 clouds->step(dtime);
2310                                 clouds->update(v2f(player_position.X, player_position.Z),
2311                                                 sky->getCloudColor());
2312                         } else{
2313                                 clouds->setVisible(false);
2314                         }
2315                 }
2316                 
2317                 /*
2318                         Update farmesh
2319                 */
2320                 if(farmesh)
2321                 {
2322                         farmesh_range = draw_control.wanted_range * 10;
2323                         if(draw_control.range_all && farmesh_range < 500)
2324                                 farmesh_range = 500;
2325                         if(farmesh_range > 1000)
2326                                 farmesh_range = 1000;
2327
2328                         farmesh->step(dtime);
2329                         farmesh->update(v2f(player_position.X, player_position.Z),
2330                                         brightness, farmesh_range);
2331                 }
2332                 
2333                 /*
2334                         Fog
2335                 */
2336                 
2337                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2338                 {
2339                         driver->setFog(
2340                                 bgcolor,
2341                                 video::EFT_FOG_LINEAR,
2342                                 fog_range*0.4,
2343                                 fog_range*1.0,
2344                                 0.01,
2345                                 false, // pixel fog
2346                                 false // range fog
2347                         );
2348                 }
2349                 else
2350                 {
2351                         driver->setFog(
2352                                 bgcolor,
2353                                 video::EFT_FOG_LINEAR,
2354                                 100000*BS,
2355                                 110000*BS,
2356                                 0.01,
2357                                 false, // pixel fog
2358                                 false // range fog
2359                         );
2360                 }
2361
2362                 /*
2363                         Update gui stuff (0ms)
2364                 */
2365
2366                 //TimeTaker guiupdatetimer("Gui updating");
2367                 
2368                 const char program_name_and_version[] =
2369                         "Minetest-c55 " VERSION_STRING;
2370
2371                 if(show_debug)
2372                 {
2373                         static float drawtime_avg = 0;
2374                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2375                         /*static float beginscenetime_avg = 0;
2376                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2377                         static float scenetime_avg = 0;
2378                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2379                         static float endscenetime_avg = 0;
2380                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2381                         
2382                         char temptext[300];
2383                         snprintf(temptext, 300, "%s ("
2384                                         "R: range_all=%i"
2385                                         ")"
2386                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2387                                         ", v_range = %.1f, RTT = %.3f",
2388                                         program_name_and_version,
2389                                         draw_control.range_all,
2390                                         drawtime_avg,
2391                                         dtime_jitter1_max_fraction * 100.0,
2392                                         draw_control.wanted_range,
2393                                         client.getRTT()
2394                                         );
2395                         
2396                         guitext->setText(narrow_to_wide(temptext).c_str());
2397                         guitext->setVisible(true);
2398                 }
2399                 else if(show_hud || show_chat)
2400                 {
2401                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2402                         guitext->setVisible(true);
2403                 }
2404                 else
2405                 {
2406                         guitext->setVisible(false);
2407                 }
2408                 
2409                 if(show_debug)
2410                 {
2411                         char temptext[300];
2412                         snprintf(temptext, 300,
2413                                         "(% .1f, % .1f, % .1f)"
2414                                         " (yaw = %.1f)",
2415                                         player_position.X/BS,
2416                                         player_position.Y/BS,
2417                                         player_position.Z/BS,
2418                                         wrapDegrees_0_360(camera_yaw));
2419
2420                         guitext2->setText(narrow_to_wide(temptext).c_str());
2421                         guitext2->setVisible(true);
2422                 }
2423                 else
2424                 {
2425                         guitext2->setVisible(false);
2426                 }
2427                 
2428                 {
2429                         guitext_info->setText(infotext.c_str());
2430                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2431                 }
2432
2433                 {
2434                         float statustext_time_max = 1.5;
2435                         if(!statustext.empty())
2436                         {
2437                                 statustext_time += dtime;
2438                                 if(statustext_time >= statustext_time_max)
2439                                 {
2440                                         statustext = L"";
2441                                         statustext_time = 0;
2442                                 }
2443                         }
2444                         guitext_status->setText(statustext.c_str());
2445                         guitext_status->setVisible(!statustext.empty());
2446
2447                         if(!statustext.empty())
2448                         {
2449                                 s32 status_y = screensize.Y - 130;
2450                                 core::rect<s32> rect(
2451                                                 10,
2452                                                 status_y - guitext_status->getTextHeight(),
2453                                                 screensize.X - 10,
2454                                                 status_y
2455                                 );
2456                                 guitext_status->setRelativePosition(rect);
2457
2458                                 // Fade out
2459                                 video::SColor initial_color(255,0,0,0);
2460                                 if(guienv->getSkin())
2461                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2462                                 video::SColor final_color = initial_color;
2463                                 final_color.setAlpha(0);
2464                                 video::SColor fade_color =
2465                                         initial_color.getInterpolated_quadratic(
2466                                                 initial_color,
2467                                                 final_color,
2468                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
2469                                 guitext_status->setOverrideColor(fade_color);
2470                                 guitext_status->enableOverrideColor(true);
2471                         }
2472                 }
2473                 
2474                 /*
2475                         Get chat messages from client
2476                 */
2477                 {
2478                         // Get new messages from error log buffer
2479                         while(!chat_log_error_buf.empty())
2480                         {
2481                                 chat_backend.addMessage(L"", narrow_to_wide(
2482                                                 chat_log_error_buf.get()));
2483                         }
2484                         // Get new messages from client
2485                         std::wstring message;
2486                         while(client.getChatMessage(message))
2487                         {
2488                                 chat_backend.addUnparsedMessage(message);
2489                         }
2490                         // Remove old messages
2491                         chat_backend.step(dtime);
2492
2493                         // Display all messages in a static text element
2494                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2495                         std::wstring recent_chat = chat_backend.getRecentChat();
2496                         guitext_chat->setText(recent_chat.c_str());
2497
2498                         // Update gui element size and position
2499                         s32 chat_y = 5+(text_height+5);
2500                         if(show_debug)
2501                                 chat_y += (text_height+5);
2502                         core::rect<s32> rect(
2503                                 10,
2504                                 chat_y,
2505                                 screensize.X - 10,
2506                                 chat_y + guitext_chat->getTextHeight()
2507                         );
2508                         guitext_chat->setRelativePosition(rect);
2509
2510                         // Don't show chat if disabled or empty or profiler is enabled
2511                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
2512                                         && !show_profiler);
2513                 }
2514
2515                 /*
2516                         Inventory
2517                 */
2518                 
2519                 if(client.getPlayerItem() != new_playeritem)
2520                 {
2521                         client.selectPlayerItem(new_playeritem);
2522                 }
2523                 if(client.getLocalInventoryUpdated())
2524                 {
2525                         //infostream<<"Updating local inventory"<<std::endl;
2526                         client.getLocalInventory(local_inventory);
2527                         
2528                         update_wielded_item_trigger = true;
2529                 }
2530                 if(update_wielded_item_trigger)
2531                 {
2532                         update_wielded_item_trigger = false;
2533                         // Update wielded tool
2534                         InventoryList *mlist = local_inventory.getList("main");
2535                         ItemStack item;
2536                         if(mlist != NULL)
2537                                 item = mlist->getItem(client.getPlayerItem());
2538                         camera.wield(item, gamedef);
2539                 }
2540                 
2541                 /*
2542                         Drawing begins
2543                 */
2544
2545                 TimeTaker tt_draw("mainloop: draw");
2546
2547                 
2548                 {
2549                         TimeTaker timer("beginScene");
2550                         //driver->beginScene(false, true, bgcolor);
2551                         //driver->beginScene(true, true, bgcolor);
2552                         driver->beginScene(true, true, skycolor);
2553                         beginscenetime = timer.stop(true);
2554                 }
2555                 
2556                 //timer3.stop();
2557         
2558                 //infostream<<"smgr->drawAll()"<<std::endl;
2559                 {
2560                         TimeTaker timer("smgr");
2561                         smgr->drawAll();
2562                         scenetime = timer.stop(true);
2563                 }
2564                 
2565                 {
2566                 //TimeTaker timer9("auxiliary drawings");
2567                 // 0ms
2568                 
2569                 //timer9.stop();
2570                 //TimeTaker //timer10("//timer10");
2571                 
2572                 video::SMaterial m;
2573                 //m.Thickness = 10;
2574                 m.Thickness = 3;
2575                 m.Lighting = false;
2576                 driver->setMaterial(m);
2577
2578                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2579
2580                 if(show_hud)
2581                 {
2582                         for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2583                                         i != hilightboxes.end(); i++)
2584                         {
2585                                 /*infostream<<"hilightbox min="
2586                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2587                                                 <<" max="
2588                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2589                                                 <<std::endl;*/
2590                                 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2591                         }
2592                 }
2593
2594                 /*
2595                         Wielded tool
2596                 */
2597                 if(show_hud)
2598                 {
2599                         // Warning: This clears the Z buffer.
2600                         camera.drawWieldedTool();
2601                 }
2602
2603                 /*
2604                         Post effects
2605                 */
2606                 {
2607                         client.getEnv().getClientMap().renderPostFx();
2608                 }
2609
2610                 /*
2611                         Profiler graph
2612                 */
2613                 if(show_profiler_graph)
2614                 {
2615                         graph.draw(10, screensize.Y - 10, driver, font);
2616                 }
2617
2618                 /*
2619                         Draw crosshair
2620                 */
2621                 if(show_hud)
2622                 {
2623                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2624                                         displaycenter + core::vector2d<s32>(10,0),
2625                                         video::SColor(255,255,255,255));
2626                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2627                                         displaycenter + core::vector2d<s32>(0,10),
2628                                         video::SColor(255,255,255,255));
2629                 }
2630
2631                 } // timer
2632
2633                 //timer10.stop();
2634                 //TimeTaker //timer11("//timer11");
2635
2636                 /*
2637                         Draw gui
2638                 */
2639                 // 0-1ms
2640                 guienv->drawAll();
2641
2642                 /*
2643                         Draw hotbar
2644                 */
2645                 if(show_hud)
2646                 {
2647                         draw_hotbar(driver, font, gamedef,
2648                                         v2s32(displaycenter.X, screensize.Y),
2649                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2650                                         client.getHP(), client.getPlayerItem());
2651                 }
2652
2653                 /*
2654                         Damage flash
2655                 */
2656                 if(damage_flash_timer > 0.0)
2657                 {
2658                         damage_flash_timer -= dtime;
2659                         
2660                         video::SColor color(128,255,0,0);
2661                         driver->draw2DRectangle(color,
2662                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2663                                         NULL);
2664                 }
2665
2666                 // Clear Z buffer
2667                 driver->clearZBuffer();
2668                 // Draw some sky things
2669                 //draw_horizon(driver, camera.getCameraNode());
2670                 
2671                 /*
2672                         End scene
2673                 */
2674                 {
2675                         TimeTaker timer("endScene");
2676                         endSceneX(driver);
2677                         endscenetime = timer.stop(true);
2678                 }
2679
2680                 drawtime = tt_draw.stop(true);
2681                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2682
2683                 /*
2684                         End of drawing
2685                 */
2686
2687                 static s16 lastFPS = 0;
2688                 //u16 fps = driver->getFPS();
2689                 u16 fps = (1.0/dtime_avg1);
2690
2691                 if (lastFPS != fps)
2692                 {
2693                         core::stringw str = L"Minetest [";
2694                         str += driver->getName();
2695                         str += "] FPS=";
2696                         str += fps;
2697
2698                         device->setWindowCaption(str.c_str());
2699                         lastFPS = fps;
2700                 }
2701
2702                 /*
2703                         Log times and stuff for visualization
2704                 */
2705                 Profiler::GraphValues values;
2706                 g_profiler->graphGet(values);
2707                 graph.put(values);
2708         }
2709
2710         /*
2711                 Drop stuff
2712         */
2713         if(clouds)
2714                 clouds->drop();
2715         if(gui_chat_console)
2716                 gui_chat_console->drop();
2717         
2718         /*
2719                 Draw a "shutting down" screen, which will be shown while the map
2720                 generator and other stuff quits
2721         */
2722         {
2723                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2724                 draw_load_screen(L"Shutting down stuff...", driver, font);
2725                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2726                 guienv->drawAll();
2727                 driver->endScene();
2728                 gui_shuttingdowntext->remove();*/
2729         }
2730
2731         chat_backend.addMessage(L"", L"# Disconnected.");
2732         chat_backend.addMessage(L"", L"");
2733
2734         // Client scope (client is destructed before destructing *def and tsrc)
2735         }while(0);
2736
2737         delete tsrc;
2738         delete nodedef;
2739         delete itemdef;
2740 }
2741
2742