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