]> git.lizzy.rs Git - dragonfireclient.git/blobdiff - src/game.cpp
Revert "Fix settings to honor numeric conversion errors"
[dragonfireclient.git] / src / game.cpp
index 4f0d1b6630710fdd24e17872230cc7ca71df5851..56519d30aa9dbfa40593315c7e028c8fcd239477 100644 (file)
@@ -37,10 +37,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "tool.h"
 #include "guiChatConsole.h"
 #include "config.h"
+#include "version.h"
 #include "clouds.h"
 #include "particles.h"
 #include "camera.h"
-#include "farmesh.h"
 #include "mapblock.h"
 #include "settings.h"
 #include "profiler.h"
@@ -66,8 +66,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
        #include "sound_openal.h"
 #endif
 #include "event_manager.h"
+#include <iomanip>
 #include <list>
 #include "util/directiontables.h"
+#include "util/pointedthing.h"
 
 /*
        Text input system
@@ -134,6 +136,10 @@ struct TextDestPlayerInventory : public TextDest
                m_client->sendInventoryFields(m_formname, fields);
        }
 
+       void setFormName(std::string formname) {
+               m_formname = formname;
+       }
+
        Client *m_client;
        std::string m_formname;
 };
@@ -203,33 +209,6 @@ class PlayerInventoryFormSource: public IFormSource
        Client *m_client;
 };
 
-class FormspecFormSource: public IFormSource
-{
-public:
-       FormspecFormSource(std::string formspec,FormspecFormSource** game_formspec)
-       {
-               m_formspec = formspec;
-               m_game_formspec = game_formspec;
-       }
-
-       ~FormspecFormSource()
-       {
-               *m_game_formspec = 0;
-       }
-
-       void setForm(std::string formspec) {
-               m_formspec = formspec;
-       }
-
-       std::string getForm()
-       {
-               return m_formspec;
-       }
-
-       std::string m_formspec;
-       FormspecFormSource** m_game_formspec;
-};
-
 /*
        Check if a node is pointable
 */
@@ -260,6 +239,8 @@ PointedThing getPointedThing(Client *client, v3f player_position,
        INodeDefManager *nodedef = client->getNodeDefManager();
        ClientMap &map = client->getEnv().getClientMap();
 
+       f32 mindistance = BS * 1001;
+
        // First try to find a pointed at active object
        if(look_for_object)
        {
@@ -281,16 +262,15 @@ PointedThing getPointedThing(Client *client, v3f player_position,
                                                selection_box->MaxEdge + pos));
                        }
 
+                       mindistance = (selected_object->getPosition() - camera_position).getLength();
 
                        result.type = POINTEDTHING_OBJECT;
                        result.object_id = selected_object->getId();
-                       return result;
                }
        }
 
        // That didn't work, try to find a pointed at node
 
-       f32 mindistance = BS * 1001;
        
        v3s16 pos_i = floatToInt(player_position, BS);
 
@@ -724,6 +704,18 @@ class SoundMaker
                sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
        }
 
+       static void playerDamage(MtEvent *e, void *data)
+       {
+               SoundMaker *sm = (SoundMaker*)data;
+               sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
+       }
+
+       static void playerFallingDamage(MtEvent *e, void *data)
+       {
+               SoundMaker *sm = (SoundMaker*)data;
+               sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
+       }
+
        void registerReceiver(MtEventManager *mgr)
        {
                mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
@@ -732,6 +724,8 @@ class SoundMaker
                mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
                mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
                mgr->reg("NodeDug", SoundMaker::nodeDug, this);
+               mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
+               mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
        }
 
        void step(float dtime)
@@ -803,19 +797,41 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter
                services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
 
                // Fog distance
-               float fog_distance = *m_fog_range;
-               if(*m_force_fog_off)
-                       fog_distance = 10000*BS;
+               float fog_distance = 10000*BS;
+               if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
+                       fog_distance = *m_fog_range;
                services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
 
                // Day-night ratio
                u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
                float daynight_ratio_f = (float)daynight_ratio / 1000.0;
                services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
+               
+               u32 animation_timer = porting::getTimeMs() % 100000;
+               float animation_timer_f = (float)animation_timer / 100000.0;
+               services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
+               services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
+
+               LocalPlayer* player = m_client->getEnv().getLocalPlayer();
+               v3f eye_position = player->getEyePosition();
+               services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
+               services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
+
+               // Normal map texture layer
+               int layer1 = 1;
+               int layer2 = 2;
+               // before 1.8 there isn't a "integer interface", only float
+#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
+               services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
+               services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
+#else
+               services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
+               services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
+#endif
        }
 };
 
