]> git.lizzy.rs Git - minetest.git/blob - src/game.cpp
replace Server smart pointer with conventional one to gain control over dtor call...
[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         Server *server = NULL;
996
997         try{
998         // Event manager
999         EventManager eventmgr;
1000
1001         // Sound maker
1002         SoundMaker soundmaker(sound, nodedef);
1003         soundmaker.registerReceiver(&eventmgr);
1004         
1005         // Add chat log output for errors to be shown in chat
1006         LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1007
1008         // Create UI for modifying quicktune values
1009         QuicktuneShortcutter quicktune;
1010
1011         /*
1012                 Create server.
1013         */
1014
1015         if(address == ""){
1016                 draw_load_screen(L"Creating server...", driver, font);
1017                 infostream<<"Creating server"<<std::endl;
1018                 server = new Server(map_dir, configpath, gamespec,
1019                                 simple_singleplayer_mode);
1020                 server->start(port);
1021         }
1022
1023         do{ // Client scope (breakable do-while(0))
1024         
1025         /*
1026                 Create client
1027         */
1028
1029         draw_load_screen(L"Creating client...", driver, font);
1030         infostream<<"Creating client"<<std::endl;
1031         
1032         MapDrawControl draw_control;
1033
1034         Client client(device, playername.c_str(), password, draw_control,
1035                         tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
1036         
1037         // Client acts as our GameDef
1038         IGameDef *gamedef = &client;
1039                         
1040         draw_load_screen(L"Resolving address...", driver, font);
1041         Address connect_address(0,0,0,0, port);
1042         try{
1043                 if(address == "")
1044                         //connect_address.Resolve("localhost");
1045                         connect_address.setAddress(127,0,0,1);
1046                 else
1047                         connect_address.Resolve(address.c_str());
1048         }
1049         catch(ResolveError &e)
1050         {
1051                 error_message = L"Couldn't resolve address";
1052                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1053                 // Break out of client scope
1054                 break;
1055         }
1056
1057         /*
1058                 Attempt to connect to the server
1059         */
1060         
1061         infostream<<"Connecting to server at ";
1062         connect_address.print(&infostream);
1063         infostream<<std::endl;
1064         client.connect(connect_address);
1065         
1066         /*
1067                 Wait for server to accept connection
1068         */
1069         bool could_connect = false;
1070         bool connect_aborted = false;
1071         try{
1072                 float frametime = 0.033;
1073                 float time_counter = 0.0;
1074                 input->clear();
1075                 while(device->run())
1076                 {
1077                         // Update client and server
1078                         client.step(frametime);
1079                         if(server != NULL)
1080                                 server->step(frametime);
1081                         
1082                         // End condition
1083                         if(client.connectedAndInitialized()){
1084                                 could_connect = true;
1085                                 break;
1086                         }
1087                         // Break conditions
1088                         if(client.accessDenied()){
1089                                 error_message = L"Access denied. Reason: "
1090                                                 +client.accessDeniedReason();
1091                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1092                                 break;
1093                         }
1094                         if(input->wasKeyDown(EscapeKey)){
1095                                 connect_aborted = true;
1096                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1097                                 break;
1098                         }
1099                         
1100                         // Display status
1101                         std::wostringstream ss;
1102                         ss<<L"Connecting to server... (press Escape to cancel)\n";
1103                         std::wstring animation = L"/-\\|";
1104                         ss<<animation[(int)(time_counter/0.2)%4];
1105                         draw_load_screen(ss.str(), driver, font);
1106                         
1107                         // Delay a bit
1108                         sleep_ms(1000*frametime);
1109                         time_counter += frametime;
1110                 }
1111         }
1112         catch(con::PeerNotFoundException &e)
1113         {}
1114         
1115         /*
1116                 Handle failure to connect
1117         */
1118         if(!could_connect){
1119                 if(error_message == L"" && !connect_aborted){
1120                         error_message = L"Connection failed";
1121                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1122                 }
1123                 // Break out of client scope
1124                 break;
1125         }
1126         
1127         /*
1128                 Wait until content has been received
1129         */
1130         bool got_content = false;
1131         bool content_aborted = false;
1132         {
1133                 float frametime = 0.033;
1134                 float time_counter = 0.0;
1135                 input->clear();
1136                 while(device->run())
1137                 {
1138                         // Update client and server
1139                         client.step(frametime);
1140                         if(server != NULL)
1141                                 server->step(frametime);
1142                         
1143                         // End condition
1144                         if(client.texturesReceived() &&
1145                                         client.itemdefReceived() &&
1146                                         client.nodedefReceived()){
1147                                 got_content = true;
1148                                 break;
1149                         }
1150                         // Break conditions
1151                         if(!client.connectedAndInitialized()){
1152                                 error_message = L"Client disconnected";
1153                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1154                                 break;
1155                         }
1156                         if(input->wasKeyDown(EscapeKey)){
1157                                 content_aborted = true;
1158                                 infostream<<"Connect aborted [Escape]"<<std::endl;
1159                                 break;
1160                         }
1161                         
1162                         // Display status
1163                         std::wostringstream ss;
1164                         ss<<L"Waiting content... (press Escape to cancel)\n";
1165
1166                         ss<<(client.itemdefReceived()?L"[X]":L"[  ]");
1167                         ss<<L" Item definitions\n";
1168                         ss<<(client.nodedefReceived()?L"[X]":L"[  ]");
1169                         ss<<L" Node definitions\n";
1170                         ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1171                         ss<<L" Media\n";
1172
1173                         draw_load_screen(ss.str(), driver, font);
1174                         
1175                         // Delay a bit
1176                         sleep_ms(1000*frametime);
1177                         time_counter += frametime;
1178                 }
1179         }
1180
1181         if(!got_content){
1182                 if(error_message == L"" && !content_aborted){
1183                         error_message = L"Something failed";
1184                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1185                 }
1186                 // Break out of client scope
1187                 break;
1188         }
1189
1190         /*
1191                 After all content has been received:
1192                 Update cached textures, meshes and materials
1193         */
1194         client.afterContentReceived();
1195
1196         /*
1197                 Create the camera node
1198         */
1199         Camera camera(smgr, draw_control, gamedef);
1200         if (!camera.successfullyCreated(error_message))
1201                 return;
1202
1203         f32 camera_yaw = 0; // "right/left"
1204         f32 camera_pitch = 0; // "up/down"
1205
1206         /*
1207                 Clouds
1208         */
1209         
1210         Clouds *clouds = NULL;
1211         if(g_settings->getBool("enable_clouds"))
1212         {
1213                 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1214         }
1215
1216         /*
1217                 Skybox thingy
1218         */
1219
1220         Sky *sky = NULL;
1221         sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1222         
1223         /*
1224                 FarMesh
1225         */
1226
1227         FarMesh *farmesh = NULL;
1228         if(g_settings->getBool("enable_farmesh"))
1229         {
1230                 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1231         }
1232
1233         /*
1234                 A copy of the local inventory
1235         */
1236         Inventory local_inventory(itemdef);
1237
1238         /*
1239                 Find out size of crack animation
1240         */
1241         int crack_animation_length = 5;
1242         {
1243                 video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
1244                 v2u32 size = t->getOriginalSize();
1245                 crack_animation_length = size.Y / size.X;
1246         }
1247
1248         /*
1249                 Add some gui stuff
1250         */
1251
1252         // First line of debug text
1253         gui::IGUIStaticText *guitext = guienv->addStaticText(
1254                         L"Minetest",
1255                         core::rect<s32>(5, 5, 795, 5+text_height),
1256                         false, false);
1257         // Second line of debug text
1258         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1259                         L"",
1260                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1261                         false, false);
1262         // At the middle of the screen
1263         // Object infos are shown in this
1264         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1265                         L"",
1266                         core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1267                         false, true);
1268         
1269         // Status text (displays info when showing and hiding GUI stuff, etc.)
1270         gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1271                         L"<Status>",
1272                         core::rect<s32>(0,0,0,0),
1273                         false, false);
1274         guitext_status->setVisible(false);
1275         
1276         std::wstring statustext;
1277         float statustext_time = 0;
1278         
1279         // Chat text
1280         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1281                         L"",
1282                         core::rect<s32>(0,0,0,0),
1283                         //false, false); // Disable word wrap as of now
1284                         false, true);
1285         // Remove stale "recent" chat messages from previous connections
1286         chat_backend.clearRecentChat();
1287         // Chat backend and console
1288         GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1289         
1290         // Profiler text (size is updated when text is updated)
1291         gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1292                         L"<Profiler>",
1293                         core::rect<s32>(0,0,0,0),
1294                         false, false);
1295         guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1296         guitext_profiler->setVisible(false);
1297         
1298         /*
1299                 Some statistics are collected in these
1300         */
1301         u32 drawtime = 0;
1302         u32 beginscenetime = 0;
1303         u32 scenetime = 0;
1304         u32 endscenetime = 0;
1305         
1306         float recent_turn_speed = 0.0;
1307         
1308         ProfilerGraph graph;
1309         // Initially clear the profiler
1310         Profiler::GraphValues dummyvalues;
1311         g_profiler->graphGet(dummyvalues);
1312
1313         float nodig_delay_timer = 0.0;
1314         float dig_time = 0.0;
1315         u16 dig_index = 0;
1316         PointedThing pointed_old;
1317         bool digging = false;
1318         bool ldown_for_dig = false;
1319
1320         float damage_flash = 0;
1321         s16 farmesh_range = 20*MAP_BLOCKSIZE;
1322
1323         float jump_timer = 0;
1324         bool reset_jump_timer = false;
1325
1326         const float object_hit_delay = 0.2;
1327         float object_hit_delay_timer = 0.0;
1328         float time_from_last_punch = 10;
1329
1330         float update_draw_list_timer = 0.0;
1331         v3f update_draw_list_last_cam_dir;
1332
1333         bool invert_mouse = g_settings->getBool("invert_mouse");
1334
1335         bool respawn_menu_active = false;
1336         bool update_wielded_item_trigger = false;
1337
1338         bool show_hud = true;
1339         bool show_chat = true;
1340         bool force_fog_off = false;
1341         f32 fog_range = 100*BS;
1342         bool disable_camera_update = false;
1343         bool show_debug = g_settings->getBool("show_debug");
1344         bool show_profiler_graph = false;
1345         u32 show_profiler = 0;
1346         u32 show_profiler_max = 3;  // Number of pages
1347
1348         float time_of_day = 0;
1349         float time_of_day_smooth = 0;
1350
1351         float repeat_rightclick_timer = 0;
1352
1353         /*
1354                 Shader constants
1355         */
1356         shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1357                         sky, &force_fog_off, &fog_range, &client));
1358
1359         /*
1360                 Main loop
1361         */
1362
1363         bool first_loop_after_window_activation = true;
1364
1365         // TODO: Convert the static interval timers to these
1366         // Interval limiter for profiler
1367         IntervalLimiter m_profiler_interval;
1368
1369         // Time is in milliseconds
1370         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1371         // NOTE: So we have to use getTime() and call run()s between them
1372         u32 lasttime = device->getTimer()->getTime();
1373
1374         LocalPlayer* player = client.getEnv().getLocalPlayer();
1375         player->hurt_tilt_timer = 0;
1376         player->hurt_tilt_strength = 0;
1377
1378         for(;;)
1379         {
1380                 if(device->run() == false || kill == true)
1381                         break;
1382
1383                 // Time of frame without fps limit
1384                 float busytime;
1385                 u32 busytime_u32;
1386                 {
1387                         // not using getRealTime is necessary for wine
1388                         u32 time = device->getTimer()->getTime();
1389                         if(time > lasttime)
1390                                 busytime_u32 = time - lasttime;
1391                         else
1392                                 busytime_u32 = 0;
1393                         busytime = busytime_u32 / 1000.0;
1394                 }
1395                 
1396                 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1397
1398                 // Necessary for device->getTimer()->getTime()
1399                 device->run();
1400
1401                 /*
1402                         FPS limiter
1403                 */
1404
1405                 {
1406                         float fps_max = g_settings->getFloat("fps_max");
1407                         u32 frametime_min = 1000./fps_max;
1408                         
1409                         if(busytime_u32 < frametime_min)
1410                         {
1411                                 u32 sleeptime = frametime_min - busytime_u32;
1412                                 device->sleep(sleeptime);
1413                                 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1414                         }
1415                 }
1416
1417                 // Necessary for device->getTimer()->getTime()
1418                 device->run();
1419
1420                 /*
1421                         Time difference calculation
1422                 */
1423                 f32 dtime; // in seconds
1424                 
1425                 u32 time = device->getTimer()->getTime();
1426                 if(time > lasttime)
1427                         dtime = (time - lasttime) / 1000.0;
1428                 else
1429                         dtime = 0;
1430                 lasttime = time;
1431
1432                 g_profiler->graphAdd("mainloop_dtime", dtime);
1433
1434                 /* Run timers */
1435
1436                 if(nodig_delay_timer >= 0)
1437                         nodig_delay_timer -= dtime;
1438                 if(object_hit_delay_timer >= 0)
1439                         object_hit_delay_timer -= dtime;
1440                 time_from_last_punch += dtime;
1441                 
1442                 g_profiler->add("Elapsed time", dtime);
1443                 g_profiler->avg("FPS", 1./dtime);
1444
1445                 /*
1446                         Time average and jitter calculation
1447                 */
1448
1449                 static f32 dtime_avg1 = 0.0;
1450                 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1451                 f32 dtime_jitter1 = dtime - dtime_avg1;
1452
1453                 static f32 dtime_jitter1_max_sample = 0.0;
1454                 static f32 dtime_jitter1_max_fraction = 0.0;
1455                 {
1456                         static f32 jitter1_max = 0.0;
1457                         static f32 counter = 0.0;
1458                         if(dtime_jitter1 > jitter1_max)
1459                                 jitter1_max = dtime_jitter1;
1460                         counter += dtime;
1461                         if(counter > 0.0)
1462                         {
1463                                 counter -= 3.0;
1464                                 dtime_jitter1_max_sample = jitter1_max;
1465                                 dtime_jitter1_max_fraction
1466                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1467                                 jitter1_max = 0.0;
1468                         }
1469                 }
1470                 
1471                 /*
1472                         Busytime average and jitter calculation
1473                 */
1474
1475                 static f32 busytime_avg1 = 0.0;
1476                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1477                 f32 busytime_jitter1 = busytime - busytime_avg1;
1478                 
1479                 static f32 busytime_jitter1_max_sample = 0.0;
1480                 static f32 busytime_jitter1_min_sample = 0.0;
1481                 {
1482                         static f32 jitter1_max = 0.0;
1483                         static f32 jitter1_min = 0.0;
1484                         static f32 counter = 0.0;
1485                         if(busytime_jitter1 > jitter1_max)
1486                                 jitter1_max = busytime_jitter1;
1487                         if(busytime_jitter1 < jitter1_min)
1488                                 jitter1_min = busytime_jitter1;
1489                         counter += dtime;
1490                         if(counter > 0.0){
1491                                 counter -= 3.0;
1492                                 busytime_jitter1_max_sample = jitter1_max;
1493                                 busytime_jitter1_min_sample = jitter1_min;
1494                                 jitter1_max = 0.0;
1495                                 jitter1_min = 0.0;
1496                         }
1497                 }
1498
1499                 /*
1500                         Handle miscellaneous stuff
1501                 */
1502                 
1503                 if(client.accessDenied())
1504                 {
1505                         error_message = L"Access denied. Reason: "
1506                                         +client.accessDeniedReason();
1507                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1508                         break;
1509                 }
1510
1511                 if(g_gamecallback->disconnect_requested)
1512                 {
1513                         g_gamecallback->disconnect_requested = false;
1514                         break;
1515                 }
1516
1517                 if(g_gamecallback->changepassword_requested)
1518                 {
1519                         (new GUIPasswordChange(guienv, guiroot, -1,
1520                                 &g_menumgr, &client))->drop();
1521                         g_gamecallback->changepassword_requested = false;
1522                 }
1523
1524                 if(g_gamecallback->changevolume_requested)
1525                 {
1526                         (new GUIVolumeChange(guienv, guiroot, -1,
1527                                 &g_menumgr, &client))->drop();
1528                         g_gamecallback->changevolume_requested = false;
1529                 }
1530
1531                 /* Process TextureSource's queue */
1532                 tsrc->processQueue();
1533
1534                 /* Process ItemDefManager's queue */
1535                 itemdef->processQueue(gamedef);
1536
1537                 /*
1538                         Process ShaderSource's queue
1539                 */
1540                 shsrc->processQueue();
1541
1542                 /*
1543                         Random calculations
1544                 */
1545                 last_screensize = screensize;
1546                 screensize = driver->getScreenSize();
1547                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1548                 //bool screensize_changed = screensize != last_screensize;
1549
1550                 // Resize hotbar
1551                 if(screensize.Y <= 800)
1552                         hotbar_imagesize = 32;
1553                 else if(screensize.Y <= 1280)
1554                         hotbar_imagesize = 48;
1555                 else
1556                         hotbar_imagesize = 64;
1557                 
1558                 // Hilight boxes collected during the loop and displayed
1559                 std::vector<aabb3f> hilightboxes;
1560                 
1561                 // Info text
1562                 std::wstring infotext;
1563
1564                 /*
1565                         Debug info for client
1566                 */
1567                 {
1568                         static float counter = 0.0;
1569                         counter -= dtime;
1570                         if(counter < 0)
1571                         {
1572                                 counter = 30.0;
1573                                 client.printDebugInfo(infostream);
1574                         }
1575                 }
1576
1577                 /*
1578                         Profiler
1579                 */
1580                 float profiler_print_interval =
1581                                 g_settings->getFloat("profiler_print_interval");
1582                 bool print_to_log = true;
1583                 if(profiler_print_interval == 0){
1584                         print_to_log = false;
1585                         profiler_print_interval = 5;
1586                 }
1587                 if(m_profiler_interval.step(dtime, profiler_print_interval))
1588                 {
1589                         if(print_to_log){
1590                                 infostream<<"Profiler:"<<std::endl;
1591                                 g_profiler->print(infostream);
1592                         }
1593
1594                         update_profiler_gui(guitext_profiler, font, text_height,
1595                                         show_profiler, show_profiler_max);
1596
1597                         g_profiler->clear();
1598                 }
1599
1600                 /*
1601                         Direct handling of user input
1602                 */
1603                 
1604                 // Reset input if window not active or some menu is active
1605                 if(device->isWindowActive() == false
1606                                 || noMenuActive() == false
1607                                 || guienv->hasFocus(gui_chat_console))
1608                 {
1609                         input->clear();
1610                 }
1611
1612                 // Input handler step() (used by the random input generator)
1613                 input->step(dtime);
1614
1615                 // Increase timer for doubleclick of "jump"
1616                 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1617                         jump_timer += dtime;
1618
1619                 /*
1620                         Launch menus and trigger stuff according to keys
1621                 */
1622                 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1623                 {
1624                         // drop selected item
1625                         IDropAction *a = new IDropAction();
1626                         a->count = 0;
1627                         a->from_inv.setCurrentPlayer();
1628                         a->from_list = "main";
1629                         a->from_i = client.getPlayerItem();
1630                         client.inventoryAction(a);
1631                 }
1632                 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1633                 {
1634                         infostream<<"the_game: "
1635                                         <<"Launching inventory"<<std::endl;
1636                         
1637                         GUIFormSpecMenu *menu =
1638                                 new GUIFormSpecMenu(device, guiroot, -1,
1639                                         &g_menumgr,
1640                                         &client, gamedef);
1641
1642                         InventoryLocation inventoryloc;
1643                         inventoryloc.setCurrentPlayer();
1644
1645                         PlayerInventoryFormSource *src = new PlayerInventoryFormSource(&client);
1646                         assert(src);
1647                         menu->setFormSpec(src->getForm(), inventoryloc);
1648                         menu->setFormSource(src);
1649                         menu->setTextDest(new TextDestPlayerInventory(&client));
1650                         menu->drop();
1651                 }
1652                 else if(input->wasKeyDown(EscapeKey))
1653                 {
1654                         infostream<<"the_game: "
1655                                         <<"Launching pause menu"<<std::endl;
1656                         // It will delete itself by itself
1657                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1658                                         &g_menumgr, simple_singleplayer_mode))->drop();
1659
1660                         // Move mouse cursor on top of the disconnect button
1661                         if(simple_singleplayer_mode)
1662                                 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1663                         else
1664                                 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1665                 }
1666                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1667                 {
1668                         TextDest *dest = new TextDestChat(&client);
1669
1670                         (new GUITextInputMenu(guienv, guiroot, -1,
1671                                         &g_menumgr, dest,
1672                                         L""))->drop();
1673                 }
1674                 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1675                 {
1676                         TextDest *dest = new TextDestChat(&client);
1677
1678                         (new GUITextInputMenu(guienv, guiroot, -1,
1679                                         &g_menumgr, dest,
1680                                         L"/"))->drop();
1681                 }
1682                 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1683                 {
1684                         if (!gui_chat_console->isOpenInhibited())
1685                         {
1686                                 // Open up to over half of the screen
1687                                 gui_chat_console->openConsole(0.6);
1688                                 guienv->setFocus(gui_chat_console);
1689                         }
1690                 }
1691                 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1692                 {
1693                         if(g_settings->getBool("free_move"))
1694                         {
1695                                 g_settings->set("free_move","false");
1696                                 statustext = L"free_move disabled";
1697                                 statustext_time = 0;
1698                         }
1699                         else
1700                         {
1701                                 g_settings->set("free_move","true");
1702                                 statustext = L"free_move enabled";
1703                                 statustext_time = 0;
1704                                 if(!client.checkPrivilege("fly"))
1705                                         statustext += L" (note: no 'fly' privilege)";
1706                         }
1707                 }
1708                 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1709                 {
1710                         if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1711                         {
1712                                 if(g_settings->getBool("free_move"))
1713                                 {
1714                                         g_settings->set("free_move","false");
1715                                         statustext = L"free_move disabled";
1716                                         statustext_time = 0;
1717                                 }
1718                                 else
1719                                 {
1720                                         g_settings->set("free_move","true");
1721                                         statustext = L"free_move enabled";
1722                                         statustext_time = 0;
1723                                         if(!client.checkPrivilege("fly"))
1724                                                 statustext += L" (note: no 'fly' privilege)";
1725                                 }
1726                         }
1727                         reset_jump_timer = true;
1728                 }
1729                 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1730                 {
1731                         if(g_settings->getBool("fast_move"))
1732                         {
1733                                 g_settings->set("fast_move","false");
1734                                 statustext = L"fast_move disabled";
1735                                 statustext_time = 0;
1736                         }
1737                         else
1738                         {
1739                                 g_settings->set("fast_move","true");
1740                                 statustext = L"fast_move enabled";
1741                                 statustext_time = 0;
1742                                 if(!client.checkPrivilege("fast"))
1743                                         statustext += L" (note: no 'fast' privilege)";
1744                         }
1745                 }
1746                 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1747                 {
1748                         if(g_settings->getBool("noclip"))
1749                         {
1750                                 g_settings->set("noclip","false");
1751                                 statustext = L"noclip disabled";
1752                                 statustext_time = 0;
1753                         }
1754                         else
1755                         {
1756                                 g_settings->set("noclip","true");
1757                                 statustext = L"noclip enabled";
1758                                 statustext_time = 0;
1759                                 if(!client.checkPrivilege("noclip"))
1760                                         statustext += L" (note: no 'noclip' privilege)";
1761                         }
1762                 }
1763                 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1764                 {
1765                         irr::video::IImage* const image = driver->createScreenShot(); 
1766                         if (image) { 
1767                                 irr::c8 filename[256]; 
1768                                 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
1769                                                  g_settings->get("screenshot_path").c_str(),
1770                                                  device->getTimer()->getRealTime()); 
1771                                 if (driver->writeImageToFile(image, filename)) {
1772                                         std::wstringstream sstr;
1773                                         sstr<<"Saved screenshot to '"<<filename<<"'";
1774                                         infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1775                                         statustext = sstr.str();
1776                                         statustext_time = 0;
1777                                 } else{
1778                                         infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1779                                 }
1780                                 image->drop(); 
1781                         }                        
1782                 }
1783                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1784                 {
1785                         show_hud = !show_hud;
1786                         if(show_hud)
1787                                 statustext = L"HUD shown";
1788                         else
1789                                 statustext = L"HUD hidden";
1790                         statustext_time = 0;
1791                 }
1792                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1793                 {
1794                         show_chat = !show_chat;
1795                         if(show_chat)
1796                                 statustext = L"Chat shown";
1797                         else
1798                                 statustext = L"Chat hidden";
1799                         statustext_time = 0;
1800                 }
1801                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1802                 {
1803                         force_fog_off = !force_fog_off;
1804                         if(force_fog_off)
1805                                 statustext = L"Fog disabled";
1806                         else
1807                                 statustext = L"Fog enabled";
1808                         statustext_time = 0;
1809                 }
1810                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1811                 {
1812                         disable_camera_update = !disable_camera_update;
1813                         if(disable_camera_update)
1814                                 statustext = L"Camera update disabled";
1815                         else
1816                                 statustext = L"Camera update enabled";
1817                         statustext_time = 0;
1818                 }
1819                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1820                 {
1821                         // Initial / 3x toggle: Chat only
1822                         // 1x toggle: Debug text with chat
1823                         // 2x toggle: Debug text with profiler graph
1824                         if(!show_debug)
1825                         {
1826                                 show_debug = true;
1827                                 show_profiler_graph = false;
1828                                 statustext = L"Debug info shown";
1829                                 statustext_time = 0;
1830                         }
1831                         else if(show_profiler_graph)
1832                         {
1833                                 show_debug = false;
1834                                 show_profiler_graph = false;
1835                                 statustext = L"Debug info and profiler graph hidden";
1836                                 statustext_time = 0;
1837                         }
1838                         else
1839                         {
1840                                 show_profiler_graph = true;
1841                                 statustext = L"Profiler graph shown";
1842                                 statustext_time = 0;
1843                         }
1844                 }
1845                 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1846                 {
1847                         show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1848
1849                         // FIXME: This updates the profiler with incomplete values
1850                         update_profiler_gui(guitext_profiler, font, text_height,
1851                                         show_profiler, show_profiler_max);
1852
1853                         if(show_profiler != 0)
1854                         {
1855                                 std::wstringstream sstr;
1856                                 sstr<<"Profiler shown (page "<<show_profiler
1857                                         <<" of "<<show_profiler_max<<")";
1858                                 statustext = sstr.str();
1859                                 statustext_time = 0;
1860                         }
1861                         else
1862                         {
1863                                 statustext = L"Profiler hidden";
1864                                 statustext_time = 0;
1865                         }
1866                 }
1867                 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1868                 {
1869                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1870                         s16 range_new = range + 10;
1871                         g_settings->set("viewing_range_nodes_min", itos(range_new));
1872                         statustext = narrow_to_wide(
1873                                         "Minimum viewing range changed to "
1874                                         + itos(range_new));
1875                         statustext_time = 0;
1876                 }
1877                 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1878                 {
1879                         s16 range = g_settings->getS16("viewing_range_nodes_min");
1880                         s16 range_new = range - 10;
1881                         if(range_new < 0)
1882                                 range_new = range;
1883                         g_settings->set("viewing_range_nodes_min",
1884                                         itos(range_new));
1885                         statustext = narrow_to_wide(
1886                                         "Minimum viewing range changed to "
1887                                         + itos(range_new));
1888                         statustext_time = 0;
1889                 }
1890                 
1891                 // Reset jump_timer
1892                 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
1893                 {
1894                         reset_jump_timer = false;
1895                         jump_timer = 0.0;
1896                 }
1897
1898                 // Handle QuicktuneShortcutter
1899                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1900                         quicktune.next();
1901                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1902                         quicktune.prev();
1903                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1904                         quicktune.inc();
1905                 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1906                         quicktune.dec();
1907                 {
1908                         std::string msg = quicktune.getMessage();
1909                         if(msg != ""){
1910                                 statustext = narrow_to_wide(msg);
1911                                 statustext_time = 0;
1912                         }
1913                 }
1914
1915                 // Item selection with mouse wheel
1916                 u16 new_playeritem = client.getPlayerItem();
1917                 {
1918                         s32 wheel = input->getMouseWheel();
1919                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1920                                         hotbar_itemcount-1);
1921
1922                         if(wheel < 0)
1923                         {
1924                                 if(new_playeritem < max_item)
1925                                         new_playeritem++;
1926                                 else
1927                                         new_playeritem = 0;
1928                         }
1929                         else if(wheel > 0)
1930                         {
1931                                 if(new_playeritem > 0)
1932                                         new_playeritem--;
1933                                 else
1934                                         new_playeritem = max_item;
1935                         }
1936                 }
1937                 
1938                 // Item selection
1939                 for(u16 i=0; i<10; i++)
1940                 {
1941                         const KeyPress *kp = NumberKey + (i + 1) % 10;
1942                         if(input->wasKeyDown(*kp))
1943                         {
1944                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1945                                 {
1946                                         new_playeritem = i;
1947
1948                                         infostream<<"Selected item: "
1949                                                         <<new_playeritem<<std::endl;
1950                                 }
1951                         }
1952                 }
1953
1954                 // Viewing range selection
1955                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1956                 {
1957                         draw_control.range_all = !draw_control.range_all;
1958                         if(draw_control.range_all)
1959                         {
1960                                 infostream<<"Enabled full viewing range"<<std::endl;
1961                                 statustext = L"Enabled full viewing range";
1962                                 statustext_time = 0;
1963                         }
1964                         else
1965                         {
1966                                 infostream<<"Disabled full viewing range"<<std::endl;
1967                                 statustext = L"Disabled full viewing range";
1968                                 statustext_time = 0;
1969                         }
1970                 }
1971
1972                 // Print debug stacks
1973                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1974                 {
1975                         dstream<<"-----------------------------------------"
1976                                         <<std::endl;
1977                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1978                         dstream<<"-----------------------------------------"
1979                                         <<std::endl;
1980                         debug_stacks_print();
1981                 }
1982
1983                 /*
1984                         Mouse and camera control
1985                         NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1986                 */
1987                 
1988                 float turn_amount = 0;
1989                 if((device->isWindowActive() && noMenuActive()) || random_input)
1990                 {
1991                         if(!random_input)
1992                         {
1993                                 // Mac OSX gets upset if this is set every frame
1994                                 if(device->getCursorControl()->isVisible())
1995                                         device->getCursorControl()->setVisible(false);
1996                         }
1997
1998                         if(first_loop_after_window_activation){
1999                                 //infostream<<"window active, first loop"<<std::endl;
2000                                 first_loop_after_window_activation = false;
2001                         }
2002                         else{
2003                                 s32 dx = input->getMousePos().X - displaycenter.X;
2004                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
2005                                 if(invert_mouse)
2006                                         dy = -dy;
2007                                 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2008                                 
2009                                 /*const float keyspeed = 500;
2010                                 if(input->isKeyDown(irr::KEY_UP))
2011                                         dy -= dtime * keyspeed;
2012                                 if(input->isKeyDown(irr::KEY_DOWN))
2013                                         dy += dtime * keyspeed;
2014                                 if(input->isKeyDown(irr::KEY_LEFT))
2015                                         dx -= dtime * keyspeed;
2016                                 if(input->isKeyDown(irr::KEY_RIGHT))
2017                                         dx += dtime * keyspeed;*/
2018                                 
2019                                 float d = 0.2;
2020                                 camera_yaw -= dx*d;
2021                                 camera_pitch += dy*d;
2022                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
2023                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
2024                                 
2025                                 turn_amount = v2f(dx, dy).getLength() * d;
2026                         }
2027                         input->setMousePos(displaycenter.X, displaycenter.Y);
2028                 }
2029                 else{
2030                         // Mac OSX gets upset if this is set every frame
2031                         if(device->getCursorControl()->isVisible() == false)
2032                                 device->getCursorControl()->setVisible(true);
2033
2034                         //infostream<<"window inactive"<<std::endl;
2035                         first_loop_after_window_activation = true;
2036                 }
2037                 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2038                 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2039
2040                 /*
2041                         Player speed control
2042                 */
2043                 {
2044                         /*bool a_up,
2045                         bool a_down,
2046                         bool a_left,
2047                         bool a_right,
2048                         bool a_jump,
2049                         bool a_superspeed,
2050                         bool a_sneak,
2051                         bool a_LMB,
2052                         bool a_RMB,
2053                         float a_pitch,
2054                         float a_yaw*/
2055                         PlayerControl control(
2056                                 input->isKeyDown(getKeySetting("keymap_forward")),
2057                                 input->isKeyDown(getKeySetting("keymap_backward")),
2058                                 input->isKeyDown(getKeySetting("keymap_left")),
2059                                 input->isKeyDown(getKeySetting("keymap_right")),
2060                                 input->isKeyDown(getKeySetting("keymap_jump")),
2061                                 input->isKeyDown(getKeySetting("keymap_special1")),
2062                                 input->isKeyDown(getKeySetting("keymap_sneak")),
2063                                 input->getLeftState(),
2064                                 input->getRightState(),
2065                                 camera_pitch,
2066                                 camera_yaw
2067                         );
2068                         client.setPlayerControl(control);
2069                         u32 keyPressed=
2070                         1*(int)input->isKeyDown(getKeySetting("keymap_forward"))+
2071                         2*(int)input->isKeyDown(getKeySetting("keymap_backward"))+
2072                         4*(int)input->isKeyDown(getKeySetting("keymap_left"))+
2073                         8*(int)input->isKeyDown(getKeySetting("keymap_right"))+
2074                         16*(int)input->isKeyDown(getKeySetting("keymap_jump"))+
2075                         32*(int)input->isKeyDown(getKeySetting("keymap_special1"))+
2076                         64*(int)input->isKeyDown(getKeySetting("keymap_sneak"))+
2077                         128*(int)input->getLeftState()+
2078                         256*(int)input->getRightState();
2079                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2080                         player->keyPressed=keyPressed;
2081                 }
2082                 
2083                 /*
2084                         Run server
2085                 */
2086
2087                 if(server != NULL)
2088                 {
2089                         //TimeTaker timer("server->step(dtime)");
2090                         server->step(dtime);
2091                 }
2092
2093                 /*
2094                         Process environment
2095                 */
2096                 
2097                 {
2098                         //TimeTaker timer("client.step(dtime)");
2099                         client.step(dtime);
2100                         //client.step(dtime_avg1);
2101                 }
2102
2103                 {
2104                         // Read client events
2105                         for(;;)
2106                         {
2107                                 ClientEvent event = client.getClientEvent();
2108                                 if(event.type == CE_NONE)
2109                                 {
2110                                         break;
2111                                 }
2112                                 else if(event.type == CE_PLAYER_DAMAGE &&
2113                                                 client.getHP() != 0)
2114                                 {
2115                                         //u16 damage = event.player_damage.amount;
2116                                         //infostream<<"Player damage: "<<damage<<std::endl;
2117
2118                                         damage_flash += 100.0;
2119                                         damage_flash += 8.0 * event.player_damage.amount;
2120
2121                                         player->hurt_tilt_timer = 1.5;
2122                                         player->hurt_tilt_strength = event.player_damage.amount/2;
2123                                         player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2124                                 }
2125                                 else if(event.type == CE_PLAYER_FORCE_MOVE)
2126                                 {
2127                                         camera_yaw = event.player_force_move.yaw;
2128                                         camera_pitch = event.player_force_move.pitch;
2129                                 }
2130                                 else if(event.type == CE_DEATHSCREEN)
2131                                 {
2132                                         if(respawn_menu_active)
2133                                                 continue;
2134
2135                                         /*bool set_camera_point_target =
2136                                                         event.deathscreen.set_camera_point_target;
2137                                         v3f camera_point_target;
2138                                         camera_point_target.X = event.deathscreen.camera_point_target_x;
2139                                         camera_point_target.Y = event.deathscreen.camera_point_target_y;
2140                                         camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2141                                         MainRespawnInitiator *respawner =
2142                                                         new MainRespawnInitiator(
2143                                                                         &respawn_menu_active, &client);
2144                                         GUIDeathScreen *menu =
2145                                                         new GUIDeathScreen(guienv, guiroot, -1, 
2146                                                                 &g_menumgr, respawner);
2147                                         menu->drop();
2148                                         
2149                                         chat_backend.addMessage(L"", L"You died.");
2150
2151                                         /* Handle visualization */
2152
2153                                         damage_flash = 0;
2154
2155                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2156                                         player->hurt_tilt_timer = 0;
2157                                         player->hurt_tilt_strength = 0;
2158
2159                                         /*LocalPlayer* player = client.getLocalPlayer();
2160                                         player->setPosition(player->getPosition() + v3f(0,-BS,0));
2161                                         camera.update(player, busytime, screensize);*/
2162                                 }
2163                                 else if (event.type == CE_SHOW_FORMSPEC)
2164                                 {
2165                                         if (current_formspec == 0)
2166                                         {
2167                                                 /* Create menu */
2168                                                 current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),&current_formspec);
2169
2170                                                 GUIFormSpecMenu *menu =
2171                                                                 new GUIFormSpecMenu(device, guiroot, -1,
2172                                                                                 &g_menumgr,
2173                                                                                 &client, gamedef);
2174                                                 menu->setFormSource(current_formspec);
2175                                                 menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
2176                                                 menu->drop();
2177                                         }
2178                                         else
2179                                         {
2180                                                 /* update menu */
2181                                                 current_formspec->setForm(*(event.show_formspec.formspec));
2182                                         }
2183                                         delete(event.show_formspec.formspec);
2184                                         delete(event.show_formspec.formname);
2185                                 }
2186                                 else if(event.type == CE_TEXTURES_UPDATED)
2187                                 {
2188                                         update_wielded_item_trigger = true;
2189                                 }
2190                                 else if(event.type == CE_SPAWN_PARTICLE)
2191                                 {
2192                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2193                                         AtlasPointer ap =
2194                                                 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2195
2196                                         new Particle(gamedef, smgr, player, client.getEnv(),
2197                                                 *event.spawn_particle.pos,
2198                                                 *event.spawn_particle.vel,
2199                                                 *event.spawn_particle.acc,
2200                                                  event.spawn_particle.expirationtime,
2201                                                  event.spawn_particle.size,
2202                                                  event.spawn_particle.collisiondetection, ap);
2203                                 }
2204                                 else if(event.type == CE_ADD_PARTICLESPAWNER)
2205                                 {
2206                                         LocalPlayer* player = client.getEnv().getLocalPlayer();
2207                                         AtlasPointer ap =
2208                                                 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2209
2210                                         new ParticleSpawner(gamedef, smgr, player,
2211                                                  event.add_particlespawner.amount,
2212                                                  event.add_particlespawner.spawntime,
2213                                                 *event.add_particlespawner.minpos,
2214                                                 *event.add_particlespawner.maxpos,
2215                                                 *event.add_particlespawner.minvel,
2216                                                 *event.add_particlespawner.maxvel,
2217                                                 *event.add_particlespawner.minacc,
2218                                                 *event.add_particlespawner.maxacc,
2219                                                  event.add_particlespawner.minexptime,
2220                                                  event.add_particlespawner.maxexptime,
2221                                                  event.add_particlespawner.minsize,
2222                                                  event.add_particlespawner.maxsize,
2223                                                  event.add_particlespawner.collisiondetection,
2224                                                  ap,
2225                                                  event.add_particlespawner.id);
2226                                 }
2227                                 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2228                                 {
2229                                         delete_particlespawner (event.delete_particlespawner.id);
2230                                 }
2231                         }
2232                 }
2233                 
2234                 //TimeTaker //timer2("//timer2");
2235
2236                 /*
2237                         For interaction purposes, get info about the held item
2238                         - What item is it?
2239                         - Is it a usable item?
2240                         - Can it point to liquids?
2241                 */
2242                 ItemStack playeritem;
2243                 bool playeritem_usable = false;
2244                 bool playeritem_liquids_pointable = false;
2245                 {
2246                         InventoryList *mlist = local_inventory.getList("main");
2247                         if(mlist != NULL)
2248                         {
2249                                 playeritem = mlist->getItem(client.getPlayerItem());
2250                                 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2251                                 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2252                         }
2253                 }
2254                 ToolCapabilities playeritem_toolcap =
2255                                 playeritem.getToolCapabilities(itemdef);
2256                 
2257                 /*
2258                         Update camera
2259                 */
2260
2261                 LocalPlayer* player = client.getEnv().getLocalPlayer();
2262                 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2263                 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2264                 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2265                 camera.update(player, busytime, screensize, tool_reload_ratio);
2266                 camera.step(dtime);
2267
2268                 v3f player_position = player->getPosition();
2269                 v3f camera_position = camera.getPosition();
2270                 v3f camera_direction = camera.getDirection();
2271                 f32 camera_fov = camera.getFovMax();
2272                 
2273                 if(!disable_camera_update){
2274                         client.getEnv().getClientMap().updateCamera(camera_position,
2275                                 camera_direction, camera_fov);
2276                 }
2277                 
2278                 // Update sound listener
2279                 sound->updateListener(camera.getCameraNode()->getPosition(),
2280                                 v3f(0,0,0), // velocity
2281                                 camera.getDirection(),
2282                                 camera.getCameraNode()->getUpVector());
2283                 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2284
2285                 /*
2286                         Update sound maker
2287                 */
2288                 {
2289                         soundmaker.step(dtime);
2290                         
2291                         ClientMap &map = client.getEnv().getClientMap();
2292                         MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2293                         soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2294                 }
2295
2296                 /*
2297                         Calculate what block is the crosshair pointing to
2298                 */
2299                 
2300                 //u32 t1 = device->getTimer()->getRealTime();
2301                 
2302                 f32 d = 4; // max. distance
2303                 core::line3d<f32> shootline(camera_position,
2304                                 camera_position + camera_direction * BS * (d+1));
2305
2306                 ClientActiveObject *selected_object = NULL;
2307
2308                 PointedThing pointed = getPointedThing(
2309                                 // input
2310                                 &client, player_position, camera_direction,
2311                                 camera_position, shootline, d,
2312                                 playeritem_liquids_pointable, !ldown_for_dig,
2313                                 // output
2314                                 hilightboxes,
2315                                 selected_object);
2316
2317                 if(pointed != pointed_old)
2318                 {
2319                         infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2320                         //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2321                 }
2322
2323                 /*
2324                         Stop digging when
2325                         - releasing left mouse button
2326                         - pointing away from node
2327                 */
2328                 if(digging)
2329                 {
2330                         if(input->getLeftReleased())
2331                         {
2332                                 infostream<<"Left button released"
2333                                         <<" (stopped digging)"<<std::endl;
2334                                 digging = false;
2335                         }
2336                         else if(pointed != pointed_old)
2337                         {
2338                                 if (pointed.type == POINTEDTHING_NODE
2339                                         && pointed_old.type == POINTEDTHING_NODE
2340                                         && pointed.node_undersurface == pointed_old.node_undersurface)
2341                                 {
2342                                         // Still pointing to the same node,
2343                                         // but a different face. Don't reset.
2344                                 }
2345                                 else
2346                                 {
2347                                         infostream<<"Pointing away from node"
2348                                                 <<" (stopped digging)"<<std::endl;
2349                                         digging = false;
2350                                 }
2351                         }
2352                         if(!digging)
2353                         {
2354                                 client.interact(1, pointed_old);
2355                                 client.setCrack(-1, v3s16(0,0,0));
2356                                 dig_time = 0.0;
2357                         }
2358                 }
2359                 if(!digging && ldown_for_dig && !input->getLeftState())
2360                 {
2361                         ldown_for_dig = false;
2362                 }
2363
2364                 bool left_punch = false;
2365                 soundmaker.m_player_leftpunch_sound.name = "";
2366
2367                 if(input->getRightState())
2368                         repeat_rightclick_timer += dtime;
2369                 else
2370                         repeat_rightclick_timer = 0;
2371
2372                 if(playeritem_usable && input->getLeftState())
2373                 {
2374                         if(input->getLeftClicked())
2375                                 client.interact(4, pointed);
2376                 }
2377                 else if(pointed.type == POINTEDTHING_NODE)
2378                 {
2379                         v3s16 nodepos = pointed.node_undersurface;
2380                         v3s16 neighbourpos = pointed.node_abovesurface;
2381
2382                         /*
2383                                 Check information text of node
2384                         */
2385                         
2386                         ClientMap &map = client.getEnv().getClientMap();
2387                         NodeMetadata *meta = map.getNodeMetadata(nodepos);
2388                         if(meta){
2389                                 infotext = narrow_to_wide(meta->getString("infotext"));
2390                         } else {
2391                                 MapNode n = map.getNode(nodepos);
2392                                 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2393                                         infotext = L"Unknown node: ";
2394                                         infotext += narrow_to_wide(nodedef->get(n).name);
2395                                 }
2396                         }
2397                         
2398                         /*
2399                                 Handle digging
2400                         */
2401                         
2402                         if(nodig_delay_timer <= 0.0 && input->getLeftState())
2403                         {
2404                                 if(!digging)
2405                                 {
2406                                         infostream<<"Started digging"<<std::endl;
2407                                         client.interact(0, pointed);
2408                                         digging = true;
2409                                         ldown_for_dig = true;
2410                                 }
2411                                 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2412                                 
2413                                 // NOTE: Similar piece of code exists on the server side for
2414                                 // cheat detection.
2415                                 // Get digging parameters
2416                                 DigParams params = getDigParams(nodedef->get(n).groups,
2417                                                 &playeritem_toolcap);
2418                                 // If can't dig, try hand
2419                                 if(!params.diggable){
2420                                         const ItemDefinition &hand = itemdef->get("");
2421                                         const ToolCapabilities *tp = hand.tool_capabilities;
2422                                         if(tp)
2423                                                 params = getDigParams(nodedef->get(n).groups, tp);
2424                                 }
2425                                 
2426                                 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2427                                 if(sound_dig.exists()){
2428                                         if(sound_dig.name == "__group"){
2429                                                 if(params.main_group != ""){
2430                                                         soundmaker.m_player_leftpunch_sound.gain = 0.5;
2431                                                         soundmaker.m_player_leftpunch_sound.name =
2432                                                                         std::string("default_dig_") +
2433                                                                                         params.main_group;
2434                                                 }
2435                                         } else{
2436                                                 soundmaker.m_player_leftpunch_sound = sound_dig;
2437                                         }
2438                                 }
2439
2440                                 float dig_time_complete = 0.0;
2441
2442                                 if(params.diggable == false)
2443                                 {
2444                                         // I guess nobody will wait for this long
2445                                         dig_time_complete = 10000000.0;
2446                                 }
2447                                 else
2448                                 {
2449                                         dig_time_complete = params.time;
2450                                         if (g_settings->getBool("enable_particles"))
2451                                         {
2452                                                 const ContentFeatures &features =
2453                                                         client.getNodeDefManager()->get(n);
2454                                                 addPunchingParticles
2455                                                         (gamedef, smgr, player, client.getEnv(),
2456                                                          nodepos, features.tiles);
2457                                         }
2458                                 }
2459
2460                                 if(dig_time_complete >= 0.001)
2461                                 {
2462                                         dig_index = (u16)((float)crack_animation_length
2463                                                         * dig_time/dig_time_complete);
2464                                 }
2465                                 // This is for torches
2466                                 else
2467                                 {
2468                                         dig_index = crack_animation_length;
2469                                 }
2470
2471                                 // Don't show cracks if not diggable
2472                                 if(dig_time_complete >= 100000.0)
2473                                 {
2474                                 }
2475                                 else if(dig_index < crack_animation_length)
2476                                 {
2477                                         //TimeTaker timer("client.setTempMod");
2478                                         //infostream<<"dig_index="<<dig_index<<std::endl;
2479                                         client.setCrack(dig_index, nodepos);
2480                                 }
2481                                 else
2482                                 {
2483                                         infostream<<"Digging completed"<<std::endl;
2484                                         client.interact(2, pointed);
2485                                         client.setCrack(-1, v3s16(0,0,0));
2486                                         MapNode wasnode = map.getNode(nodepos);
2487                                         client.removeNode(nodepos);
2488
2489                                         if (g_settings->getBool("enable_particles"))
2490                                         {
2491                                                 const ContentFeatures &features =
2492                                                         client.getNodeDefManager()->get(wasnode);
2493                                                 addDiggingParticles
2494                                                         (gamedef, smgr, player, client.getEnv(),
2495                                                          nodepos, features.tiles);
2496                                         }
2497
2498                                         dig_time = 0;
2499                                         digging = false;
2500
2501                                         nodig_delay_timer = dig_time_complete
2502                                                         / (float)crack_animation_length;
2503
2504                                         // We don't want a corresponding delay to
2505                                         // very time consuming nodes
2506                                         if(nodig_delay_timer > 0.3)
2507                                                 nodig_delay_timer = 0.3;
2508                                         // We want a slight delay to very little
2509                                         // time consuming nodes
2510                                         float mindelay = 0.15;
2511                                         if(nodig_delay_timer < mindelay)
2512                                                 nodig_delay_timer = mindelay;
2513                                         
2514                                         // Send event to trigger sound
2515                                         MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2516                                         gamedef->event()->put(e);
2517                                 }
2518
2519                                 dig_time += dtime;
2520
2521                                 camera.setDigging(0);  // left click animation
2522                         }
2523
2524                         if(input->getRightClicked() ||
2525                                         repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
2526                         {
2527                                 repeat_rightclick_timer = 0;
2528                                 infostream<<"Ground right-clicked"<<std::endl;
2529                                 
2530                                 // Sign special case, at least until formspec is properly implemented.
2531                                 // Deprecated?
2532                                 if(meta && meta->getString("formspec") == "hack:sign_text_input" 
2533                                                 && !random_input
2534                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2535                                 {
2536                                         infostream<<"Launching metadata text input"<<std::endl;
2537                                         
2538                                         // Get a new text for it
2539
2540                                         TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2541
2542                                         std::wstring wtext = narrow_to_wide(meta->getString("text"));
2543
2544                                         (new GUITextInputMenu(guienv, guiroot, -1,
2545                                                         &g_menumgr, dest,
2546                                                         wtext))->drop();
2547                                 }
2548                                 // If metadata provides an inventory view, activate it
2549                                 else if(meta && meta->getString("formspec") != "" && !random_input
2550                                                 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2551                                 {
2552                                         infostream<<"Launching custom inventory view"<<std::endl;
2553
2554                                         InventoryLocation inventoryloc;
2555                                         inventoryloc.setNodeMeta(nodepos);
2556                                         
2557                                         /* Create menu */
2558
2559                                         GUIFormSpecMenu *menu =
2560                                                 new GUIFormSpecMenu(device, guiroot, -1,
2561                                                         &g_menumgr,
2562                                                         &client, gamedef);
2563                                         menu->setFormSpec(meta->getString("formspec"),
2564                                                         inventoryloc);
2565                                         menu->setFormSource(new NodeMetadataFormSource(
2566                                                         &client.getEnv().getClientMap(), nodepos));
2567                                         menu->setTextDest(new TextDestNodeMetadata(nodepos, &client));
2568                                         menu->drop();
2569                                 }
2570                                 // Otherwise report right click to server
2571                                 else
2572                                 {
2573                                         // Report to server
2574                                         client.interact(3, pointed);
2575                                         camera.setDigging(1);  // right click animation
2576                                         
2577                                         // If the wielded item has node placement prediction,
2578                                         // make that happen
2579                                         const ItemDefinition &def =
2580                                                         playeritem.getDefinition(itemdef);
2581                                         if(def.node_placement_prediction != ""
2582                                                         && !nodedef->get(map.getNode(nodepos)).rightclickable)
2583                                         do{ // breakable
2584                                                 verbosestream<<"Node placement prediction for "
2585                                                                 <<playeritem.name<<" is "
2586                                                                 <<def.node_placement_prediction<<std::endl;
2587                                                 v3s16 p = neighbourpos;
2588                                                 // Place inside node itself if buildable_to
2589                                                 try{
2590                                                         MapNode n_under = map.getNode(nodepos);
2591                                                         if(nodedef->get(n_under).buildable_to)
2592                                                                 p = nodepos;
2593                                                 }catch(InvalidPositionException &e){}
2594                                                 // Find id of predicted node
2595                                                 content_t id;
2596                                                 bool found =
2597                                                         nodedef->getId(def.node_placement_prediction, id);
2598                                                 if(!found){
2599                                                         errorstream<<"Node placement prediction failed for "
2600                                                                         <<playeritem.name<<" (places "
2601                                                                         <<def.node_placement_prediction
2602                                                                         <<") - Name not known"<<std::endl;
2603                                                         break;
2604                                                 }
2605                                                 MapNode n(id);
2606                                                 try{
2607                                                         // This triggers the required mesh update too
2608                                                         client.addNode(p, n);
2609                                                 }catch(InvalidPositionException &e){
2610                                                         errorstream<<"Node placement prediction failed for "
2611                                                                         <<playeritem.name<<" (places "
2612                                                                         <<def.node_placement_prediction
2613                                                                         <<") - Position not loaded"<<std::endl;
2614                                                 }
2615                                         }while(0);
2616                                         
2617                                         // Read the sound
2618                                         soundmaker.m_player_rightpunch_sound = def.sound_place;
2619                                 }
2620                         }
2621                 }
2622                 else if(pointed.type == POINTEDTHING_OBJECT)
2623                 {
2624                         infotext = narrow_to_wide(selected_object->infoText());
2625
2626                         if(infotext == L"" && show_debug){
2627                                 infotext = narrow_to_wide(selected_object->debugInfoText());
2628                         }
2629
2630                         //if(input->getLeftClicked())
2631                         if(input->getLeftState())
2632                         {
2633                                 bool do_punch = false;
2634                                 bool do_punch_damage = false;
2635                                 if(object_hit_delay_timer <= 0.0){
2636                                         do_punch = true;
2637                                         do_punch_damage = true;
2638                                         object_hit_delay_timer = object_hit_delay;
2639                                 }
2640                                 if(input->getLeftClicked()){
2641                                         do_punch = true;
2642                                 }
2643                                 if(do_punch){
2644                                         infostream<<"Left-clicked object"<<std::endl;
2645                                         left_punch = true;
2646                                 }
2647                                 if(do_punch_damage){
2648                                         // Report direct punch
2649                                         v3f objpos = selected_object->getPosition();
2650                                         v3f dir = (objpos - player_position).normalize();
2651                                         
2652                                         bool disable_send = selected_object->directReportPunch(
2653                                                         dir, &playeritem, time_from_last_punch);
2654                                         time_from_last_punch = 0;
2655                                         if(!disable_send)
2656                                                 client.interact(0, pointed);
2657                                 }
2658                         }
2659                         else if(input->getRightClicked())
2660                         {
2661                                 infostream<<"Right-clicked object"<<std::endl;
2662                                 client.interact(3, pointed);  // place
2663                         }
2664                 }
2665                 else if(input->getLeftState())
2666                 {
2667                         // When button is held down in air, show continuous animation
2668                         left_punch = true;
2669                 }
2670
2671                 pointed_old = pointed;
2672                 
2673                 if(left_punch || input->getLeftClicked())
2674                 {
2675                         camera.setDigging(0); // left click animation
2676                 }
2677
2678                 input->resetLeftClicked();
2679                 input->resetRightClicked();
2680
2681                 input->resetLeftReleased();
2682                 input->resetRightReleased();
2683                 
2684                 /*
2685                         Calculate stuff for drawing
2686                 */
2687
2688                 /*
2689                         Fog range
2690                 */
2691         
2692                 if(farmesh)
2693                 {
2694                         fog_range = BS*farmesh_range;
2695                 }
2696                 else
2697                 {
2698                         fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2699                         fog_range *= 0.9;
2700                         if(draw_control.range_all)
2701                                 fog_range = 100000*BS;
2702                 }
2703
2704                 /*
2705                         Calculate general brightness
2706                 */
2707                 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2708                 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
2709                 float direct_brightness = 0;
2710                 bool sunlight_seen = false;
2711                 if(g_settings->getBool("free_move")){
2712                         direct_brightness = time_brightness;
2713                         sunlight_seen = true;
2714                 } else {
2715                         ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2716                         float old_brightness = sky->getBrightness();
2717                         direct_brightness = (float)client.getEnv().getClientMap()
2718                                         .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2719                                         daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2720                                         / 255.0;
2721                 }
2722                 
2723                 time_of_day = client.getEnv().getTimeOfDayF();
2724                 float maxsm = 0.05;
2725                 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2726                                 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2727                                 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2728                         time_of_day_smooth = time_of_day;
2729                 float todsm = 0.05;
2730                 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2731                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2732                                         + (time_of_day+1.0) * todsm;
2733                 else
2734                         time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2735                                         + time_of_day * todsm;
2736                         
2737                 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2738                                 sunlight_seen);
2739                 
2740                 float brightness = sky->getBrightness();
2741                 video::SColor bgcolor = sky->getBgColor();
2742                 video::SColor skycolor = sky->getSkyColor();
2743
2744                 /*
2745                         Update clouds
2746                 */
2747                 if(clouds){
2748                         if(sky->getCloudsVisible()){
2749                                 clouds->setVisible(true);
2750                                 clouds->step(dtime);
2751                                 clouds->update(v2f(player_position.X, player_position.Z),
2752                                                 sky->getCloudColor());
2753                         } else{
2754                                 clouds->setVisible(false);
2755                         }
2756                 }
2757                 
2758                 /*
2759                         Update farmesh
2760                 */
2761                 if(farmesh)
2762                 {
2763                         farmesh_range = draw_control.wanted_range * 10;
2764                         if(draw_control.range_all && farmesh_range < 500)
2765                                 farmesh_range = 500;
2766                         if(farmesh_range > 1000)
2767                                 farmesh_range = 1000;
2768
2769                         farmesh->step(dtime);
2770                         farmesh->update(v2f(player_position.X, player_position.Z),
2771                                         brightness, farmesh_range);
2772                 }
2773
2774                 /*
2775                         Update particles
2776                 */
2777
2778                 allparticles_step(dtime, client.getEnv());
2779                 allparticlespawners_step(dtime, client.getEnv());
2780                 
2781                 /*
2782                         Fog
2783                 */
2784                 
2785                 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2786                 {
2787                         driver->setFog(
2788                                 bgcolor,
2789                                 video::EFT_FOG_LINEAR,
2790                                 fog_range*0.4,
2791                                 fog_range*1.0,
2792                                 0.01,
2793                                 false, // pixel fog
2794                                 false // range fog
2795                         );
2796                 }
2797                 else
2798                 {
2799                         driver->setFog(
2800                                 bgcolor,
2801                                 video::EFT_FOG_LINEAR,
2802                                 100000*BS,
2803                                 110000*BS,
2804                                 0.01,
2805                                 false, // pixel fog
2806                                 false // range fog
2807                         );
2808                 }
2809
2810                 /*
2811                         Update gui stuff (0ms)
2812                 */
2813
2814                 //TimeTaker guiupdatetimer("Gui updating");
2815                 
2816                 const char program_name_and_version[] =
2817                         "Minetest " VERSION_STRING;
2818
2819                 if(show_debug)
2820                 {
2821                         static float drawtime_avg = 0;
2822                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2823                         /*static float beginscenetime_avg = 0;
2824                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2825                         static float scenetime_avg = 0;
2826                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2827                         static float endscenetime_avg = 0;
2828                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2829                         
2830                         char temptext[300];
2831                         snprintf(temptext, 300, "%s ("
2832                                         "R: range_all=%i"
2833                                         ")"
2834                                         " drawtime=%.0f, dtime_jitter = % .1f %%"
2835                                         ", v_range = %.1f, RTT = %.3f",
2836                                         program_name_and_version,
2837                                         draw_control.range_all,
2838                                         drawtime_avg,
2839                                         dtime_jitter1_max_fraction * 100.0,
2840                                         draw_control.wanted_range,
2841                                         client.getRTT()
2842                                         );
2843                         
2844                         guitext->setText(narrow_to_wide(temptext).c_str());
2845                         guitext->setVisible(true);
2846                 }
2847                 else if(show_hud || show_chat)
2848                 {
2849                         guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2850                         guitext->setVisible(true);
2851                 }
2852                 else
2853                 {
2854                         guitext->setVisible(false);
2855                 }
2856                 
2857                 if(show_debug)
2858                 {
2859                         char temptext[300];
2860                         snprintf(temptext, 300,
2861                                         "(% .1f, % .1f, % .1f)"
2862                                         " (yaw = %.1f) (seed = %llu)",
2863                                         player_position.X/BS,
2864                                         player_position.Y/BS,
2865                                         player_position.Z/BS,
2866                                         wrapDegrees_0_360(camera_yaw),
2867                                         (unsigned long long)client.getMapSeed());
2868
2869                         guitext2->setText(narrow_to_wide(temptext).c_str());
2870                         guitext2->setVisible(true);
2871                 }
2872                 else
2873                 {
2874                         guitext2->setVisible(false);
2875                 }
2876                 
2877                 {
2878                         guitext_info->setText(infotext.c_str());
2879                         guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2880                 }
2881
2882                 {
2883                         float statustext_time_max = 1.5;
2884                         if(!statustext.empty())
2885                         {
2886                                 statustext_time += dtime;
2887                                 if(statustext_time >= statustext_time_max)
2888                                 {
2889                                         statustext = L"";
2890                                         statustext_time = 0;
2891                                 }
2892                         }
2893                         guitext_status->setText(statustext.c_str());
2894                         guitext_status->setVisible(!statustext.empty());
2895
2896                         if(!statustext.empty())
2897                         {
2898                                 s32 status_y = screensize.Y - 130;
2899                                 core::rect<s32> rect(
2900                                                 10,
2901                                                 status_y - guitext_status->getTextHeight(),
2902                                                 screensize.X - 10,
2903                                                 status_y
2904                                 );
2905                                 guitext_status->setRelativePosition(rect);
2906
2907                                 // Fade out
2908                                 video::SColor initial_color(255,0,0,0);
2909                                 if(guienv->getSkin())
2910                                         initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2911                                 video::SColor final_color = initial_color;
2912                                 final_color.setAlpha(0);
2913                                 video::SColor fade_color =
2914                                         initial_color.getInterpolated_quadratic(
2915                                                 initial_color,
2916                                                 final_color,
2917                                                 pow(statustext_time / (float)statustext_time_max, 2.0f));
2918                                 guitext_status->setOverrideColor(fade_color);
2919                                 guitext_status->enableOverrideColor(true);
2920                         }
2921                 }
2922                 
2923                 /*
2924                         Get chat messages from client
2925                 */
2926                 {
2927                         // Get new messages from error log buffer
2928                         while(!chat_log_error_buf.empty())
2929                         {
2930                                 chat_backend.addMessage(L"", narrow_to_wide(
2931                                                 chat_log_error_buf.get()));
2932                         }
2933                         // Get new messages from client
2934                         std::wstring message;
2935                         while(client.getChatMessage(message))
2936                         {
2937                                 chat_backend.addUnparsedMessage(message);
2938                         }
2939                         // Remove old messages
2940                         chat_backend.step(dtime);
2941
2942                         // Display all messages in a static text element
2943                         u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2944                         std::wstring recent_chat = chat_backend.getRecentChat();
2945                         guitext_chat->setText(recent_chat.c_str());
2946
2947                         // Update gui element size and position
2948                         s32 chat_y = 5+(text_height+5);
2949                         if(show_debug)
2950                                 chat_y += (text_height+5);
2951                         core::rect<s32> rect(
2952                                 10,
2953                                 chat_y,
2954                                 screensize.X - 10,
2955                                 chat_y + guitext_chat->getTextHeight()
2956                         );
2957                         guitext_chat->setRelativePosition(rect);
2958
2959                         // Don't show chat if disabled or empty or profiler is enabled
2960                         guitext_chat->setVisible(show_chat && recent_chat_count != 0
2961                                         && !show_profiler);
2962                 }
2963
2964                 /*
2965                         Inventory
2966                 */
2967                 
2968                 if(client.getPlayerItem() != new_playeritem)
2969                 {
2970                         client.selectPlayerItem(new_playeritem);
2971                 }
2972                 if(client.getLocalInventoryUpdated())
2973                 {
2974                         //infostream<<"Updating local inventory"<<std::endl;
2975                         client.getLocalInventory(local_inventory);
2976                         
2977                         update_wielded_item_trigger = true;
2978                 }
2979                 if(update_wielded_item_trigger)
2980                 {
2981                         update_wielded_item_trigger = false;
2982                         // Update wielded tool
2983                         InventoryList *mlist = local_inventory.getList("main");
2984                         ItemStack item;
2985                         if(mlist != NULL)
2986                                 item = mlist->getItem(client.getPlayerItem());
2987                         camera.wield(item);
2988                 }
2989
2990                 /*
2991                         Update block draw list every 200ms or when camera direction has
2992                         changed much
2993                 */
2994                 update_draw_list_timer += dtime;
2995                 if(update_draw_list_timer >= 0.2 ||
2996                                 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2){
2997                         update_draw_list_timer = 0;
2998                         client.getEnv().getClientMap().updateDrawList(driver);
2999                         update_draw_list_last_cam_dir = camera_direction;
3000                 }
3001
3002                 /*
3003                         Drawing begins
3004                 */
3005
3006                 TimeTaker tt_draw("mainloop: draw");
3007
3008                 
3009                 {
3010                         TimeTaker timer("beginScene");
3011                         //driver->beginScene(false, true, bgcolor);
3012                         //driver->beginScene(true, true, bgcolor);
3013                         driver->beginScene(true, true, skycolor);
3014                         beginscenetime = timer.stop(true);
3015                 }
3016                 
3017                 //timer3.stop();
3018         
3019                 //infostream<<"smgr->drawAll()"<<std::endl;
3020                 {
3021                         TimeTaker timer("smgr");
3022                         smgr->drawAll();
3023                         
3024                         if(g_settings->getBool("anaglyph"))
3025                         {
3026                                 irr::core::vector3df oldPosition = camera.getCameraNode()->getPosition();
3027                                 irr::core::vector3df oldTarget   = camera.getCameraNode()->getTarget();
3028
3029                                 irr::core::matrix4 startMatrix   = camera.getCameraNode()->getAbsoluteTransformation();
3030
3031                                 irr::core::vector3df focusPoint  = (camera.getCameraNode()->getTarget() -
3032                                                                                  camera.getCameraNode()->getAbsolutePosition()).setLength(1) +
3033                                                                                  camera.getCameraNode()->getAbsolutePosition() ;
3034
3035                                 //Left eye...
3036                                 irr::core::vector3df leftEye;
3037                                 irr::core::matrix4   leftMove;
3038
3039                                 leftMove.setTranslation( irr::core::vector3df(-g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3040                                 leftEye=(startMatrix*leftMove).getTranslation();
3041
3042                                 //clear the depth buffer, and color
3043                                 driver->beginScene( true, true, irr::video::SColor(0,200,200,255) );
3044
3045                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
3046                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3047                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + 
3048                                                                                                                          irr::scene::ESNRP_SOLID +
3049                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3050                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3051                                                                                                                          irr::scene::ESNRP_SHADOW;
3052
3053                                 camera.getCameraNode()->setPosition( leftEye );
3054                                 camera.getCameraNode()->setTarget( focusPoint );
3055
3056                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3057
3058
3059                                 //Right eye...
3060                                 irr::core::vector3df rightEye;
3061                                 irr::core::matrix4   rightMove;
3062
3063                                 rightMove.setTranslation( irr::core::vector3df(g_settings->getFloat("anaglyph_strength"),0.0f,0.0f) );
3064                                 rightEye=(startMatrix*rightMove).getTranslation();
3065
3066                                 //clear the depth buffer
3067                                 driver->clearZBuffer();
3068
3069                                 driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_GREEN + irr::video::ECP_BLUE;
3070                                 driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
3071                                 driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
3072                                                                                                                          irr::scene::ESNRP_SOLID +
3073                                                                                                                          irr::scene::ESNRP_TRANSPARENT +
3074                                                                                                                          irr::scene::ESNRP_TRANSPARENT_EFFECT +
3075                                                                                                                          irr::scene::ESNRP_SHADOW;
3076
3077                                 camera.getCameraNode()->setPosition( rightEye );
3078                                 camera.getCameraNode()->setTarget( focusPoint );
3079
3080                                 smgr->drawAll(); // 'smgr->drawAll();' may go here
3081
3082
3083                                 //driver->endScene();
3084
3085                                 driver->getOverrideMaterial().Material.ColorMask=irr::video::ECP_ALL;
3086                                 driver->getOverrideMaterial().EnableFlags=0;
3087                                 driver->getOverrideMaterial().EnablePasses=0;
3088
3089                                 camera.getCameraNode()->setPosition( oldPosition );
3090                                 camera.getCameraNode()->setTarget( oldTarget );
3091                         }
3092
3093                         scenetime = timer.stop(true);
3094                 }
3095                 
3096                 {
3097                 //TimeTaker timer9("auxiliary drawings");
3098                 // 0ms
3099                 
3100                 //timer9.stop();
3101                 //TimeTaker //timer10("//timer10");
3102                 
3103                 video::SMaterial m;
3104                 //m.Thickness = 10;
3105                 m.Thickness = 3;
3106                 m.Lighting = false;
3107                 driver->setMaterial(m);
3108
3109                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
3110
3111                 if(show_hud)
3112                 {
3113                         v3f selectionbox_color = g_settings->getV3F("selectionbox_color");
3114                         u32 selectionbox_color_r = rangelim(myround(selectionbox_color.X), 0, 255);
3115                         u32 selectionbox_color_g = rangelim(myround(selectionbox_color.Y), 0, 255);
3116                         u32 selectionbox_color_b = rangelim(myround(selectionbox_color.Z), 0, 255);
3117
3118                         for(std::vector<aabb3f>::const_iterator
3119                                         i = hilightboxes.begin();
3120                                         i != hilightboxes.end(); i++)
3121                         {
3122                                 /*infostream<<"hilightbox min="
3123                                                 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
3124                                                 <<" max="
3125                                                 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
3126                                                 <<std::endl;*/
3127                                 driver->draw3DBox(*i, video::SColor(255,selectionbox_color_r,selectionbox_color_g,selectionbox_color_b));
3128                         }
3129                 }
3130
3131                 /*
3132                         Wielded tool
3133                 */
3134                 if(show_hud)
3135                 {
3136                         // Warning: This clears the Z buffer.
3137                         camera.drawWieldedTool();
3138                 }
3139
3140                 /*
3141                         Post effects
3142                 */
3143                 {
3144                         client.getEnv().getClientMap().renderPostFx();
3145                 }
3146
3147                 /*
3148                         Profiler graph
3149                 */
3150                 if(show_profiler_graph)
3151                 {
3152                         graph.draw(10, screensize.Y - 10, driver, font);
3153                 }
3154
3155                 /*
3156                         Draw crosshair
3157                 */
3158                 if(show_hud)
3159                 {
3160                         v3f crosshair_color = g_settings->getV3F("crosshair_color");
3161                         u32 crosshair_color_r = rangelim(myround(crosshair_color.X), 0, 255);
3162                         u32 crosshair_color_g = rangelim(myround(crosshair_color.Y), 0, 255);
3163                         u32 crosshair_color_b = rangelim(myround(crosshair_color.Z), 0, 255);
3164                         u32 crosshair_alpha = rangelim(g_settings->getS32("crosshair_alpha"), 0, 255);
3165
3166                         driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
3167                                         displaycenter + core::vector2d<s32>(10,0),
3168                                         video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3169                         driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
3170                                         displaycenter + core::vector2d<s32>(0,10),
3171                                         video::SColor(crosshair_alpha,crosshair_color_r,crosshair_color_g,crosshair_color_b));
3172                 }
3173
3174                 } // timer
3175
3176                 //timer10.stop();
3177                 //TimeTaker //timer11("//timer11");
3178
3179
3180                 /*
3181                         Draw hotbar
3182                 */
3183                 if(show_hud)
3184                 {
3185                         draw_hotbar(driver, font, gamedef,
3186                                         v2s32(displaycenter.X, screensize.Y),
3187                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
3188                                         client.getHP(), client.getPlayerItem());
3189                 }
3190
3191                 /*
3192                         Damage flash
3193                 */
3194                 if(damage_flash > 0.0)
3195                 {
3196                         video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3197                         driver->draw2DRectangle(color,
3198                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
3199                                         NULL);
3200                         
3201                         damage_flash -= 100.0*dtime;
3202                 }
3203
3204                 /*
3205                         Damage camera tilt
3206                 */
3207                 if(player->hurt_tilt_timer > 0.0)
3208                 {
3209                         player->hurt_tilt_timer -= dtime*5;
3210                         if(player->hurt_tilt_timer < 0)
3211                                 player->hurt_tilt_strength = 0;
3212                 }
3213
3214                 /*
3215                         Draw gui
3216                 */
3217                 // 0-1ms
3218                 guienv->drawAll();
3219
3220                 /*
3221                         End scene
3222                 */
3223                 {
3224                         TimeTaker timer("endScene");
3225                         endSceneX(driver);
3226                         endscenetime = timer.stop(true);
3227                 }
3228
3229                 drawtime = tt_draw.stop(true);
3230                 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3231
3232                 /*
3233                         End of drawing
3234                 */
3235
3236                 static s16 lastFPS = 0;
3237                 //u16 fps = driver->getFPS();
3238                 u16 fps = (1.0/dtime_avg1);
3239
3240                 if (lastFPS != fps)
3241                 {
3242                         core::stringw str = L"Minetest [";
3243                         str += driver->getName();
3244                         str += "] FPS=";
3245                         str += fps;
3246
3247                         device->setWindowCaption(str.c_str());
3248                         lastFPS = fps;
3249                 }
3250
3251                 /*
3252                         Log times and stuff for visualization
3253                 */
3254                 Profiler::GraphValues values;
3255                 g_profiler->graphGet(values);
3256                 graph.put(values);
3257         }
3258
3259         /*
3260                 Drop stuff
3261         */
3262         if(clouds)
3263                 clouds->drop();
3264         if(gui_chat_console)
3265                 gui_chat_console->drop();
3266         clear_particles ();
3267         
3268         /*
3269                 Draw a "shutting down" screen, which will be shown while the map
3270                 generator and other stuff quits
3271         */
3272         {
3273                 /*gui::IGUIStaticText *gui_shuttingdowntext = */
3274                 draw_load_screen(L"Shutting down stuff...", driver, font);
3275                 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
3276                 guienv->drawAll();
3277                 driver->endScene();
3278                 gui_shuttingdowntext->remove();*/
3279         }
3280
3281         chat_backend.addMessage(L"", L"# Disconnected.");
3282         chat_backend.addMessage(L"", L"");
3283
3284         // Client scope (client is destructed before destructing *def and tsrc)
3285         }while(0);
3286         } // try-catch
3287         catch(SerializationError &e)
3288         {
3289                 error_message = L"A serialization error occurred:\n"
3290                                 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3291                                 L" running a different version of Minetest.";
3292                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3293         }
3294         catch(ServerError &e)
3295         {
3296                 error_message = narrow_to_wide(e.what());
3297                 errorstream<<wide_to_narrow(error_message)<<std::endl;
3298         }
3299         catch(ModError &e)
3300         {
3301                 errorstream<<e.what()<<std::endl;
3302                 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3303         }
3304
3305
3306         
3307         if(!sound_is_dummy)
3308                 delete sound;
3309
3310         //has to be deleted first to stop all server threads
3311         delete server;
3312
3313         delete tsrc;
3314         delete shsrc;
3315         delete nodedef;
3316         delete itemdef;
3317 }
3318
3319