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