-void nodePlacementPrediction(Client &client,
+bool nodePlacementPrediction(Client &client,
                const ItemDefinition &playeritem_def,
                v3s16 nodepos, v3s16 neighbourpos)
 {
@@ -835,7 +851,7 @@ void nodePlacementPrediction(Client &client,
                        if(nodedef->get(n_under).buildable_to)
                                p = nodepos;
                        else if (!nodedef->get(map.getNode(p)).buildable_to)
-                               return;
+                               return false;
                }catch(InvalidPositionException &e){}
                // Find id of predicted node
                content_t id;
@@ -845,7 +861,7 @@ void nodePlacementPrediction(Client &client,
                                        <<playeritem_def.name<<" (places "
                                        <<prediction
                                        <<") - Name not known"<<std::endl;
-                       return;
+                       return false;
                }
                // Predict param2 for facedir and wallmounted nodes
                u8 param2 = 0;
@@ -884,13 +900,25 @@ void nodePlacementPrediction(Client &client,
                        else
                                pp = p + v3s16(0,-1,0);
                        if(!nodedef->get(map.getNode(pp)).walkable)
-                               return;
+                               return false;
                }
                // Add node to client map
                MapNode n(id, 0, param2);
                try{
-                       // This triggers the required mesh update too
-                       client.addNode(p, n);
+                       LocalPlayer* player = client.getEnv().getLocalPlayer();
+
+                       // Dont place node when player would be inside new node
+                       // NOTE: This is to be eventually implemented by a mod as client-side Lua
+                       if (!nodedef->get(n).walkable || 
+                               (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) || 
+                               (nodedef->get(n).walkable &&
+                               neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
+                               neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
+
+                                       // This triggers the required mesh update too
+                                       client.addNode(p, n);
+                                       return true;
+                               }
                }catch(InvalidPositionException &e){
                        errorstream<<"Node placement prediction failed for "
                                        <<playeritem_def.name<<" (places "
@@ -898,6 +926,7 @@ void nodePlacementPrediction(Client &client,
                                        <<") - Position not loaded"<<std::endl;
                }
        }
+       return false;
 }
 
 
@@ -913,13 +942,13 @@ void the_game(
        std::string address, // If "", local server is used
        u16 port,
        std::wstring &error_message,
-       std::string configpath,
        ChatBackend &chat_backend,
        const SubgameSpec &gamespec, // Used for local game,
        bool simple_singleplayer_mode
 )
 {
        FormspecFormSource* current_formspec = 0;
+       TextDestPlayerInventory* current_textdest = 0;
        video::IVideoDriver* driver = device->getVideoDriver();
        scene::ISceneManager* smgr = device->getSceneManager();
        
@@ -998,7 +1027,7 @@ void the_game(
                draw_load_screen(text, device, font,0,25);
                delete[] text;
                infostream<<"Creating server"<<std::endl;
-               server = new Server(map_dir, configpath, gamespec,
+               server = new Server(map_dir, gamespec,
                                simple_singleplayer_mode);
                server->start(port);
        }
@@ -1017,12 +1046,6 @@ void the_game(
        infostream<<"Creating client"<<std::endl;
        
        MapDrawControl draw_control;
-
-       Client client(device, playername.c_str(), password, draw_control,
-                       tsrc, shsrc, itemdef, nodedef, sound, &eventmgr);
-       
-       // Client acts as our GameDef
-       IGameDef *gamedef = &client;
        
        {
                wchar_t* text = wgettext("Resolving address...");
@@ -1032,18 +1055,39 @@ void the_game(
        Address connect_address(0,0,0,0, port);
        try{
                if(address == "")
+               {
                        //connect_address.Resolve("localhost");
-                       connect_address.setAddress(127,0,0,1);
+                       if(g_settings->getBool("enable_ipv6") && g_settings->getBool("ipv6_server"))
+                       {
+                               IPv6AddressBytes addr_bytes;
+                               addr_bytes.bytes[15] = 1;
+                               connect_address.setAddress(&addr_bytes);
+                       }
+                       else
+                       {
+                               connect_address.setAddress(127,0,0,1);
+                       }
+               }
                else
                        connect_address.Resolve(address.c_str());
        }
        catch(ResolveError &e)
        {
-               error_message = L"Couldn't resolve address";
+               error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
                errorstream<<wide_to_narrow(error_message)<<std::endl;
                // Break out of client scope
                break;
        }
+       
+       /*
+               Create client
+       */
+       Client client(device, playername.c_str(), password, draw_control,
+               tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
+               connect_address.isIPv6());
+       
+       // Client acts as our GameDef
+       IGameDef *gamedef = &client;
 
        /*
                Attempt to connect to the server
@@ -1176,13 +1220,19 @@ void the_game(
                                server->step(dtime);
                        
                        // End condition
-                       if(client.texturesReceived() &&
+                       if(client.mediaReceived() &&
                                        client.itemdefReceived() &&
                                        client.nodedefReceived()){
                                got_content = true;
                                break;
                        }
                        // Break conditions
+                       if(client.accessDenied()){
+                               error_message = L"Access denied. Reason: "
+                                               +client.accessDeniedReason();
+                               errorstream<<wide_to_narrow(error_message)<<std::endl;
+                               break;
+                       }
                        if(!client.connectedAndInitialized()){
                                error_message = L"Client disconnected";
                                errorstream<<wide_to_narrow(error_message)<<std::endl;
@@ -1195,26 +1245,28 @@ void the_game(
                        }
                        
                        // Display status
-                       std::ostringstream ss;
                        int progress=0;
                        if (!client.itemdefReceived())
                        {
-                               ss << "Item definitions...";
+                               wchar_t* text = wgettext("Item definitions...");
                                progress = 0;
+                               draw_load_screen(text, device, font, dtime, progress);
+                               delete[] text;
                        }
                        else if (!client.nodedefReceived())
                        {
-                               ss << "Node definitions...";
+                               wchar_t* text = wgettext("Node definitions...");
                                progress = 25;
+                               draw_load_screen(text, device, font, dtime, progress);
+                               delete[] text;
                        }
                        else
                        {
-                               ss << "Media...";
+                               wchar_t* text = wgettext("Media...");
                                progress = 50+client.mediaReceiveProgress()*50+0.5;
+                               draw_load_screen(text, device, font, dtime, progress);
+                               delete[] text;
                        }
-                       wchar_t* text = wgettext(ss.str().c_str());
-                       draw_load_screen(text, device, font, dtime, progress);
-                       delete[] text;
                        
                        // On some computers framerate doesn't seem to be
                        // automatically limited
@@ -1284,18 +1336,10 @@ void the_game(
        */
 
        Sky *sky = NULL;
-       sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
-       
-       /*
-               FarMesh
-       */
-
-       FarMesh *farmesh = NULL;
-       if(g_settings->getBool("enable_farmesh"))
-       {
-               farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
-       }
+       sky = new Sky(smgr->getRootSceneNode(), smgr, -1, client.getEnv().getLocalPlayer());
 
+       scene::ISceneNode* skybox = NULL;
+       
        /*
                A copy of the local inventory
        */
@@ -1306,7 +1350,7 @@ void the_game(
        */
        int crack_animation_length = 5;
        {
-               video::ITexture *t = tsrc->getTextureRaw("crack_anylength.png");
+               video::ITexture *t = tsrc->getTexture("crack_anylength.png");
                v2u32 size = t->getOriginalSize();
                crack_animation_length = size.Y / size.X;
        }
@@ -1360,6 +1404,7 @@ void the_game(
                        false, false);
        guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
        guitext_profiler->setVisible(false);
+       guitext_profiler->setWordWrap(true);
        
        /*
                Some statistics are collected in these
@@ -1384,7 +1429,6 @@ void the_game(
        bool ldown_for_dig = false;
 
        float damage_flash = 0;
-       s16 farmesh_range = 20*MAP_BLOCKSIZE;
 
        float jump_timer = 0;
        bool reset_jump_timer = false;
@@ -1399,7 +1443,7 @@ void the_game(
        bool invert_mouse = g_settings->getBool("invert_mouse");
 
        bool respawn_menu_active = false;
-       bool update_wielded_item_trigger = false;
+       bool update_wielded_item_trigger = true;
 
        bool show_hud = true;
        bool show_chat = true;
@@ -1444,9 +1488,16 @@ void the_game(
        /*
                HUD object
        */
-       Hud hud(driver, guienv, font, text_height,
+       Hud hud(driver, smgr, guienv, font, text_height,
                        gamedef, player, &local_inventory);
 
+       bool use_weather = g_settings->getBool("weather");
+
+       core::stringw str = L"Minetest [";
+       str += driver->getName();
+       str += "]";
+       device->setWindowCaption(str.c_str());
+
        for(;;)
        {
                if(device->run() == false || kill == true)
@@ -1475,7 +1526,9 @@ void the_game(
                */
 
                {
-                       float fps_max = g_settings->getFloat("fps_max");
+                       float fps_max = g_menumgr.pausesGame() ?
+                                       g_settings->getFloat("pause_fps_max") :
+                                       g_settings->getFloat("fps_max");
                        u32 frametime_min = 1000./fps_max;
                        
                        if(busytime_u32 < frametime_min)
@@ -1678,6 +1731,10 @@ void the_game(
                {
                        input->clear();
                }
+               if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
+               {
+                       gui_chat_console->closeConsoleAtOnce();
+               }
 
                // Input handler step() (used by the random input generator)
                input->step(dtime);
@@ -1707,7 +1764,7 @@ void the_game(
                        GUIFormSpecMenu *menu =
                                new GUIFormSpecMenu(device, guiroot, -1,
                                        &g_menumgr,
-                                       &client, gamedef);
+                                       &client, gamedef, tsrc);
 
                        InventoryLocation inventoryloc;
                        inventoryloc.setCurrentPlayer();
@@ -1832,12 +1889,12 @@ void the_game(
                }
                else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
                {
-                       irr::video::IImage* const image = driver->createScreenShot(); 
-                       if (image) { 
-                               irr::c8 filename[256]; 
-                               snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png", 
+                       irr::video::IImage* const image = driver->createScreenShot();
+                       if (image) {
+                               irr::c8 filename[256];
+                               snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
                                                 g_settings->get("screenshot_path").c_str(),
-                                                device->getTimer()->getRealTime()); 
+                                                device->getTimer()->getRealTime());
                                if (driver->writeImageToFile(image, filename)) {
                                        std::wstringstream sstr;
                                        sstr<<"Saved screenshot to '"<<filename<<"'";
@@ -1847,8 +1904,8 @@ void the_game(
                                } else{
                                        infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
                                }
-                               image->drop(); 
-                       }                        
+                               image->drop();
+                       }
                }
                else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
                {
@@ -2150,25 +2207,28 @@ void the_game(
                        LocalPlayer* player = client.getEnv().getLocalPlayer();
                        player->keyPressed=keyPressed;
                }
-               
+
                /*
-                       Run server
+                       Run server, client (and process environments)
                */
-
-               if(server != NULL)
+               bool can_be_and_is_paused =
+                               (simple_singleplayer_mode && g_menumgr.pausesGame());
+               if(can_be_and_is_paused)
                {
-                       //TimeTaker timer("server->step(dtime)");
-                       server->step(dtime);
+                       // No time passes
+                       dtime = 0;
                }
-
-               /*
-                       Process environment
-               */
-               
+               else
                {
-                       //TimeTaker timer("client.step(dtime)");
-                       client.step(dtime);
-                       //client.step(dtime_avg1);
+                       if(server != NULL)
+                       {
+                               //TimeTaker timer("server->step(dtime)");
+                               server->step(dtime);
+                       }
+                       {
+                               //TimeTaker timer("client.step(dtime)");
+                               client.step(dtime);
+                       }
                }
 
                {
@@ -2192,6 +2252,9 @@ void the_game(
                                        player->hurt_tilt_timer = 1.5;
                                        player->hurt_tilt_strength = event.player_damage.amount/2;
                                        player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
+
+                                       MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
+                                       gamedef->event()->put(e);
                                }
                                else if(event.type == CE_PLAYER_FORCE_MOVE)
                                {
@@ -2213,7 +2276,7 @@ void the_game(
                                                        new MainRespawnInitiator(
                                                                        &respawn_menu_active, &client);
                                        GUIDeathScreen *menu =
-                                                       new GUIDeathScreen(guienv, guiroot, -1, 
+                                                       new GUIDeathScreen(guienv, guiroot, -1,
                                                                &g_menumgr, respawner);
                                        menu->drop();
                                        
@@ -2236,32 +2299,32 @@ void the_game(
                                        if (current_formspec == 0)
                                        {
                                                /* Create menu */
+                                               /* Note: FormspecFormSource and TextDestPlayerInventory
+                                                * are deleted by guiFormSpecMenu                     */
                                                current_formspec = new FormspecFormSource(*(event.show_formspec.formspec),&current_formspec);
-
+                                               current_textdest = new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
                                                GUIFormSpecMenu *menu =
                                                                new GUIFormSpecMenu(device, guiroot, -1,
                                                                                &g_menumgr,
-                                                                               &client, gamedef);
+                                                                               &client, gamedef, tsrc);
                                                menu->setFormSource(current_formspec);
-                                               menu->setTextDest(new TextDestPlayerInventory(&client,*(event.show_formspec.formname)));
+                                               menu->setTextDest(current_textdest);
                                                menu->drop();
                                        }
                                        else
                                        {
+                                               assert(current_textdest != 0);
                                                /* update menu */
+                                               current_textdest->setFormName(*(event.show_formspec.formname));
                                                current_formspec->setForm(*(event.show_formspec.formspec));
                                        }
                                        delete(event.show_formspec.formspec);
                                        delete(event.show_formspec.formname);
                                }
-                               else if(event.type == CE_TEXTURES_UPDATED)
-                               {
-                                       update_wielded_item_trigger = true;
-                               }
                                else if(event.type == CE_SPAWN_PARTICLE)
                                {
                                        LocalPlayer* player = client.getEnv().getLocalPlayer();
-                                       AtlasPointer ap =
+                                       video::ITexture *texture =
                                                gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
 
                                        new Particle(gamedef, smgr, player, client.getEnv(),
@@ -2270,12 +2333,16 @@ void the_game(
                                                *event.spawn_particle.acc,
                                                 event.spawn_particle.expirationtime,
                                                 event.spawn_particle.size,
-                                                event.spawn_particle.collisiondetection, ap);
+                                                event.spawn_particle.collisiondetection,
+                                                event.spawn_particle.vertical,
+                                                texture,
+                                                v2f(0.0, 0.0),
+                                                v2f(1.0, 1.0));
                                }
                                else if(event.type == CE_ADD_PARTICLESPAWNER)
                                {
                                        LocalPlayer* player = client.getEnv().getLocalPlayer();
-                                       AtlasPointer ap =
+                                       video::ITexture *texture =
                                                gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
 
                                        new ParticleSpawner(gamedef, smgr, player,
@@ -2292,7 +2359,8 @@ void the_game(
                                                 event.add_particlespawner.minsize,
                                                 event.add_particlespawner.maxsize,
                                                 event.add_particlespawner.collisiondetection,
-                                                ap,
+                                                event.add_particlespawner.vertical,
+                                                texture,
                                                 event.add_particlespawner.id);
                                }
                                else if(event.type == CE_DELETE_PARTICLESPAWNER)
@@ -2310,6 +2378,7 @@ void the_game(
                                                delete event.hudadd.text;
                                                delete event.hudadd.align;
                                                delete event.hudadd.offset;
+                                               delete event.hudadd.world_pos;
                                                continue;
                                        }
                                        
@@ -2324,6 +2393,7 @@ void the_game(
                                        e->dir    = event.hudadd.dir;
                                        e->align  = *event.hudadd.align;
                                        e->offset = *event.hudadd.offset;
+                                       e->world_pos = *event.hudadd.world_pos;
                                        
                                        if (id == nhudelem)
                                                player->hud.push_back(e);
@@ -2336,6 +2406,7 @@ void the_game(
                                        delete event.hudadd.text;
                                        delete event.hudadd.align;
                                        delete event.hudadd.offset;
+                                       delete event.hudadd.world_pos;
                                }
                                else if (event.type == CE_HUDRM)
                                {
@@ -2349,6 +2420,7 @@ void the_game(
                                {
                                        u32 id = event.hudchange.id;
                                        if (id >= player->hud.size() || !player->hud[id]) {
+                                               delete event.hudchange.v3fdata;
                                                delete event.hudchange.v2fdata;
                                                delete event.hudchange.sdata;
                                                continue;
@@ -2383,11 +2455,55 @@ void the_game(
                                                case HUD_STAT_OFFSET:
                                                        e->offset = *event.hudchange.v2fdata;
                                                        break;
+                                               case HUD_STAT_WORLD_POS:
+                                                       e->world_pos = *event.hudchange.v3fdata;
+                                                       break;
                                        }
                                        
+                                       delete event.hudchange.v3fdata;
                                        delete event.hudchange.v2fdata;
                                        delete event.hudchange.sdata;
                                }
+                               else if (event.type == CE_SET_SKY)
+                               {
+                                       sky->setVisible(false);
+                                       if(skybox){
+                                               skybox->drop();
+                                               skybox = NULL;
+                                       }
+                                       // Handle according to type
+                                       if(*event.set_sky.type == "regular"){
+                                               sky->setVisible(true);
+                                       }
+                                       else if(*event.set_sky.type == "skybox" &&
+                                                       event.set_sky.params->size() == 6){
+                                               sky->setFallbackBgColor(*event.set_sky.bgcolor);
+                                               skybox = smgr->addSkyBoxSceneNode(
+                                                               tsrc->getTexture((*event.set_sky.params)[0]),
+                                                               tsrc->getTexture((*event.set_sky.params)[1]),
+                                                               tsrc->getTexture((*event.set_sky.params)[2]),
+                                                               tsrc->getTexture((*event.set_sky.params)[3]),
+                                                               tsrc->getTexture((*event.set_sky.params)[4]),
+                                                               tsrc->getTexture((*event.set_sky.params)[5]));
+                                       }
+                                       // Handle everything else as plain color
+                                       else {
+                                               if(*event.set_sky.type != "plain")
+                                                       infostream<<"Unknown sky type: "
+                                                                       <<(*event.set_sky.type)<<std::endl;
+                                               sky->setFallbackBgColor(*event.set_sky.bgcolor);
+                                       }
+
+                                       delete event.set_sky.bgcolor;
+                                       delete event.set_sky.type;
+                                       delete event.set_sky.params;
+                               }
+                               else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO)
+                               {
+                                       bool enable = event.override_day_night_ratio.do_override;
+                                       u32 value = event.override_day_night_ratio.ratio_f * 1000;
+                                       client.getEnv().setDayNightRatioOverride(enable, value);
+                               }
                        }
                }
                
@@ -2420,10 +2536,12 @@ void the_game(
                float full_punch_interval = playeritem_toolcap.full_punch_interval;
                float tool_reload_ratio = time_from_last_punch / full_punch_interval;
                tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
-               camera.update(player, busytime, screensize, tool_reload_ratio);
+               camera.update(player, dtime, busytime, screensize,
+                               tool_reload_ratio);
                camera.step(dtime);
 
                v3f player_position = player->getPosition();
+               v3s16 pos_i = floatToInt(player_position, BS);
                v3f camera_position = camera.getPosition();
                v3f camera_direction = camera.getDirection();
                f32 camera_fov = camera.getFovMax();
@@ -2457,7 +2575,12 @@ void the_game(
                
                //u32 t1 = device->getTimer()->getRealTime();
                
-               f32 d = 4; // max. distance
+               f32 d = playeritem_def.range; // max. distance
+               f32 d_hand = itemdef->get("").range;
+               if(d < 0 && d_hand >= 0)
+                       d = d_hand;
+               else if(d < 0)
+                       d = 4.0;
                core::line3d<f32> shootline(camera_position,
                                camera_position + camera_direction * BS * (d+1));
 
@@ -2557,7 +2680,8 @@ void the_game(
                                Handle digging
                        */
                        
-                       if(nodig_delay_timer <= 0.0 && input->getLeftState())
+                       if(nodig_delay_timer <= 0.0 && input->getLeftState()
+                                       && client.checkPrivilege("interact"))
                        {
                                if(!digging)
                                {
@@ -2580,20 +2704,6 @@ void the_game(
                                        if(tp)
                                                params = getDigParams(nodedef->get(n).groups, tp);
                                }
-                               
-                               SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
-                               if(sound_dig.exists()){
-                                       if(sound_dig.name == "__group"){
-                                               if(params.main_group != ""){
-                                                       soundmaker.m_player_leftpunch_sound.gain = 0.5;
-                                                       soundmaker.m_player_leftpunch_sound.name =
-                                                                       std::string("default_dig_") +
-                                                                                       params.main_group;
-                                               }
-                                       } else{
-                                               soundmaker.m_player_leftpunch_sound = sound_dig;
-                                       }
-                               }
 
                                float dig_time_complete = 0.0;
 
@@ -2626,6 +2736,20 @@ void the_game(
                                        dig_index = crack_animation_length;
                                }
 
+                               SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
+                               if(sound_dig.exists() && params.diggable){
+                                       if(sound_dig.name == "__group"){
+                                               if(params.main_group != ""){
+                                                       soundmaker.m_player_leftpunch_sound.gain = 0.5;
+                                                       soundmaker.m_player_leftpunch_sound.name =
+                                                                       std::string("default_dig_") +
+                                                                                       params.main_group;
+                                               }
+                                       } else{
+                                               soundmaker.m_player_leftpunch_sound = sound_dig;
+                                       }
+                               }
+
                                // Don't show cracks if not diggable
                                if(dig_time_complete >= 100000.0)
                                {
@@ -2674,20 +2798,27 @@ void the_game(
                                        gamedef->event()->put(e);
                                }
 
-                               dig_time += dtime;
+                               if(dig_time_complete < 100000.0)
+                                       dig_time += dtime;
+                               else {
+                                       dig_time = 0;
+                                       client.setCrack(-1, nodepos);
+                               }
 
                                camera.setDigging(0);  // left click animation
                        }
 
-                       if(input->getRightClicked() ||
-                                       repeat_rightclick_timer >= g_settings->getFloat("repeat_rightclick_time"))
+                       if((input->getRightClicked() ||
+                                       repeat_rightclick_timer >=
+                                               g_settings->getFloat("repeat_rightclick_time")) &&
+                                       client.checkPrivilege("interact"))
                        {
                                repeat_rightclick_timer = 0;
                                infostream<<"Ground right-clicked"<<std::endl;
                                
                                // Sign special case, at least until formspec is properly implemented.
                                // Deprecated?
-                               if(meta && meta->getString("formspec") == "hack:sign_text_input" 
+                               if(meta && meta->getString("formspec") == "hack:sign_text_input"
                                                && !random_input
                                                && !input->isKeyDown(getKeySetting("keymap_sneak")))
                                {
@@ -2717,7 +2848,7 @@ void the_game(
                                        GUIFormSpecMenu *menu =
                                                new GUIFormSpecMenu(device, guiroot, -1,
                                                        &g_menumgr,
-                                                       &client, gamedef);
+                                                       &client, gamedef, tsrc);
                                        menu->setFormSpec(meta->getString("formspec"),
                                                        inventoryloc);
                                        menu->setFormSource(new NodeMetadataFormSource(
@@ -2728,19 +2859,28 @@ void the_game(
                                // Otherwise report right click to server
                                else
                                {
-                                       // Report to server
-                                       client.interact(3, pointed);
-                                       camera.setDigging(1);  // right click animation
-                                       
+                                       camera.setDigging(1);  // right click animation (always shown for feedback)
+
                                        // If the wielded item has node placement prediction,
                                        // make that happen
-                                       nodePlacementPrediction(client,
-                                                       playeritem_def,
-                                                       nodepos, neighbourpos);
-                                       
-                                       // Read the sound
-                                       soundmaker.m_player_rightpunch_sound =
+                                       bool placed = nodePlacementPrediction(client,
+                                               playeritem_def,
+                                               nodepos, neighbourpos);
+
+                                       if(placed) {
+                                               // Report to server
+                                               client.interact(3, pointed);
+                                               // Read the sound
+                                               soundmaker.m_player_rightpunch_sound =
                                                        playeritem_def.sound_place;
+                                       } else {
+                                               soundmaker.m_player_rightpunch_sound =
+                                                       SimpleSoundSpec();
+                                       }
+
+                                       if (playeritem_def.node_placement_prediction == "" ||
+                                               nodedef->get(map.getNode(nodepos)).rightclickable)
+                                               client.interact(3, pointed); // Report to server
                                }
                        }
                }
@@ -2814,16 +2954,14 @@ void the_game(
                        Fog range
                */
        
-               if(farmesh)
-               {
-                       fog_range = BS*farmesh_range;
-               }
-               else
-               {
+               if(draw_control.range_all)
+                       fog_range = 100000*BS;
+               else {
                        fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
+                       if(use_weather)
+                               fog_range *= (1.5 - 1.4*(float)client.getEnv().getClientMap().getHumidity(pos_i)/100);
+                       fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
                        fog_range *= 0.9;
-                       if(draw_control.range_all)
-                               fog_range = 100000*BS;
                }
 
                /*
@@ -2862,7 +3000,6 @@ void the_game(
                sky->update(time_of_day_smooth, time_brightness, direct_brightness,
                                sunlight_seen);
                
-               float brightness = sky->getBrightness();
                video::SColor bgcolor = sky->getBgColor();
                video::SColor skycolor = sky->getSkyColor();
 
@@ -2880,22 +3017,6 @@ void the_game(
                        }
                }
                
-               /*
-                       Update farmesh
-               */
-               if(farmesh)
-               {
-                       farmesh_range = draw_control.wanted_range * 10;
-                       if(draw_control.range_all && farmesh_range < 500)
-                               farmesh_range = 500;
-                       if(farmesh_range > 1000)
-                               farmesh_range = 1000;
-
-                       farmesh->step(dtime);
-                       farmesh->update(v2f(player_position.X, player_position.Z),
-                                       brightness, farmesh_range);
-               }
-
                /*
                        Update particles
                */
@@ -2907,7 +3028,7 @@ void the_game(
                        Fog
                */
                
-               if(g_settings->getBool("enable_fog") == true && !force_fog_off)
+               if(g_settings->getBool("enable_fog") && !force_fog_off)
                {
                        driver->setFog(
                                bgcolor,
@@ -2938,9 +3059,6 @@ void the_game(
 
                //TimeTaker guiupdatetimer("Gui updating");
                
-               const char program_name_and_version[] =
-                       "Minetest " VERSION_STRING;
-
                if(show_debug)
                {
                        static float drawtime_avg = 0;
@@ -2951,27 +3069,31 @@ void the_game(
                        scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
                        static float endscenetime_avg = 0;
                        endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
-                       
-                       char temptext[300];
-                       snprintf(temptext, 300, "%s ("
-                                       "R: range_all=%i"
-                                       ")"
-                                       " drawtime=%.0f, dtime_jitter = % .1f %%"
-                                       ", v_range = %.1f, RTT = %.3f",
-                                       program_name_and_version,
-                                       draw_control.range_all,
-                                       drawtime_avg,
-                                       dtime_jitter1_max_fraction * 100.0,
-                                       draw_control.wanted_range,
-                                       client.getRTT()
-                                       );
-                       
-                       guitext->setText(narrow_to_wide(temptext).c_str());
+
+                       u16 fps = (1.0/dtime_avg1);
+
+                       std::ostringstream os(std::ios_base::binary);
+                       os<<std::fixed
+                               <<"Minetest "<<minetest_version_hash
+                               <<" FPS = "<<fps
+                               <<" (R: range_all="<<draw_control.range_all<<")"
+                               <<std::setprecision(0)
+                               <<" drawtime = "<<drawtime_avg
+                               <<std::setprecision(1)
+                               <<", dtime_jitter = "
+                               <<(dtime_jitter1_max_fraction * 100.0)<<" %"
+                               <<std::setprecision(1)
+                               <<", v_range = "<<draw_control.wanted_range
+                               <<std::setprecision(3)
+                               <<", RTT = "<<client.getRTT();
+                       guitext->setText(narrow_to_wide(os.str()).c_str());
                        guitext->setVisible(true);
                }
                else if(show_hud || show_chat)
                {
-                       guitext->setText(narrow_to_wide(program_name_and_version).c_str());
+                       std::ostringstream os(std::ios_base::binary);
+                       os<<"Minetest "<<minetest_version_hash;
+                       guitext->setText(narrow_to_wide(os.str()).c_str());
                        guitext->setVisible(true);
                }
                else
@@ -2981,17 +3103,17 @@ void the_game(
                
                if(show_debug)
                {
-                       char temptext[300];
-                       snprintf(temptext, 300,
-                                       "(% .1f, % .1f, % .1f)"
-                                       " (yaw = %.1f) (seed = %llu)",
-                                       player_position.X/BS,
-                                       player_position.Y/BS,
-                                       player_position.Z/BS,
-                                       wrapDegrees_0_360(camera_yaw),
-                                       (unsigned long long)client.getMapSeed());
-
-                       guitext2->setText(narrow_to_wide(temptext).c_str());
+                       std::ostringstream os(std::ios_base::binary);
+                       os<<std::setprecision(1)<<std::fixed
+                               <<"(" <<(player_position.X/BS)
+                               <<", "<<(player_position.Y/BS)
+                               <<", "<<(player_position.Z/BS)
+                               <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
+                               <<") (t="<<client.getEnv().getClientMap().getHeat(pos_i)
+                               <<"C, h="<<client.getEnv().getClientMap().getHumidity(pos_i)
+                               <<"%) (seed = "<<((unsigned long long)client.getMapSeed())
+                               <<")";
+                       guitext2->setText(narrow_to_wide(os.str()).c_str());
                        guitext2->setVisible(true);
                }
                else
@@ -3168,7 +3290,7 @@ void the_game(
 
                                driver->getOverrideMaterial().Material.ColorMask = irr::video::ECP_RED;
                                driver->getOverrideMaterial().EnableFlags  = irr::video::EMF_COLOR_MASK;
-                               driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX + 
+                               driver->getOverrideMaterial().EnablePasses = irr::scene::ESNRP_SKY_BOX +
                                                                                                                         irr::scene::ESNRP_SOLID +
                                                                                                                         irr::scene::ESNRP_TRANSPARENT +
                                                                                                                         irr::scene::ESNRP_TRANSPARENT_EFFECT +
@@ -3179,6 +3301,11 @@ void the_game(
 
                                smgr->drawAll(); // 'smgr->drawAll();' may go here
 
+                               driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
+
+                               if (show_hud)
+                                       hud.drawSelectionBoxes(hilightboxes);
+
 
                                //Right eye...
                                irr::core::vector3df rightEye;
@@ -3203,6 +3330,11 @@ void the_game(
 
                                smgr->drawAll(); // 'smgr->drawAll();' may go here
 
+                               driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
+
+                               if (show_hud)
+                                       hud.drawSelectionBoxes(hilightboxes);
+
 
                                //driver->endScene();
 
@@ -3231,9 +3363,11 @@ void the_game(
                driver->setMaterial(m);
 
                driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
-
-               if (show_hud)
+               if((!g_settings->getBool("anaglyph")) && (show_hud))
+               {
                        hud.drawSelectionBoxes(hilightboxes);
+               }
+
                /*
                        Wielded tool
                */
@@ -3276,7 +3410,7 @@ void the_game(
                if (show_hud)
                {
                        hud.drawHotbar(v2s32(displaycenter.X, screensize.Y),
-                                       client.getHP(), client.getPlayerItem());
+                                       client.getHP(), client.getPlayerItem(), client.getBreath());
                }
 
                /*
@@ -3319,7 +3453,7 @@ void the_game(
                */
                {
                        TimeTaker timer("endScene");
-                       endSceneX(driver);
+                       driver->endScene();
                        endscenetime = timer.stop(true);
                }
 
@@ -3330,21 +3464,6 @@ void the_game(
                        End of drawing
                */
 
-               static s16 lastFPS = 0;
-               //u16 fps = driver->getFPS();
-               u16 fps = (1.0/dtime_avg1);
-
-               if (lastFPS != fps)
-               {
-                       core::stringw str = L"Minetest [";
-                       str += driver->getName();
-                       str += "] FPS=";
-                       str += fps;
-
-                       device->setWindowCaption(str.c_str());
-                       lastFPS = fps;
-               }
-
                /*
                        Log times and stuff for visualization
                */
@@ -3382,6 +3501,16 @@ void the_game(
        chat_backend.addMessage(L"", L"# Disconnected.");
        chat_backend.addMessage(L"", L"");
 
+       client.Stop();
+
+       //force answer all texture and shader jobs (TODO return empty values)
+
+       while(!client.isShutdown()) {
+               tsrc->processQueue();
+               shsrc->processQueue();
+               sleep_ms(100);
+       }
+
        // Client scope (client is destructed before destructing *def and tsrc)
        }while(0);
        } // try-catch
@@ -3392,14 +3521,12 @@ void the_game(
                                L" running a different version of Minetest.";
                errorstream<<wide_to_narrow(error_message)<<std::endl;
        }
-       catch(ServerError &e)
-       {
+       catch(ServerError &e) {
                error_message = narrow_to_wide(e.what());
-               errorstream<<wide_to_narrow(error_message)<<std::endl;
+               errorstream << "ServerError: " << e.what() << std::endl;
        }
-       catch(ModError &e)
-       {
-               errorstream<<e.what()<<std::endl;
+       catch(ModError &e) {
+               errorstream << "ModError: " << e.what() << std::endl;
                error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
        }
 
@@ -3427,6 +3554,7 @@ void the_game(
                infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
                                << std::endl;
        }
+       clearTextureNameCache();
        infostream << "\tRemaining materials: "
                << driver-> getMaterialRendererCount ()
                << " (note: irrlicht doesn't support removing renderers)"<< std::endl;