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