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