]> git.lizzy.rs Git - minetest.git/blobdiff - src/game.cpp
TOGGLE_CHAT keymap should togglechat not HUD
[minetest.git] / src / game.cpp
index 83ef9c0b09fe7777a4a2c561668cfcd3fa0e9165..cb38208700162e5cec41b552a981dc6e95b0d5b5 100644 (file)
@@ -41,7 +41,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "guiKeyChangeMenu.h"
 #include "guiPasswordChange.h"
 #include "guiVolumeChange.h"
-#include "hud.h"
 #include "mainmenumanager.h"
 #include "mapblock.h"
 #include "nodedef.h"         // Needed for determining pointing to nodes
@@ -61,6 +60,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "version.h"
 #include "minimap.h"
 #include "mapblock_mesh.h"
+#include "script/clientscripting.h"
 
 #include "sound.h"
 
@@ -125,6 +125,7 @@ struct TextDestPlayerInventory : public TextDest {
 
 struct LocalFormspecHandler : public TextDest {
        LocalFormspecHandler();
+
        LocalFormspecHandler(std::string formname) :
                m_client(0)
        {
@@ -179,38 +180,8 @@ struct LocalFormspecHandler : public TextDest {
                        }
                }
 
-               if (m_formname == "MT_DEATH_SCREEN") {
-                       assert(m_client != 0);
-
-                       if ((fields.find("btn_respawn") != fields.end())) {
-                               m_client->sendRespawn();
-                               return;
-                       }
-
-                       if (fields.find("quit") != fields.end()) {
-                               m_client->sendRespawn();
-                               return;
-                       }
-               }
-
-               // don't show error message for unhandled cursor keys
-               if ((fields.find("key_up") != fields.end()) ||
-                               (fields.find("key_down") != fields.end()) ||
-                               (fields.find("key_left") != fields.end()) ||
-                               (fields.find("key_right") != fields.end())) {
-                       return;
-               }
-
-               errorstream << "LocalFormspecHandler::gotText unhandled >"
-                       << m_formname << "< event" << std::endl;
-
-               int i = 0;
-               StringMap::const_iterator it;
-               for (it = fields.begin(); it != fields.end(); ++it) {
-                       errorstream << "\t" << i << ": " << it->first
-                               << "=" << it->second << std::endl;
-                       i++;
-               }
+               // Don't disable this part when modding is disabled, it's used in builtin
+               m_client->getScript()->on_formspec_input(m_formname, fields);
        }
 
        Client *m_client;
@@ -265,269 +236,6 @@ class PlayerInventoryFormSource: public IFormSource
        Client *m_client;
 };
 
-/*
-       Check if a node is pointable
-*/
-inline bool isPointableNode(const MapNode &n,
-                           Client *client, bool liquids_pointable)
-{
-       const ContentFeatures &features = client->getNodeDefManager()->get(n);
-       return features.pointable ||
-              (liquids_pointable && features.isLiquid());
-}
-
-static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
-               ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors)
-{
-       MapNode n2 = map->getNodeNoEx(p);
-       if (nodedef->nodeboxConnects(n, n2, bitmask))
-               *neighbors |= bitmask;
-}
-
-static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n)
-{
-       u8 neighbors = 0;
-       const ContentFeatures &f = nodedef->get(n);
-       // locate possible neighboring nodes to connect to
-       if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
-               v3s16 p2 = p;
-
-               p2.Y++;
-               getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
-
-               p2 = p;
-               p2.Y--;
-               getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
-
-               p2 = p;
-               p2.Z--;
-               getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
-
-               p2 = p;
-               p2.X--;
-               getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
-
-               p2 = p;
-               p2.Z++;
-               getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
-
-               p2 = p;
-               p2.X++;
-               getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
-       }
-
-       return neighbors;
-}
-
-/*
-       Find what the player is pointing at
-*/
-PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
-               const v3f &camera_direction, const v3f &camera_position,
-               core::line3d<f32> shootline, f32 d, bool liquids_pointable,
-               bool look_for_object, const v3s16 &camera_offset,
-               ClientActiveObject *&selected_object)
-{
-       PointedThing result;
-
-       std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
-       selectionboxes->clear();
-       static const bool show_entity_selectionbox = g_settings->getBool("show_entity_selectionbox");
-
-       selected_object = NULL;
-
-       INodeDefManager *nodedef = client->getNodeDefManager();
-       ClientMap &map = client->getEnv().getClientMap();
-
-       f32 min_distance = BS * 1001;
-
-       // First try to find a pointed at active object
-       if (look_for_object) {
-               selected_object = client->getSelectedActiveObject(d * BS,
-                                 camera_position, shootline);
-
-               if (selected_object != NULL) {
-                       if (show_entity_selectionbox &&
-                                       selected_object->doShowSelectionBox()) {
-                               aabb3f *selection_box = selected_object->getSelectionBox();
-                               // Box should exist because object was
-                               // returned in the first place
-                               assert(selection_box);
-
-                               v3f pos = selected_object->getPosition();
-                               selectionboxes->push_back(aabb3f(
-                                       selection_box->MinEdge, selection_box->MaxEdge));
-                               hud->setSelectionPos(pos, camera_offset);
-                       }
-
-                       min_distance = (selected_object->getPosition() - camera_position).getLength();
-
-                       result.type = POINTEDTHING_OBJECT;
-                       result.object_id = selected_object->getId();
-               }
-       }
-
-       // That didn't work, try to find a pointed at node
-
-       v3s16 pos_i = floatToInt(player_position, BS);
-
-       /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
-                       <<std::endl;*/
-
-       s16 a = d;
-       s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
-       s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
-       s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
-       s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
-       s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
-       s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
-
-       // Prevent signed number overflow
-       if (yend == 32767)
-               yend = 32766;
-
-       if (zend == 32767)
-               zend = 32766;
-
-       if (xend == 32767)
-               xend = 32766;
-
-       v3s16 pointed_pos(0, 0, 0);
-
-       for (s16 y = ystart; y <= yend; y++) {
-               for (s16 z = zstart; z <= zend; z++) {
-                       for (s16 x = xstart; x <= xend; x++) {
-                               MapNode n;
-                               bool is_valid_position;
-                               v3s16 p(x, y, z);
-
-                               n = map.getNodeNoEx(p, &is_valid_position);
-                               if (!is_valid_position) {
-                                       continue;
-                               }
-                               if (!isPointableNode(n, client, liquids_pointable)) {
-                                       continue;
-                               }
-
-                               std::vector<aabb3f> boxes;
-                               n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
-
-                               v3s16 np(x, y, z);
-                               v3f npf = intToFloat(np, BS);
-                               for (std::vector<aabb3f>::const_iterator
-                                               i = boxes.begin();
-                                               i != boxes.end(); ++i) {
-                                       aabb3f box = *i;
-                                       box.MinEdge += npf;
-                                       box.MaxEdge += npf;
-
-                                       v3f centerpoint = box.getCenter();
-                                       f32 distance = (centerpoint - camera_position).getLength();
-                                       if (distance >= min_distance) {
-                                               continue;
-                                       }
-                                       if (!box.intersectsWithLine(shootline)) {
-                                               continue;
-                                       }
-                                       result.type = POINTEDTHING_NODE;
-                                       min_distance = distance;
-                                       pointed_pos = np;
-                               }
-                       }
-               }
-       }
-
-       if (result.type == POINTEDTHING_NODE) {
-               f32 d = 0.001 * BS;
-               MapNode n = map.getNodeNoEx(pointed_pos);
-               v3f npf = intToFloat(pointed_pos, BS);
-               std::vector<aabb3f> boxes;
-               n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
-               f32 face_min_distance = 1000 * BS;
-               for (std::vector<aabb3f>::const_iterator
-                               i = boxes.begin();
-                               i != boxes.end(); ++i) {
-                       aabb3f box = *i;
-                       box.MinEdge += npf;
-                       box.MaxEdge += npf;
-                       for (u16 j = 0; j < 6; j++) {
-                               v3s16 facedir = g_6dirs[j];
-                               aabb3f facebox = box;
-                               if (facedir.X > 0) {
-                                       facebox.MinEdge.X = facebox.MaxEdge.X - d;
-                               } else if (facedir.X < 0) {
-                                       facebox.MaxEdge.X = facebox.MinEdge.X + d;
-                               } else if (facedir.Y > 0) {
-                                       facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
-                               } else if (facedir.Y < 0) {
-                                       facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
-                               } else if (facedir.Z > 0) {
-                                       facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
-                               } else if (facedir.Z < 0) {
-                                       facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
-                               }
-                               v3f centerpoint = facebox.getCenter();
-                               f32 distance = (centerpoint - camera_position).getLength();
-                               if (distance >= face_min_distance)
-                                       continue;
-                               if (!facebox.intersectsWithLine(shootline))
-                                       continue;
-                               result.node_abovesurface = pointed_pos + facedir;
-                               face_min_distance = distance;
-                       }
-               }
-               selectionboxes->clear();
-               for (std::vector<aabb3f>::const_iterator
-                               i = boxes.begin();
-                               i != boxes.end(); ++i) {
-                       aabb3f box = *i;
-                       box.MinEdge += v3f(-d, -d, -d);
-                       box.MaxEdge += v3f(d, d, d);
-                       selectionboxes->push_back(box);
-               }
-               hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
-               result.node_undersurface = pointed_pos;
-       }
-
-       // Update selection mesh light level and vertex colors
-       if (selectionboxes->size() > 0) {
-               v3f pf = hud->getSelectionPos();
-               v3s16 p = floatToInt(pf, BS);
-
-               // Get selection mesh light level
-               MapNode n = map.getNodeNoEx(p);
-               u16 node_light = getInteriorLight(n, -1, nodedef);
-               u16 light_level = node_light;
-
-               for (u8 i = 0; i < 6; i++) {
-                       n = map.getNodeNoEx(p + g_6dirs[i]);
-                       node_light = getInteriorLight(n, -1, nodedef);
-                       if (node_light > light_level)
-                               light_level = node_light;
-               }
-
-               video::SColor c = MapBlock_LightColor(255, light_level, 0);
-               u8 day = c.getRed();
-               u8 night = c.getGreen();
-               u32 daynight_ratio = client->getEnv().getDayNightRatio();
-               finalColorBlend(c, day, night, daynight_ratio);
-
-               // Modify final color a bit with time
-               u32 timer = porting::getTimeMs() % 5000;
-               float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
-               float sin_r = 0.08 * sin(timerf);
-               float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
-               float sin_b = 0.08 * sin(timerf + irr::core::PI);
-               c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
-               c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
-               c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
-
-               // Set mesh final color
-               hud->setSelectionMeshColor(c);
-       }
-       return result;
-}
-
 /* Profiler display */
 
 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
@@ -871,7 +579,7 @@ class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
                        return;
 
                m_fetched.insert(name);
-               std::string base = porting::path_share + DIR_DELIM + "testsounds";
+               std::string base = porting::path_share + DIR_DELIM + "sounds";
                dst_paths.insert(base + DIR_DELIM + name + ".ogg");
                dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
                dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
@@ -886,40 +594,73 @@ class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
        }
 };
 
+
+// before 1.8 there isn't a "integer interface", only float
+#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
+typedef f32 SamplerLayer_t;
+#else
+typedef s32 SamplerLayer_t;
+#endif
+
+
 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
 {
        Sky *m_sky;
        bool *m_force_fog_off;
        f32 *m_fog_range;
+       bool m_fog_enabled;
+       CachedPixelShaderSetting<float, 4> m_sky_bg_color;
+       CachedPixelShaderSetting<float> m_fog_distance;
+       CachedVertexShaderSetting<float> m_animation_timer_vertex;
+       CachedPixelShaderSetting<float> m_animation_timer_pixel;
+       CachedPixelShaderSetting<float, 3> m_day_light;
+       CachedPixelShaderSetting<float, 3> m_eye_position_pixel;
+       CachedVertexShaderSetting<float, 3> m_eye_position_vertex;
+       CachedPixelShaderSetting<float, 3> m_minimap_yaw;
+       CachedPixelShaderSetting<SamplerLayer_t> m_base_texture;
+       CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture;
+       CachedPixelShaderSetting<SamplerLayer_t> m_texture_flags;
        Client *m_client;
-       bool m_fogEnabled;
 
 public:
        void onSettingsChange(const std::string &name)
        {
                if (name == "enable_fog")
-                       m_fogEnabled = g_settings->getBool("enable_fog");
+                       m_fog_enabled = g_settings->getBool("enable_fog");
        }
 
-       static void SettingsCallback(const std::string &name, void *userdata)
+       static void settingsCallback(const std::string &name, void *userdata)
        {
                reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
        }
 
+       void setSky(Sky *sky) { m_sky = sky; }
+
        GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
                        f32 *fog_range, Client *client) :
                m_sky(sky),
                m_force_fog_off(force_fog_off),
                m_fog_range(fog_range),
+               m_sky_bg_color("skyBgColor"),
+               m_fog_distance("fogDistance"),
+               m_animation_timer_vertex("animationTimer"),
+               m_animation_timer_pixel("animationTimer"),
+               m_day_light("dayLight"),
+               m_eye_position_pixel("eyePosition"),
+               m_eye_position_vertex("eyePosition"),
+               m_minimap_yaw("yawVec"),
+               m_base_texture("baseTexture"),
+               m_normal_texture("normalTexture"),
+               m_texture_flags("textureFlags"),
                m_client(client)
        {
-               g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
-               m_fogEnabled = g_settings->getBool("enable_fog");
+               g_settings->registerChangedCallback("enable_fog", settingsCallback, this);
+               m_fog_enabled = g_settings->getBool("enable_fog");
        }
 
        ~GameGlobalShaderConstantSetter()
        {
-               g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
+               g_settings->deregisterChangedCallback("enable_fog", settingsCallback, this);
        }
 
        virtual void onSetConstants(video::IMaterialRendererServices *services,
@@ -937,54 +678,98 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter
                        bgcolorf.b,
                        bgcolorf.a,
                };
-               services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
+               m_sky_bg_color.set(bgcolorfa, services);
 
                // Fog distance
                float fog_distance = 10000 * BS;
 
-               if (m_fogEnabled && !*m_force_fog_off)
+               if (m_fog_enabled && !*m_force_fog_off)
                        fog_distance = *m_fog_range;
 
-               services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
+               m_fog_distance.set(&fog_distance, services);
 
-               // 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 daynight_ratio = (float)m_client->getEnv().getDayNightRatio();
+               video::SColorf sunlight;
+               get_sunlight_color(&sunlight, daynight_ratio);
+               float dnc[3] = {
+                       sunlight.r,
+                       sunlight.g,
+                       sunlight.b };
+               m_day_light.set(dnc, services);
 
                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);
+               float animation_timer_f = (float)animation_timer / 100000.f;
+               m_animation_timer_vertex.set(&animation_timer_f, services);
+               m_animation_timer_pixel.set(&animation_timer_f, services);
 
-               v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
-               services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
+               float eye_position_array[3];
+               v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition();
+#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
+               eye_position_array[0] = epos.X;
+               eye_position_array[1] = epos.Y;
+               eye_position_array[2] = epos.Z;
+#else
+               epos.getAs3Values(eye_position_array);
+#endif
+               m_eye_position_pixel.set(eye_position_array, services);
+               m_eye_position_vertex.set(eye_position_array, services);
 
-               // Uniform sampler layers
-               // before 1.8 there isn't a "integer interface", only float
+               float minimap_yaw_array[3];
+               v3f minimap_yaw = m_client->getMinimap()->getYawVec();
 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
-               f32 layer0 = 0;
-               f32 layer1 = 1;
-               f32 layer2 = 2;
-               services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
-               services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
-               services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
+               minimap_yaw_array[0] = minimap_yaw.X;
+               minimap_yaw_array[1] = minimap_yaw.Y;
+               minimap_yaw_array[2] = minimap_yaw.Z;
 #else
-               s32 layer0 = 0;
-               s32 layer1 = 1;
-               s32 layer2 = 2;
-               services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
-               services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
-               services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
+               minimap_yaw.getAs3Values(minimap_yaw_array);
 #endif
+               m_minimap_yaw.set(minimap_yaw_array, services);
+
+               SamplerLayer_t base_tex = 0,
+                               normal_tex = 1,
+                               flags_tex = 2;
+               m_base_texture.set(&base_tex, services);
+               m_normal_texture.set(&normal_tex, services);
+               m_texture_flags.set(&flags_tex, services);
        }
 };
 
+
+class GameGlobalShaderConstantSetterFactory : public IShaderConstantSetterFactory
+{
+       Sky *m_sky;
+       bool *m_force_fog_off;
+       f32 *m_fog_range;
+       Client *m_client;
+       std::vector<GameGlobalShaderConstantSetter *> created_nosky;
+public:
+       GameGlobalShaderConstantSetterFactory(bool *force_fog_off,
+                       f32 *fog_range, Client *client) :
+               m_sky(NULL),
+               m_force_fog_off(force_fog_off),
+               m_fog_range(fog_range),
+               m_client(client)
+       {}
+
+       void setSky(Sky *sky) {
+               m_sky = sky;
+               for (size_t i = 0; i < created_nosky.size(); ++i) {
+                       created_nosky[i]->setSky(m_sky);
+               }
+               created_nosky.clear();
+       }
+
+       virtual IShaderConstantSetter* create()
+       {
+               GameGlobalShaderConstantSetter *scs = new GameGlobalShaderConstantSetter(
+                               m_sky, m_force_fog_off, m_fog_range, m_client);
+               if (!m_sky)
+                       created_nosky.push_back(scs);
+               return scs;
+       }
+};
+
+
 bool nodePlacementPrediction(Client &client,
                const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
 {
@@ -1032,7 +817,8 @@ bool nodePlacementPrediction(Client &client,
                // Predict param2 for facedir and wallmounted nodes
                u8 param2 = 0;
 
-               if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
+               if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
+                               nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED) {
                        v3s16 dir = nodepos - neighbourpos;
 
                        if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
@@ -1044,7 +830,8 @@ bool nodePlacementPrediction(Client &client,
                        }
                }
 
-               if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
+               if (nodedef->get(id).param_type_2 == CPT2_FACEDIR ||
+                               nodedef->get(id).param_type_2 == CPT2_COLORED_FACEDIR) {
                        v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
 
                        if (abs(dir.X) > abs(dir.Z)) {
@@ -1068,7 +855,8 @@ bool nodePlacementPrediction(Client &client,
                        };
                        v3s16 pp;
 
-                       if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
+                       if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED ||
+                                       nodedef->get(id).param_type_2 == CPT2_COLORED_WALLMOUNTED)
                                pp = p + wallmounted_dirs[param2];
                        else
                                pp = p + v3s16(0, -1, 0);
@@ -1108,16 +896,14 @@ bool nodePlacementPrediction(Client &client,
 }
 
 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
-               InventoryManager *invmgr, IGameDef *gamedef,
-               IWritableTextureSource *tsrc, IrrlichtDevice *device,
-               JoystickController *joystick,
-               IFormSource *fs_src, TextDest *txt_dest, Client *client)
+               Client *client, IrrlichtDevice *device, JoystickController *joystick,
+               IFormSource *fs_src, TextDest *txt_dest)
 {
 
        if (*cur_formspec == 0) {
                *cur_formspec = new GUIFormSpecMenu(device, joystick,
-                       guiroot, -1, &g_menumgr, invmgr, gamedef, tsrc,
-                       fs_src, txt_dest, client);
+                       guiroot, -1, &g_menumgr, client, client->getTextureSource(),
+                       fs_src, txt_dest);
                (*cur_formspec)->doPause = false;
 
                /*
@@ -1132,6 +918,7 @@ static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
                (*cur_formspec)->setFormSource(fs_src);
                (*cur_formspec)->setTextDest(txt_dest);
        }
+
 }
 
 #ifdef __ANDROID__
@@ -1140,32 +927,9 @@ static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
 #endif
 
-static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
-               InventoryManager *invmgr, IGameDef *gamedef,
-               IWritableTextureSource *tsrc, IrrlichtDevice *device,
-               JoystickController *joystick, Client *client)
-{
-       std::string formspec =
-               std::string(FORMSPEC_VERSION_STRING) +
-               SIZE_TAG
-               "bgcolor[#320000b4;true]"
-               "label[4.85,1.35;" + gettext("You died.") + "]"
-               "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
-               ;
-
-       /* Create menu */
-       /* Note: FormspecFormSource and LocalFormspecHandler
-        * are deleted by guiFormSpecMenu                     */
-       FormspecFormSource *fs_src = new FormspecFormSource(formspec);
-       LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
-
-       create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
-               joystick, fs_src, txt_dst, NULL);
-}
-
 /******************************************************************************/
 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
-               InventoryManager *invmgr, IGameDef *gamedef,
+               Client *client,
                IWritableTextureSource *tsrc, IrrlichtDevice *device,
                JoystickController *joystick, bool singleplayermode)
 {
@@ -1232,8 +996,7 @@ static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
        FormspecFormSource *fs_src = new FormspecFormSource(os.str());
        LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
 
-       create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device,
-               joystick, fs_src, txt_dst, NULL);
+       create_formspec_menu(cur_formspec, client, device, joystick, fs_src, txt_dst);
        std::string con("btn_continue");
        (*cur_formspec)->setFocus(con);
        (*cur_formspec)->doPause = true;
@@ -1536,51 +1299,43 @@ class Game {
 
        // Main loop
 
-       void updateInteractTimers(GameRunData *runData, f32 dtime);
+       void updateInteractTimers(f32 dtime);
        bool checkConnection();
        bool handleCallbacks();
        void processQueues();
-       void updateProfilers(const GameRunData &runData, const RunStats &stats,
-                       const FpsControl &draw_times, f32 dtime);
-       void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
-                       f32 dtime);
+       void updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
+       void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times, f32 dtime);
        void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
 
        // Input related
-       void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
-                       f32 dtime);
-       void processKeyInput(VolatileRunFlags *flags,
-                       float *statustext_time,
-                       float *jump_timer,
-                       bool *reset_jump_timer,
-                       u32 *profiler_current_page,
-                       u32 profiler_max_page);
+       void processUserInput(f32 dtime);
+       void processKeyInput();
        void processItemSelection(u16 *new_playeritem);
 
        void dropSelectedItem();
        void openInventory();
-       void openConsole(float height, const wchar_t *line=NULL);
-       void toggleFreeMove(float *statustext_time);
-       void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
-       void toggleFast(float *statustext_time);
-       void toggleNoClip(float *statustext_time);
-       void toggleCinematic(float *statustext_time);
-       void toggleAutorun(float *statustext_time);
-
-       void toggleChat(float *statustext_time, bool *flag);
-       void toggleHud(float *statustext_time, bool *flag);
-       void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
+       void openConsole(float scale, const wchar_t *line=NULL);
+       void toggleFreeMove();
+       void toggleFreeMoveAlt();
+       void toggleFast();
+       void toggleNoClip();
+       void toggleCinematic();
+       void toggleAutorun();
+
+       void toggleChat(bool *flag);
+       void toggleHud(bool *flag);
+       void toggleMinimap(bool *flag, bool show_hud,
                        bool shift_pressed);
-       void toggleFog(float *statustext_time, bool *flag);
-       void toggleDebug(float *statustext_time, bool *show_debug,
-                       bool *show_profiler_graph);
-       void toggleUpdateCamera(float *statustext_time, bool *flag);
-       void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
+       void toggleFog(bool *flag);
+       void toggleDebug(bool *show_debug,
+                       bool *show_profiler_graph, bool *show_wireframe);
+       void toggleUpdateCamera(bool *flag);
+       void toggleProfiler(u32 *profiler_current_page,
                        u32 profiler_max_page);
 
-       void increaseViewRange(float *statustext_time);
-       void decreaseViewRange(float *statustext_time);
-       void toggleFullViewRange(float *statustext_time);
+       void increaseViewRange();
+       void decreaseViewRange();
+       void toggleFullViewRange();
 
        void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags,
                float dtime);
@@ -1588,27 +1343,38 @@ class Game {
                const VolatileRunFlags &flags, float dtime);
        void updatePlayerControl(const CameraOrientation &cam);
        void step(f32 *dtime);
-       void processClientEvents(CameraOrientation *cam, float *damage_flash);
-       void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
-                       float time_from_last_punch);
+       void processClientEvents(CameraOrientation *cam);
+       void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime);
        void updateSound(f32 dtime);
-       void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
-                       bool show_debug);
-       void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
-       void handlePointingAtNode(GameRunData *runData,
-                       const PointedThing &pointed, const ItemDefinition &playeritem_def,
+       void processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug);
+       /*!
+        * Returns the object or node the player is pointing at.
+        * Also updates the selected thing in the Hud.
+        *
+        * @param[in]  shootline         the shootline, starting from
+        * the camera position. This also gives the maximal distance
+        * of the search.
+        * @param[in]  liquids_pointable if false, liquids are ignored
+        * @param[in]  look_for_object   if false, objects are ignored
+        * @param[in]  camera_offset     offset of the camera
+        * @param[out] selected_object   the selected object or
+        * NULL if not found
+        */
+       PointedThing updatePointedThing(
+                       const core::line3d<f32> &shootline, bool liquids_pointable,
+                       bool look_for_object, const v3s16 &camera_offset,
+                       ClientActiveObject *&selected_object);
+       void handlePointingAtNothing(const ItemStack &playerItem);
+       void handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
                        const ToolCapabilities &playeritem_toolcap, f32 dtime);
-       void handlePointingAtObject(GameRunData *runData,
-                       const PointedThing &pointed, const ItemStack &playeritem,
+       void handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
                        const v3f &player_position, bool show_debug);
-       void handleDigging(GameRunData *runData, const PointedThing &pointed,
-                       const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
-                       f32 dtime);
-       void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
-                       f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
-       void updateGui(float *statustext_time, const RunStats &stats,
-                       const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
-                       const CameraOrientation &cam);
+       void handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
+                       const ToolCapabilities &playeritem_toolcap, f32 dtime);
+       void updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
+                       const VolatileRunFlags &flags, const CameraOrientation &cam);
+       void updateGui(const RunStats &stats, f32 dtime,
+                       const VolatileRunFlags &flags, const CameraOrientation &cam);
        void updateProfilerGraphs(ProfilerGraph *graph);
 
        // Misc
@@ -1680,6 +1446,8 @@ class Game {
        ChatBackend *chat_backend;
 
        GUIFormSpecMenu *current_formspec;
+       //default: "". If other than "", empty show_formspec packets will only close the formspec when the formname matches
+       std::string cur_formname;
 
        EventManager *eventmgr;
        QuicktuneShortcutter *quicktune;
@@ -1691,7 +1459,10 @@ class Game {
        Sky *sky;                         // Free using ->Drop()
        Inventory *local_inventory;
        Hud *hud;
-       Mapper *mapper;
+       Minimap *mapper;
+
+       GameRunData runData;
+       VolatileRunFlags flags;
 
        /* 'cache'
           This class does take ownership/responsibily for cleaning up etc of any of
@@ -1703,7 +1474,6 @@ class Game {
        bool *kill;
        std::string *error_message;
        bool *reconnect_requested;
-       IGameDef *gamedef;                     // Convenience (same as *client)
        scene::ISceneNode *skybox;
 
        bool random_input;
@@ -1746,6 +1516,8 @@ class Game {
        f32  m_cache_mouse_sensitivity;
        f32  m_cache_joystick_frustum_sensitivity;
        f32  m_repeat_right_click_time;
+       f32  m_cache_cam_smoothing;
+       f32  m_cache_fog_start;
 
 #ifdef __ANDROID__
        bool m_cache_hold_aux1;
@@ -1765,6 +1537,7 @@ Game::Game() :
        soundmaker(NULL),
        chat_backend(NULL),
        current_formspec(NULL),
+       cur_formname(""),
        eventmgr(NULL),
        quicktune(NULL),
        gui_chat_console(NULL),
@@ -1796,6 +1569,12 @@ Game::Game() :
                &settingChangedCallback, this);
        g_settings->registerChangedCallback("free_move",
                &settingChangedCallback, this);
+       g_settings->registerChangedCallback("cinematic",
+               &settingChangedCallback, this);
+       g_settings->registerChangedCallback("cinematic_camera_smoothing",
+               &settingChangedCallback, this);
+       g_settings->registerChangedCallback("camera_smoothing",
+               &settingChangedCallback, this);
 
        readSettings();
 
@@ -1845,6 +1624,16 @@ Game::~Game()
                &settingChangedCallback, this);
        g_settings->deregisterChangedCallback("repeat_rightclick_time",
                &settingChangedCallback, this);
+       g_settings->deregisterChangedCallback("noclip",
+               &settingChangedCallback, this);
+       g_settings->deregisterChangedCallback("free_move",
+               &settingChangedCallback, this);
+       g_settings->deregisterChangedCallback("cinematic",
+               &settingChangedCallback, this);
+       g_settings->deregisterChangedCallback("cinematic_camera_smoothing",
+               &settingChangedCallback, this);
+       g_settings->deregisterChangedCallback("camera_smoothing",
+               &settingChangedCallback, this);
 }
 
 bool Game::startup(bool *kill,
@@ -1880,6 +1669,18 @@ bool Game::startup(bool *kill,
 
        smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
 
+       memset(&runData, 0, sizeof(runData));
+       runData.time_from_last_punch = 10.0;
+       runData.profiler_max_page = 3;
+       runData.update_wielded_item_trigger = true;
+
+       memset(&flags, 0, sizeof(flags));
+       flags.show_chat = true;
+       flags.show_hud = true;
+       flags.show_debug = g_settings->getBool("show_debug");
+       flags.invert_mouse = g_settings->getBool("invert_mouse");
+       flags.first_loop_after_window_activation = true;
+
        if (!init(map_dir, address, port, gamespec))
                return false;
 
@@ -1896,34 +1697,15 @@ void Game::run()
        RunStats stats              = { 0 };
        CameraOrientation cam_view_target  = { 0 };
        CameraOrientation cam_view  = { 0 };
-       GameRunData runData         = { 0 };
        FpsControl draw_times       = { 0 };
-       VolatileRunFlags flags      = { 0 };
        f32 dtime; // in seconds
 
-       runData.time_from_last_punch  = 10.0;
-       runData.profiler_max_page = 3;
-       runData.update_wielded_item_trigger = true;
-
-       flags.show_chat = true;
-       flags.show_hud = true;
-       flags.show_minimap = g_settings->getBool("enable_minimap");
-       flags.show_debug = g_settings->getBool("show_debug");
-       flags.invert_mouse = g_settings->getBool("invert_mouse");
-       flags.first_loop_after_window_activation = true;
-
        /* Clear the profiler */
        Profiler::GraphValues dummyvalues;
        g_profiler->graphGet(dummyvalues);
 
        draw_times.last_time = device->getTimer()->getTime();
 
-       shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
-                       sky,
-                       &flags.force_fog_off,
-                       &runData.fog_range,
-                       client));
-
        set_light_table(g_settings->getFloat("display_gamma"));
 
 #ifdef __ANDROID__
@@ -1941,7 +1723,7 @@ void Game::run()
                limitFps(&draw_times, &dtime);
 
                updateStats(&stats, draw_times, dtime);
-               updateInteractTimers(&runData, dtime);
+               updateInteractTimers(dtime);
 
                if (!checkConnection())
                        break;
@@ -1953,42 +1735,36 @@ void Game::run()
                infotext = L"";
                hud->resizeHotbar();
 
-               updateProfilers(runData, stats, draw_times, dtime);
-               processUserInput(&flags, &runData, dtime);
+               updateProfilers(stats, draw_times, dtime);
+               processUserInput(dtime);
                // Update camera before player movement to avoid camera lag of one frame
                updateCameraDirection(&cam_view_target, &flags, dtime);
-               float cam_smoothing = 0;
-               if (g_settings->getBool("cinematic"))
-                       cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
-               else
-                       cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
-               cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
                cam_view.camera_yaw += (cam_view_target.camera_yaw -
-                               cam_view.camera_yaw) * cam_smoothing;
+                               cam_view.camera_yaw) * m_cache_cam_smoothing;
                cam_view.camera_pitch += (cam_view_target.camera_pitch -
-                               cam_view.camera_pitch) * cam_smoothing;
+                               cam_view.camera_pitch) * m_cache_cam_smoothing;
                updatePlayerControl(cam_view);
                step(&dtime);
-               processClientEvents(&cam_view_target, &runData.damage_flash);
-               updateCamera(&flags, draw_times.busy_time, dtime,
-                               runData.time_from_last_punch);
+               processClientEvents(&cam_view_target);
+               updateCamera(&flags, draw_times.busy_time, dtime);
                updateSound(dtime);
-               processPlayerInteraction(&runData, dtime, flags.show_hud,
-                               flags.show_debug);
-               updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
+               processPlayerInteraction(dtime, flags.show_hud, flags.show_debug);
+               updateFrame(&graph, &stats, dtime, flags, cam_view);
                updateProfilerGraphs(&graph);
 
                // Update if minimap has been disabled by the server
-               flags.show_minimap &= !client->isMinimapDisabledByServer();
+               flags.show_minimap &= client->shouldShowMinimap();
        }
 }
 
 
 void Game::shutdown()
 {
+#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8
        if (g_settings->get("3d_mode") == "pageflip") {
                driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
        }
+#endif
 
        showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
 
@@ -2163,12 +1939,16 @@ bool Game::createClient(const std::string &playername,
                return false;
        }
 
+       GameGlobalShaderConstantSetterFactory *scsf = new GameGlobalShaderConstantSetterFactory(
+                       &flags.force_fog_off, &runData.fog_range, client);
+       shader_src->addShaderConstantSetterFactory(scsf);
+
        // Update cached textures, meshes and materials
        client->afterContentReceived(device);
 
        /* Camera
         */
-       camera = new Camera(smgr, *draw_control, gamedef);
+       camera = new Camera(smgr, *draw_control, client);
        if (!camera || !camera->successfullyCreated(*error_message))
                return false;
        client->setCamera(camera);
@@ -2187,6 +1967,7 @@ bool Game::createClient(const std::string &playername,
        /* Skybox
         */
        sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
+       scsf->setSky(sky);
        skybox = NULL;  // This is used/set later on in the main run loop
 
        local_inventory = new Inventory(itemdef_manager);
@@ -2224,7 +2005,7 @@ bool Game::createClient(const std::string &playername,
        player->hurt_tilt_timer = 0;
        player->hurt_tilt_strength = 0;
 
-       hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
+       hud = new Hud(driver, smgr, guienv, client, player, local_inventory);
 
        if (!hud) {
                *error_message = "Memory error: could not create HUD";
@@ -2232,7 +2013,7 @@ bool Game::createClient(const std::string &playername,
                return false;
        }
 
-       mapper = client->getMapper();
+       mapper = client->getMinimap();
        mapper->setMinimapMode(MINIMAP_MODE_OFF);
 
        return true;
@@ -2354,8 +2135,6 @@ bool Game::connectToServer(const std::string &playername,
        if (!client)
                return false;
 
-       gamedef = client;       // Client acts as our GameDef
-
        infostream << "Connecting to server at ";
        connect_address.print(&infostream);
        infostream << std::endl;
@@ -2376,6 +2155,8 @@ bool Game::connectToServer(const std::string &playername,
 
                fps_control.last_time = device->getTimer()->getTime();
 
+               client->initMods();
+
                while (device->run()) {
 
                        limitFps(&fps_control, &dtime);
@@ -2534,15 +2315,15 @@ bool Game::getServerContent(bool *aborted)
  ****************************************************************************/
 /****************************************************************************/
 
-inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
+inline void Game::updateInteractTimers(f32 dtime)
 {
-       if (runData->nodig_delay_timer >= 0)
-               runData->nodig_delay_timer -= dtime;
+       if (runData.nodig_delay_timer >= 0)
+               runData.nodig_delay_timer -= dtime;
 
-       if (runData->object_hit_delay_timer >= 0)
-               runData->object_hit_delay_timer -= dtime;
+       if (runData.object_hit_delay_timer >= 0)
+               runData.object_hit_delay_timer -= dtime;
 
-       runData->time_from_last_punch += dtime;
+       runData.time_from_last_punch += dtime;
 }
 
 
@@ -2601,13 +2382,12 @@ inline bool Game::handleCallbacks()
 void Game::processQueues()
 {
        texture_src->processQueue();
-       itemdef_manager->processQueue(gamedef);
+       itemdef_manager->processQueue(client);
        shader_src->processQueue();
 }
 
 
-void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
-               const FpsControl &draw_times, f32 dtime)
+void Game::updateProfilers(const RunStats &stats, const FpsControl &draw_times, f32 dtime)
 {
        float profiler_print_interval =
                        g_settings->getFloat("profiler_print_interval");
@@ -2705,13 +2485,10 @@ void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
  Input handling
  ****************************************************************************/
 
-void Game::processUserInput(VolatileRunFlags *flags,
-               GameRunData *runData, f32 dtime)
+void Game::processUserInput(f32 dtime)
 {
        // Reset input if window not active or some menu is active
-       if (device->isWindowActive() == false
-                       || noMenuActive() == false
-                       || guienv->hasFocus(gui_chat_console)) {
+       if (!device->isWindowActive() || !noMenuActive() || guienv->hasFocus(gui_chat_console)) {
                input->clear();
 #ifdef HAVE_TOUCHSCREENGUI
                g_touchscreengui->hide();
@@ -2740,40 +2517,25 @@ void Game::processUserInput(VolatileRunFlags *flags,
 #endif
 
        // Increase timer for double tap of "keymap_jump"
-       if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
-               runData->jump_timer += dtime;
-
-       processKeyInput(
-                       flags,
-                       &runData->statustext_time,
-                       &runData->jump_timer,
-                       &runData->reset_jump_timer,
-                       &runData->profiler_current_page,
-                       runData->profiler_max_page);
-
-       processItemSelection(&runData->new_playeritem);
+       if (m_cache_doubletap_jump && runData.jump_timer <= 0.2f)
+               runData.jump_timer += dtime;
+
+       processKeyInput();
+       processItemSelection(&runData.new_playeritem);
 }
 
 
-void Game::processKeyInput(VolatileRunFlags *flags,
-               float *statustext_time,
-               float *jump_timer,
-               bool *reset_jump_timer,
-               u32 *profiler_current_page,
-               u32 profiler_max_page)
+void Game::processKeyInput()
 {
-
-       //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
-
        if (wasKeyDown(KeyType::DROP)) {
                dropSelectedItem();
        } else if (wasKeyDown(KeyType::AUTORUN)) {
-               toggleAutorun(statustext_time);
+               toggleAutorun();
        } else if (wasKeyDown(KeyType::INVENTORY)) {
                openInventory();
        } else if (wasKeyDown(KeyType::ESC) || input->wasKeyDown(CancelKey)) {
                if (!gui_chat_console->isOpenInhibited()) {
-                       show_pause_menu(&current_formspec, client, gamedef,
+                       show_pause_menu(&current_formspec, client,
                                texture_src, device, &input->joystick,
                                simple_singleplayer_mode);
                }
@@ -2782,41 +2544,43 @@ void Game::processKeyInput(VolatileRunFlags *flags,
        } else if (wasKeyDown(KeyType::CMD)) {
                openConsole(0.2, L"/");
        } else if (wasKeyDown(KeyType::CONSOLE)) {
-               openConsole(1);
+               openConsole(core::clamp(
+                       g_settings->getFloat("console_height"), 0.1f, 1.0f));
        } else if (wasKeyDown(KeyType::FREEMOVE)) {
-               toggleFreeMove(statustext_time);
+               toggleFreeMove();
        } else if (wasKeyDown(KeyType::JUMP)) {
-               toggleFreeMoveAlt(statustext_time, jump_timer);
-               *reset_jump_timer = true;
+               toggleFreeMoveAlt();
+               runData.reset_jump_timer = true;
        } else if (wasKeyDown(KeyType::FASTMOVE)) {
-               toggleFast(statustext_time);
+               toggleFast();
        } else if (wasKeyDown(KeyType::NOCLIP)) {
-               toggleNoClip(statustext_time);
+               toggleNoClip();
        } else if (wasKeyDown(KeyType::CINEMATIC)) {
-               toggleCinematic(statustext_time);
+               toggleCinematic();
        } else if (wasKeyDown(KeyType::SCREENSHOT)) {
                client->makeScreenshot(device);
        } else if (wasKeyDown(KeyType::TOGGLE_HUD)) {
-               toggleHud(statustext_time, &flags->show_hud);
+               toggleHud(&flags.show_hud);
        } else if (wasKeyDown(KeyType::MINIMAP)) {
-               toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
-                       isKeyDown(KeyType::SNEAK));
+               toggleMinimap(&flags.show_minimap, flags.show_hud, isKeyDown(KeyType::SNEAK));
        } else if (wasKeyDown(KeyType::TOGGLE_CHAT)) {
-               toggleChat(statustext_time, &flags->show_chat);
+               toggleChat(&flags.show_chat);
        } else if (wasKeyDown(KeyType::TOGGLE_FORCE_FOG_OFF)) {
-               toggleFog(statustext_time, &flags->force_fog_off);
+               toggleFog(&flags.force_fog_off);
        } else if (wasKeyDown(KeyType::TOGGLE_UPDATE_CAMERA)) {
-               toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
+               toggleUpdateCamera(&flags.disable_camera_update);
        } else if (wasKeyDown(KeyType::TOGGLE_DEBUG)) {
-               toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
+               toggleDebug(&flags.show_debug, &flags.show_profiler_graph,
+                       &draw_control->show_wireframe);
        } else if (wasKeyDown(KeyType::TOGGLE_PROFILER)) {
-               toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
+               toggleProfiler(&runData.profiler_current_page,
+                       runData.profiler_max_page);
        } else if (wasKeyDown(KeyType::INCREASE_VIEWING_RANGE)) {
-               increaseViewRange(statustext_time);
+               increaseViewRange();
        } else if (wasKeyDown(KeyType::DECREASE_VIEWING_RANGE)) {
-               decreaseViewRange(statustext_time);
+               decreaseViewRange();
        } else if (wasKeyDown(KeyType::RANGESELECT)) {
-               toggleFullViewRange(statustext_time);
+               toggleFullViewRange();
        } else if (wasKeyDown(KeyType::QUICKTUNE_NEXT)) {
                quicktune->next();
        } else if (wasKeyDown(KeyType::QUICKTUNE_PREV)) {
@@ -2835,17 +2599,14 @@ void Game::processKeyInput(VolatileRunFlags *flags,
                debug_stacks_print();
        }
 
-       if (!isKeyDown(KeyType::JUMP) && *reset_jump_timer) {
-               *reset_jump_timer = false;
-               *jump_timer = 0.0;
+       if (!isKeyDown(KeyType::JUMP) && runData.reset_jump_timer) {
+               runData.reset_jump_timer = false;
+               runData.jump_timer = 0.0f;
        }
 
-       //tt.stop();
-
        if (quicktune->hasMessage()) {
-               std::string msg = quicktune->getMessage();
-               statustext = utf8_to_wide(msg);
-               *statustext_time = 0;
+               statustext = utf8_to_wide(quicktune->getMessage());
+               runData.statustext_time = 0.0f;
        }
 }
 
@@ -2924,8 +2685,8 @@ void Game::openInventory()
        PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
        TextDest *txt_dst = new TextDestPlayerInventory(client);
 
-       create_formspec_menu(&current_formspec, client, gamedef, texture_src,
-                       device, &input->joystick, fs_src, txt_dst, client);
+       create_formspec_menu(&current_formspec, client, device, &input->joystick, fs_src, txt_dst);
+       cur_formname = "";
 
        InventoryLocation inventoryloc;
        inventoryloc.setCurrentPlayer();
@@ -2933,15 +2694,17 @@ void Game::openInventory()
 }
 
 
-void Game::openConsole(float height, const wchar_t *line)
+void Game::openConsole(float scale, const wchar_t *line)
 {
+       assert(scale > 0.0f && scale <= 1.0f);
+
 #ifdef __ANDROID__
        porting::showInputDialog(gettext("ok"), "", "", 2);
        m_android_chat_open = true;
 #else
        if (gui_chat_console->isOpenInhibited())
                return;
-       gui_chat_console->openConsole(height);
+       gui_chat_console->openConsole(scale);
        if (line) {
                gui_chat_console->setCloseOnEnter(true);
                gui_chat_console->replaceAndAddToHistory(line);
@@ -2960,36 +2723,34 @@ void Game::handleAndroidChatInput()
 #endif
 
 
-void Game::toggleFreeMove(float *statustext_time)
+void Game::toggleFreeMove()
 {
        static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
 
        bool free_move = !g_settings->getBool("free_move");
+       g_settings->set("free_move", bool_to_cstr(free_move));
 
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[free_move];
-       if (free_move && !client->checkPrivilege("fly")) {
+       if (free_move && !client->checkPrivilege("fly"))
                statustext += L" (note: no 'fly' privilege)";
-       } else {
-               g_settings->set("free_move", bool_to_cstr(free_move));
-       }
 }
 
 
-void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
+void Game::toggleFreeMoveAlt()
 {
-       if (m_cache_doubletap_jump && *jump_timer < 0.2f)
-               toggleFreeMove(statustext_time);
+       if (m_cache_doubletap_jump && runData.jump_timer < 0.2f)
+               toggleFreeMove();
 }
 
 
-void Game::toggleFast(float *statustext_time)
+void Game::toggleFast()
 {
        static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
        bool fast_move = !g_settings->getBool("fast_move");
        g_settings->set("fast_move", bool_to_cstr(fast_move));
 
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[fast_move];
 
        bool has_fast_privs = client->checkPrivilege("fast");
@@ -3003,62 +2764,60 @@ void Game::toggleFast(float *statustext_time)
 }
 
 
-void Game::toggleNoClip(float *statustext_time)
+void Game::toggleNoClip()
 {
        static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
        bool noclip = !g_settings->getBool("noclip");
+       g_settings->set("noclip", bool_to_cstr(noclip));
 
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[noclip];
 
-       if (noclip && !client->checkPrivilege("noclip")) {
+       if (noclip && !client->checkPrivilege("noclip"))
                statustext += L" (note: no 'noclip' privilege)";
-       } else {
-               g_settings->set("noclip", bool_to_cstr(noclip));
-       }
 }
 
-void Game::toggleCinematic(float *statustext_time)
+void Game::toggleCinematic()
 {
        static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
        bool cinematic = !g_settings->getBool("cinematic");
        g_settings->set("cinematic", bool_to_cstr(cinematic));
 
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[cinematic];
 }
 
 // Add WoW-style autorun by toggling continuous forward.
-void Game::toggleAutorun(float *statustext_time)
+void Game::toggleAutorun()
 {
        static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
        bool autorun_enabled = !g_settings->getBool("continuous_forward");
        g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
 
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[autorun_enabled ? 1 : 0];
 }
 
-void Game::toggleChat(float *statustext_time, bool *flag)
+void Game::toggleChat(bool *flag)
 {
        static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
 
        *flag = !*flag;
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[*flag];
 }
 
 
-void Game::toggleHud(float *statustext_time, bool *flag)
+void Game::toggleHud(bool *flag)
 {
        static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
 
        *flag = !*flag;
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[*flag];
 }
 
-void Game::toggleMinimap(float *statustext_time, bool *flag,
+void Game::toggleMinimap(bool *flag,
        bool show_hud, bool shift_pressed)
 {
        if (!show_hud || !g_settings->getBool("enable_minimap"))
@@ -3104,43 +2863,53 @@ void Game::toggleMinimap(float *statustext_time, bool *flag,
                                L"Minimap hidden" : L"Minimap disabled by server";
        }
 
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        mapper->setMinimapMode(mode);
 }
 
-void Game::toggleFog(float *statustext_time, bool *flag)
+void Game::toggleFog(bool *flag)
 {
        static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
 
        *flag = !*flag;
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[*flag];
 }
 
 
-void Game::toggleDebug(float *statustext_time, bool *show_debug,
-               bool *show_profiler_graph)
+void Game::toggleDebug(bool *show_debug, bool *show_profiler_graph, bool *show_wireframe)
 {
-       // Initial / 3x toggle: Chat only
+       // Initial / 4x toggle: Chat only
        // 1x toggle: Debug text with chat
        // 2x toggle: Debug text with profiler graph
+       // 3x toggle: Debug text and wireframe
        if (!*show_debug) {
                *show_debug = true;
                *show_profiler_graph = false;
+               *show_wireframe = false;
                statustext = L"Debug info shown";
-       } else if (*show_profiler_graph) {
-               *show_debug = false;
-               *show_profiler_graph = false;
-               statustext = L"Debug info and profiler graph hidden";
-       } else {
+       } else if (!*show_profiler_graph && !*show_wireframe) {
                *show_profiler_graph = true;
                statustext = L"Profiler graph shown";
+       } else if (!*show_wireframe && client->checkPrivilege("debug")) {
+               *show_profiler_graph = false;
+               *show_wireframe = true;
+               statustext = L"Wireframe shown";
+       } else {
+               *show_debug = false;
+               *show_profiler_graph = false;
+               *show_wireframe = false;
+               if (client->checkPrivilege("debug")) {
+                       statustext = L"Debug info, profiler graph, and wireframe hidden";
+               } else {
+                       statustext = L"Debug info and profiler graph hidden";
+               }
        }
-       *statustext_time = 0;
+       runData.statustext_time = 0;
 }
 
 
-void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
+void Game::toggleUpdateCamera(bool *flag)
 {
        static const wchar_t *msg[] = {
                L"Camera update enabled",
@@ -3148,13 +2917,12 @@ void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
        };
 
        *flag = !*flag;
-       *statustext_time = 0;
+       runData.statustext_time = 0;
        statustext = msg[*flag];
 }
 
 
-void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
-               u32 profiler_max_page)
+void Game::toggleProfiler(u32 *profiler_current_page, u32 profiler_max_page)
 {
        *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
 
@@ -3170,37 +2938,47 @@ void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
        } else {
                statustext = L"Profiler hidden";
        }
-       *statustext_time = 0;
+       runData.statustext_time = 0;
 }
 
 
-void Game::increaseViewRange(float *statustext_time)
+void Game::increaseViewRange()
 {
        s16 range = g_settings->getS16("viewing_range");
        s16 range_new = range + 10;
+
+       if (range_new > 4000) {
+               range_new = 4000;
+               statustext = utf8_to_wide("Viewing range is at maximum: "
+                               + itos(range_new));
+       } else {
+               statustext = utf8_to_wide("Viewing range changed to "
+                               + itos(range_new));
+       }
        g_settings->set("viewing_range", itos(range_new));
-       statustext = utf8_to_wide("Viewing range changed to "
-                       + itos(range_new));
-       *statustext_time = 0;
+       runData.statustext_time = 0;
 }
 
 
-void Game::decreaseViewRange(float *statustext_time)
+void Game::decreaseViewRange()
 {
        s16 range = g_settings->getS16("viewing_range");
        s16 range_new = range - 10;
 
-       if (range_new < 20)
+       if (range_new < 20) {
                range_new = 20;
-
+               statustext = utf8_to_wide("Viewing range is at minimum: "
+                               + itos(range_new));
+       } else {
+               statustext = utf8_to_wide("Viewing range changed to "
+                               + itos(range_new));
+       }
        g_settings->set("viewing_range", itos(range_new));
-       statustext = utf8_to_wide("Viewing range changed to "
-                       + itos(range_new));
-       *statustext_time = 0;
+       runData.statustext_time = 0;
 }
 
 
-void Game::toggleFullViewRange(float *statustext_time)
+void Game::toggleFullViewRange()
 {
        static const wchar_t *msg[] = {
                L"Disabled full viewing range",
@@ -3210,7 +2988,7 @@ void Game::toggleFullViewRange(float *statustext_time)
        draw_control->range_all = !draw_control->range_all;
        infostream << msg[draw_control->range_all] << std::endl;
        statustext = msg[draw_control->range_all];
-       *statustext_time = 0;
+       runData.statustext_time = 0;
 }
 
 
@@ -3253,8 +3031,8 @@ void Game::updateCameraOrientation(CameraOrientation *cam,
 {
 #ifdef HAVE_TOUCHSCREENGUI
        if (g_touchscreengui) {
-               cam->camera_yaw   = g_touchscreengui->getYaw();
-               cam->camera_pitch = g_touchscreengui->getPitch();
+               cam->camera_yaw   += g_touchscreengui->getYawChange();
+               cam->camera_pitch  = g_touchscreengui->getPitch();
        } else {
 #endif
 
@@ -3361,7 +3139,7 @@ inline void Game::step(f32 *dtime)
 }
 
 
-void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
+void Game::processClientEvents(CameraOrientation *cam)
 {
        ClientEvent event = client->getClientEvent();
 
@@ -3369,55 +3147,64 @@ void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
 
        for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
 
-               if (event.type == CE_PLAYER_DAMAGE &&
-                               client->getHP() != 0) {
-                       //u16 damage = event.player_damage.amount;
-                       //infostream<<"Player damage: "<<damage<<std::endl;
+               if (event.type == CE_PLAYER_DAMAGE && client->getHP() != 0) {
+                       if (client->moddingEnabled()) {
+                               client->getScript()->on_damage_taken(event.player_damage.amount);
+                       }
 
-                       *damage_flash += 100.0;
-                       *damage_flash += 8.0 * event.player_damage.amount;
+                       runData.damage_flash += 95.0 + 3.2 * event.player_damage.amount;
+                       runData.damage_flash = MYMIN(runData.damage_flash, 127.0);
 
                        player->hurt_tilt_timer = 1.5;
-                       player->hurt_tilt_strength = event.player_damage.amount / 4;
-                       player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
+                       player->hurt_tilt_strength =
+                               rangelim(event.player_damage.amount / 4, 1.0, 4.0);
 
                        MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
-                       gamedef->event()->put(e);
+                       client->event()->put(e);
                } else if (event.type == CE_PLAYER_FORCE_MOVE) {
                        cam->camera_yaw = event.player_force_move.yaw;
                        cam->camera_pitch = event.player_force_move.pitch;
                } else if (event.type == CE_DEATHSCREEN) {
-                       show_deathscreen(&current_formspec, client, gamedef, texture_src,
-                               device, &input->joystick, client);
-
-                       chat_backend->addMessage(L"", L"You died.");
+                       // This should be enabled for death formspec in builtin
+                       client->getScript()->on_death();
 
                        /* Handle visualization */
-                       *damage_flash = 0;
+                       runData.damage_flash = 0;
                        player->hurt_tilt_timer = 0;
                        player->hurt_tilt_strength = 0;
 
                } else if (event.type == CE_SHOW_FORMSPEC) {
-                       FormspecFormSource *fs_src =
-                               new FormspecFormSource(*(event.show_formspec.formspec));
-                       TextDestPlayerInventory *txt_dst =
-                               new TextDestPlayerInventory(client, *(event.show_formspec.formname));
-
-                       create_formspec_menu(&current_formspec, client, gamedef,
-                               texture_src, device, &input->joystick,
-                               fs_src, txt_dst, client);
+                       if (*(event.show_formspec.formspec) == "") {
+                               if (current_formspec && ( *(event.show_formspec.formname) == "" || *(event.show_formspec.formname) == cur_formname) ){
+                                       current_formspec->quitMenu();
+                               }
+                       } else {
+                               FormspecFormSource *fs_src =
+                                       new FormspecFormSource(*(event.show_formspec.formspec));
+                               TextDestPlayerInventory *txt_dst =
+                                       new TextDestPlayerInventory(client, *(event.show_formspec.formname));
+
+                               create_formspec_menu(&current_formspec, client, device, &input->joystick,
+                                       fs_src, txt_dst);
+                               cur_formname = *(event.show_formspec.formname);
+                       }
 
                        delete(event.show_formspec.formspec);
                        delete(event.show_formspec.formname);
+               } else if (event.type == CE_SHOW_LOCAL_FORMSPEC) {
+                       FormspecFormSource *fs_src = new FormspecFormSource(*event.show_formspec.formspec);
+                       LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event.show_formspec.formname, client);
+                       create_formspec_menu(&current_formspec, client, device, &input->joystick,
+                               fs_src, txt_dst);
+                       delete event.show_formspec.formspec;
+                       delete event.show_formspec.formname;
                } else if ((event.type == CE_SPAWN_PARTICLE) ||
                                (event.type == CE_ADD_PARTICLESPAWNER) ||
                                (event.type == CE_DELETE_PARTICLESPAWNER)) {
-                       client->getParticleManager()->handleParticleEvent(&event, gamedef,
+                       client->getParticleManager()->handleParticleEvent(&event, client,
                                        smgr, player);
                } else if (event.type == CE_HUDADD) {
                        u32 id = event.hudadd.id;
-
-                       LocalPlayer *player = client->getEnv().getLocalPlayer();
                        HudElement *e = player->getHud(id);
 
                        if (e != NULL) {
@@ -3568,8 +3355,7 @@ void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
 }
 
 
-void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
-               f32 dtime, float time_from_last_punch)
+void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime)
 {
        LocalPlayer *player = client->getEnv().getLocalPlayer();
 
@@ -3587,6 +3373,13 @@ void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
                        playeritem = mlist->getItem(client->getPlayerItem());
        }
 
+       if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
+               InventoryList *hlist = local_inventory->getList("hand");
+               if (hlist)
+                       playeritem = hlist->getItem(0);
+       }
+
+
        ToolCapabilities playeritem_toolcap =
                playeritem.getToolCapabilities(itemdef_manager);
 
@@ -3606,7 +3399,7 @@ void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
        }
 
        float full_punch_interval = playeritem_toolcap.full_punch_interval;
-       float tool_reload_ratio = time_from_last_punch / full_punch_interval;
+       float tool_reload_ratio = runData.time_from_last_punch / full_punch_interval;
 
        tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
        camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
@@ -3652,13 +3445,12 @@ void Game::updateSound(f32 dtime)
        LocalPlayer *player = client->getEnv().getLocalPlayer();
 
        ClientMap &map = client->getEnv().getClientMap();
-       MapNode n = map.getNodeNoEx(player->getStandingNodePos());
+       MapNode n = map.getNodeNoEx(player->getFootstepNodePos());
        soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
 }
 
 
-void Game::processPlayerInteraction(GameRunData *runData,
-               f32 dtime, bool show_hud, bool show_debug)
+void Game::processPlayerInteraction(f32 dtime, bool show_hud, bool show_debug)
 {
        LocalPlayer *player = client->getEnv().getLocalPlayer();
 
@@ -3670,6 +3462,11 @@ void Game::processPlayerInteraction(GameRunData *runData,
                        playeritem = mlist->getItem(client->getPlayerItem());
        }
 
+       if (playeritem.getDefinition(itemdef_manager).name.empty()) { // override the hand
+               InventoryList *hlist = local_inventory->getList("hand");
+               if (hlist)
+                       playeritem = hlist->getItem(0);
+       }
        const ItemDefinition &playeritem_def =
                        playeritem.getDefinition(itemdef_manager);
 
@@ -3694,14 +3491,11 @@ void Game::processPlayerInteraction(GameRunData *runData,
        core::line3d<f32> shootline;
 
        if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
-
                shootline = core::line3d<f32>(camera_position,
-                                               camera_position + camera_direction * BS * (d + 1));
-
+                       camera_position + camera_direction * BS * d);
        } else {
            // prevent player pointing anything in front-view
-               if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
-                       shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
+               shootline = core::line3d<f32>(camera_position,camera_position);
        }
 
 #ifdef HAVE_TOUCHSCREENGUI
@@ -3714,17 +3508,14 @@ void Game::processPlayerInteraction(GameRunData *runData,
 
 #endif
 
-       PointedThing pointed = getPointedThing(
-                       // input
-                       client, hud, player_position, camera_direction,
-                       camera_position, shootline, d,
+       PointedThing pointed = updatePointedThing(shootline,
                        playeritem_def.liquids_pointable,
-                       !runData->ldown_for_dig,
+                       !runData.ldown_for_dig,
                        camera_offset,
                        // output
-                       runData->selected_object);
+                       runData.selected_object);
 
-       if (pointed != runData->pointed_old) {
+       if (pointed != runData.pointed_old) {
                infostream << "Pointing at " << pointed.dump() << std::endl;
                hud->updateSelectionMesh(camera_offset);
        }
@@ -3734,45 +3525,45 @@ void Game::processPlayerInteraction(GameRunData *runData,
                - releasing left mouse button
                - pointing away from node
        */
-       if (runData->digging) {
+       if (runData.digging) {
                if (getLeftReleased()) {
                        infostream << "Left button released"
                                   << " (stopped digging)" << std::endl;
-                       runData->digging = false;
-               } else if (pointed != runData->pointed_old) {
+                       runData.digging = false;
+               } else if (pointed != runData.pointed_old) {
                        if (pointed.type == POINTEDTHING_NODE
-                                       && runData->pointed_old.type == POINTEDTHING_NODE
+                                       && runData.pointed_old.type == POINTEDTHING_NODE
                                        && pointed.node_undersurface
-                                                       == runData->pointed_old.node_undersurface) {
+                                                       == runData.pointed_old.node_undersurface) {
                                // Still pointing to the same node, but a different face.
                                // Don't reset.
                        } else {
                                infostream << "Pointing away from node"
                                           << " (stopped digging)" << std::endl;
-                               runData->digging = false;
+                               runData.digging = false;
                                hud->updateSelectionMesh(camera_offset);
                        }
                }
 
-               if (!runData->digging) {
-                       client->interact(1, runData->pointed_old);
+               if (!runData.digging) {
+                       client->interact(1, runData.pointed_old);
                        client->setCrack(-1, v3s16(0, 0, 0));
-                       runData->dig_time = 0.0;
+                       runData.dig_time = 0.0;
                }
        }
 
-       if (!runData->digging && runData->ldown_for_dig && !isLeftPressed()) {
-               runData->ldown_for_dig = false;
+       if (!runData.digging && runData.ldown_for_dig && !isLeftPressed()) {
+               runData.ldown_for_dig = false;
        }
 
-       runData->left_punch = false;
+       runData.left_punch = false;
 
        soundmaker->m_player_leftpunch_sound.name = "";
 
        if (isRightPressed())
-               runData->repeat_rightclick_timer += dtime;
+               runData.repeat_rightclick_timer += dtime;
        else
-               runData->repeat_rightclick_timer = 0;
+               runData.repeat_rightclick_timer = 0;
 
        if (playeritem_def.usable && isLeftPressed()) {
                if (getLeftClicked())
@@ -3780,21 +3571,19 @@ void Game::processPlayerInteraction(GameRunData *runData,
        } else if (pointed.type == POINTEDTHING_NODE) {
                ToolCapabilities playeritem_toolcap =
                                playeritem.getToolCapabilities(itemdef_manager);
-               handlePointingAtNode(runData, pointed, playeritem_def,
-                               playeritem_toolcap, dtime);
+               handlePointingAtNode(pointed, playeritem_def, playeritem_toolcap, dtime);
        } else if (pointed.type == POINTEDTHING_OBJECT) {
-               handlePointingAtObject(runData, pointed, playeritem,
-                               player_position, show_debug);
+               handlePointingAtObject(pointed, playeritem, player_position, show_debug);
        } else if (isLeftPressed()) {
                // When button is held down in air, show continuous animation
-               runData->left_punch = true;
+               runData.left_punch = true;
        } else if (getRightClicked()) {
-               handlePointingAtNothing(runData, playeritem);
+               handlePointingAtNothing(playeritem);
        }
 
-       runData->pointed_old = pointed;
+       runData.pointed_old = pointed;
 
-       if (runData->left_punch || getLeftClicked())
+       if (runData.left_punch || getLeftClicked())
                camera->setDigging(0); // left click animation
 
        input->resetLeftClicked();
@@ -3811,7 +3600,108 @@ void Game::processPlayerInteraction(GameRunData *runData,
 }
 
 
-void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
+PointedThing Game::updatePointedThing(
+       const core::line3d<f32> &shootline,
+       bool liquids_pointable,
+       bool look_for_object,
+       const v3s16 &camera_offset,
+       ClientActiveObject *&selected_object)
+{
+       std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
+       selectionboxes->clear();
+       hud->setSelectedFaceNormal(v3f(0.0, 0.0, 0.0));
+       static const bool show_entity_selectionbox = g_settings->getBool(
+               "show_entity_selectionbox");
+
+       ClientMap &map = client->getEnv().getClientMap();
+       INodeDefManager *nodedef=client->getNodeDefManager();
+
+       selected_object = NULL;
+
+       PointedThing result=client->getEnv().getPointedThing(
+               shootline, liquids_pointable, look_for_object);
+       if (result.type == POINTEDTHING_OBJECT) {
+               selected_object = client->getEnv().getActiveObject(result.object_id);
+               if (show_entity_selectionbox && selected_object->doShowSelectionBox()) {
+                       aabb3f *selection_box = selected_object->getSelectionBox();
+
+                       // Box should exist because object was
+                       // returned in the first place
+
+                       assert(selection_box);
+
+                       v3f pos = selected_object->getPosition();
+                       selectionboxes->push_back(aabb3f(
+                               selection_box->MinEdge, selection_box->MaxEdge));
+                       selectionboxes->push_back(
+                               aabb3f(selection_box->MinEdge, selection_box->MaxEdge));
+                       hud->setSelectionPos(pos, camera_offset);
+               }
+       } else if (result.type == POINTEDTHING_NODE) {
+               // Update selection boxes
+               MapNode n = map.getNodeNoEx(result.node_undersurface);
+               std::vector<aabb3f> boxes;
+               n.getSelectionBoxes(nodedef, &boxes,
+                       n.getNeighbors(result.node_undersurface, &map));
+
+               f32 d = 0.002 * BS;
+               for (std::vector<aabb3f>::const_iterator i = boxes.begin();
+                       i != boxes.end(); ++i) {
+                       aabb3f box = *i;
+                       box.MinEdge -= v3f(d, d, d);
+                       box.MaxEdge += v3f(d, d, d);
+                       selectionboxes->push_back(box);
+               }
+               hud->setSelectionPos(intToFloat(result.node_undersurface, BS),
+                       camera_offset);
+               hud->setSelectedFaceNormal(v3f(
+                       result.intersection_normal.X,
+                       result.intersection_normal.Y,
+                       result.intersection_normal.Z));
+       }
+
+       // Update selection mesh light level and vertex colors
+       if (selectionboxes->size() > 0) {
+               v3f pf = hud->getSelectionPos();
+               v3s16 p = floatToInt(pf, BS);
+
+               // Get selection mesh light level
+               MapNode n = map.getNodeNoEx(p);
+               u16 node_light = getInteriorLight(n, -1, nodedef);
+               u16 light_level = node_light;
+
+               for (u8 i = 0; i < 6; i++) {
+                       n = map.getNodeNoEx(p + g_6dirs[i]);
+                       node_light = getInteriorLight(n, -1, nodedef);
+                       if (node_light > light_level)
+                               light_level = node_light;
+               }
+
+               u32 daynight_ratio = client->getEnv().getDayNightRatio();
+               video::SColor c;
+               final_color_blend(&c, light_level, daynight_ratio);
+
+               // Modify final color a bit with time
+               u32 timer = porting::getTimeMs() % 5000;
+               float timerf = (float) (irr::core::PI * ((timer / 2500.0) - 0.5));
+               float sin_r = 0.08 * sin(timerf);
+               float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
+               float sin_b = 0.08 * sin(timerf + irr::core::PI);
+               c.setRed(
+                       core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
+               c.setGreen(
+                       core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
+               c.setBlue(
+                       core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
+
+               // Set mesh final color
+               hud->setSelectionMeshColor(c);
+       }
+       return result;
+}
+
+
+void Game::handlePointingAtNothing(const ItemStack &playerItem)
 {
        infostream << "Right Clicked in Air" << std::endl;
        PointedThing fauxPointed;
@@ -3820,8 +3710,7 @@ void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &player
 }
 
 
-void Game::handlePointingAtNode(GameRunData *runData,
-               const PointedThing &pointed, const ItemDefinition &playeritem_def,
+void Game::handlePointingAtNode(const PointedThing &pointed, const ItemDefinition &playeritem_def,
                const ToolCapabilities &playeritem_toolcap, f32 dtime)
 {
        v3s16 nodepos = pointed.node_undersurface;
@@ -3845,15 +3734,15 @@ void Game::handlePointingAtNode(GameRunData *runData,
                }
        }
 
-       if (runData->nodig_delay_timer <= 0.0 && isLeftPressed()
+       if (runData.nodig_delay_timer <= 0.0 && isLeftPressed()
                        && client->checkPrivilege("interact")) {
-               handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
+               handleDigging(pointed, nodepos, playeritem_toolcap, dtime);
        }
 
        if ((getRightClicked() ||
-                       runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
+                       runData.repeat_rightclick_timer >= m_repeat_right_click_time) &&
                        client->checkPrivilege("interact")) {
-               runData->repeat_rightclick_timer = 0;
+               runData.repeat_rightclick_timer = 0;
                infostream << "Ground right-clicked" << std::endl;
 
                if (meta && meta->getString("formspec") != "" && !random_input
@@ -3867,8 +3756,9 @@ void Game::handlePointingAtNode(GameRunData *runData,
                                &client->getEnv().getClientMap(), nodepos);
                        TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
 
-                       create_formspec_menu(&current_formspec, client, gamedef,
-                               texture_src, device, &input->joystick, fs_src, txt_dst, client);
+                       create_formspec_menu(&current_formspec, client,
+                                       device, &input->joystick, fs_src, txt_dst);
+                       cur_formname = "";
 
                        current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
                } else {
@@ -3905,31 +3795,28 @@ void Game::handlePointingAtNode(GameRunData *runData,
 }
 
 
-void Game::handlePointingAtObject(GameRunData *runData,
-               const PointedThing &pointed,
-               const ItemStack &playeritem,
-               const v3f &player_position,
-               bool show_debug)
+void Game::handlePointingAtObject(const PointedThing &pointed, const ItemStack &playeritem,
+               const v3f &player_position, bool show_debug)
 {
        infotext = unescape_enriched(
-               utf8_to_wide(runData->selected_object->infoText()));
+               utf8_to_wide(runData.selected_object->infoText()));
 
        if (show_debug) {
                if (infotext != L"") {
                        infotext += L"\n";
                }
                infotext += unescape_enriched(utf8_to_wide(
-                       runData->selected_object->debugInfoText()));
+                       runData.selected_object->debugInfoText()));
        }
 
        if (isLeftPressed()) {
                bool do_punch = false;
                bool do_punch_damage = false;
 
-               if (runData->object_hit_delay_timer <= 0.0) {
+               if (runData.object_hit_delay_timer <= 0.0) {
                        do_punch = true;
                        do_punch_damage = true;
-                       runData->object_hit_delay_timer = object_hit_delay;
+                       runData.object_hit_delay_timer = object_hit_delay;
                }
 
                if (getLeftClicked())
@@ -3937,17 +3824,17 @@ void Game::handlePointingAtObject(GameRunData *runData,
 
                if (do_punch) {
                        infostream << "Left-clicked object" << std::endl;
-                       runData->left_punch = true;
+                       runData.left_punch = true;
                }
 
                if (do_punch_damage) {
                        // Report direct punch
-                       v3f objpos = runData->selected_object->getPosition();
+                       v3f objpos = runData.selected_object->getPosition();
                        v3f dir = (objpos - player_position).normalize();
 
-                       bool disable_send = runData->selected_object->directReportPunch(
-                                       dir, &playeritem, runData->time_from_last_punch);
-                       runData->time_from_last_punch = 0;
+                       bool disable_send = runData.selected_object->directReportPunch(
+                                       dir, &playeritem, runData.time_from_last_punch);
+                       runData.time_from_last_punch = 0;
 
                        if (!disable_send)
                                client->interact(0, pointed);
@@ -3959,21 +3846,22 @@ void Game::handlePointingAtObject(GameRunData *runData,
 }
 
 
-void Game::handleDigging(GameRunData *runData,
-               const PointedThing &pointed, const v3s16 &nodepos,
+void Game::handleDigging(const PointedThing &pointed, const v3s16 &nodepos,
                const ToolCapabilities &playeritem_toolcap, f32 dtime)
 {
-       if (!runData->digging) {
-               infostream << "Started digging" << std::endl;
-               client->interact(0, pointed);
-               runData->digging = true;
-               runData->ldown_for_dig = true;
-       }
-
        LocalPlayer *player = client->getEnv().getLocalPlayer();
        ClientMap &map = client->getEnv().getClientMap();
        MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
 
+       if (!runData.digging) {
+               infostream << "Started digging" << std::endl;
+               if (client->moddingEnabled() && client->getScript()->on_punchnode(nodepos, n))
+                       return;
+               client->interact(0, pointed);
+               runData.digging = true;
+               runData.ldown_for_dig = true;
+       }
+
        // NOTE: Similar piece of code exists on the server side for
        // cheat detection.
        // Get digging parameters
@@ -3989,27 +3877,27 @@ void Game::handleDigging(GameRunData *runData,
                        params = getDigParams(nodedef_manager->get(n).groups, tp);
        }
 
-       if (params.diggable == false) {
+       if (!params.diggable) {
                // I guess nobody will wait for this long
-               runData->dig_time_complete = 10000000.0;
+               runData.dig_time_complete = 10000000.0;
        } else {
-               runData->dig_time_complete = params.time;
+               runData.dig_time_complete = params.time;
 
                if (m_cache_enable_particles) {
                        const ContentFeatures &features =
                                        client->getNodeDefManager()->get(n);
-                       client->getParticleManager()->addPunchingParticles(gamedef, smgr,
-                                       player, nodepos, features.tiles);
+                       client->getParticleManager()->addPunchingParticles(client, smgr,
+                                       player, nodepos, n, features);
                }
        }
 
-       if (runData->dig_time_complete >= 0.001) {
-               runData->dig_index = (float)crack_animation_length
-                               * runData->dig_time
-                               / runData->dig_time_complete;
+       if (runData.dig_time_complete >= 0.001) {
+               runData.dig_index = (float)crack_animation_length
+                               * runData.dig_time
+                               / runData.dig_time_complete;
        } else {
                // This is for torches
-               runData->dig_index = crack_animation_length;
+               runData.dig_index = crack_animation_length;
        }
 
        SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
@@ -4028,54 +3916,63 @@ void Game::handleDigging(GameRunData *runData,
        }
 
        // Don't show cracks if not diggable
-       if (runData->dig_time_complete >= 100000.0) {
-       } else if (runData->dig_index < crack_animation_length) {
+       if (runData.dig_time_complete >= 100000.0) {
+       } else if (runData.dig_index < crack_animation_length) {
                //TimeTaker timer("client.setTempMod");
                //infostream<<"dig_index="<<dig_index<<std::endl;
-               client->setCrack(runData->dig_index, nodepos);
+               client->setCrack(runData.dig_index, nodepos);
        } else {
                infostream << "Digging completed" << std::endl;
-               client->interact(2, pointed);
                client->setCrack(-1, v3s16(0, 0, 0));
-               bool is_valid_position;
-               MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
-               if (is_valid_position)
-                       client->removeNode(nodepos);
-
-               if (m_cache_enable_particles) {
-                       const ContentFeatures &features =
-                               client->getNodeDefManager()->get(wasnode);
-                       client->getParticleManager()->addDiggingParticles(gamedef, smgr,
-                                       player, nodepos, features.tiles);
-               }
 
-               runData->dig_time = 0;
-               runData->digging = false;
+               runData.dig_time = 0;
+               runData.digging = false;
 
-               runData->nodig_delay_timer =
-                               runData->dig_time_complete / (float)crack_animation_length;
+               runData.nodig_delay_timer =
+                               runData.dig_time_complete / (float)crack_animation_length;
 
                // We don't want a corresponding delay to
                // very time consuming nodes
-               if (runData->nodig_delay_timer > 0.3)
-                       runData->nodig_delay_timer = 0.3;
+               if (runData.nodig_delay_timer > 0.3)
+                       runData.nodig_delay_timer = 0.3;
 
                // We want a slight delay to very little
                // time consuming nodes
                const float mindelay = 0.15;
 
-               if (runData->nodig_delay_timer < mindelay)
-                       runData->nodig_delay_timer = mindelay;
+               if (runData.nodig_delay_timer < mindelay)
+                       runData.nodig_delay_timer = mindelay;
+
+               bool is_valid_position;
+               MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
+               if (is_valid_position) {
+                       if (client->moddingEnabled()) {
+                               if (client->getScript()->on_dignode(nodepos, wasnode)) {
+                                       return;
+                               }
+                       }
+                       client->removeNode(nodepos);
+               }
+
+               client->interact(2, pointed);
+
+               if (m_cache_enable_particles) {
+                       const ContentFeatures &features =
+                               client->getNodeDefManager()->get(wasnode);
+                       client->getParticleManager()->addDiggingParticles(client, smgr,
+                               player, nodepos, wasnode, features);
+               }
+
 
                // Send event to trigger sound
                MtEvent *e = new NodeDugEvent(nodepos, wasnode);
-               gamedef->event()->put(e);
+               client->event()->put(e);
        }
 
-       if (runData->dig_time_complete < 100000.0) {
-               runData->dig_time += dtime;
+       if (runData.dig_time_complete < 100000.0) {
+               runData.dig_time += dtime;
        } else {
-               runData->dig_time = 0;
+               runData.dig_time = 0;
                client->setCrack(-1, nodepos);
        }
 
@@ -4083,9 +3980,8 @@ void Game::handleDigging(GameRunData *runData,
 }
 
 
-void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
-               GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
-               const CameraOrientation &cam)
+void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime,
+               const VolatileRunFlags &flags, const CameraOrientation &cam)
 {
        LocalPlayer *player = client->getEnv().getLocalPlayer();
 
@@ -4094,9 +3990,9 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
        */
 
        if (draw_control->range_all) {
-               runData->fog_range = 100000 * BS;
+               runData.fog_range = 100000 * BS;
        } else {
-               runData->fog_range = 0.9 * draw_control->wanted_range * BS;
+               runData.fog_range = draw_control->wanted_range * BS;
        }
 
        /*
@@ -4114,13 +4010,13 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
                ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
                float old_brightness = sky->getBrightness();
                direct_brightness = client->getEnv().getClientMap()
-                               .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
+                               .getBackgroundBrightness(MYMIN(runData.fog_range * 1.2, 60 * BS),
                                        daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
                                    / 255.0;
        }
 
-       float time_of_day = runData->time_of_day;
-       float time_of_day_smooth = runData->time_of_day_smooth;
+       float time_of_day = runData.time_of_day;
+       float time_of_day_smooth = runData.time_of_day_smooth;
 
        time_of_day = client->getEnv().getTimeOfDayF();
 
@@ -4139,8 +4035,8 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
                time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
                                + time_of_day * todsm;
 
-       runData->time_of_day = time_of_day;
-       runData->time_of_day_smooth = time_of_day_smooth;
+       runData.time_of_day = time_of_day;
+       runData.time_of_day_smooth = time_of_day_smooth;
 
        sky->update(time_of_day_smooth, time_brightness, direct_brightness,
                        sunlight_seen, camera->getCameraMode(), player->getYaw(),
@@ -4174,8 +4070,8 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
                driver->setFog(
                                sky->getBgColor(),
                                video::EFT_FOG_LINEAR,
-                               runData->fog_range * 0.4,
-                               runData->fog_range * 1.0,
+                               runData.fog_range * m_cache_fog_start,
+                               runData.fog_range * 1.0,
                                0.01,
                                false, // pixel fog
                                true // range fog
@@ -4199,50 +4095,56 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
        v2u32 screensize = driver->getScreenSize();
 
        updateChat(*client, dtime, flags.show_debug, screensize,
-                       flags.show_chat, runData->profiler_current_page,
+                       flags.show_chat, runData.profiler_current_page,
                        *chat_backend, guitext_chat);
 
        /*
                Inventory
        */
 
-       if (client->getPlayerItem() != runData->new_playeritem)
-               client->selectPlayerItem(runData->new_playeritem);
+       if (client->getPlayerItem() != runData.new_playeritem)
+               client->selectPlayerItem(runData.new_playeritem);
 
        // Update local inventory if it has changed
        if (client->getLocalInventoryUpdated()) {
                //infostream<<"Updating local inventory"<<std::endl;
                client->getLocalInventory(*local_inventory);
-               runData->update_wielded_item_trigger = true;
+               runData.update_wielded_item_trigger = true;
        }
 
-       if (runData->update_wielded_item_trigger) {
+       if (runData.update_wielded_item_trigger) {
                // Update wielded tool
                InventoryList *mlist = local_inventory->getList("main");
 
                if (mlist && (client->getPlayerItem() < mlist->getSize())) {
                        ItemStack item = mlist->getItem(client->getPlayerItem());
+                       if (item.getDefinition(itemdef_manager).name.empty()) { // override the hand
+                               InventoryList *hlist = local_inventory->getList("hand");
+                               if (hlist)
+                                       item = hlist->getItem(0);
+                       }
                        camera->wield(item);
                }
-               runData->update_wielded_item_trigger = false;
+
+               runData.update_wielded_item_trigger = false;
        }
 
        /*
                Update block draw list every 200ms or when camera direction has
                changed much
        */
-       runData->update_draw_list_timer += dtime;
+       runData.update_draw_list_timer += dtime;
 
        v3f camera_direction = camera->getDirection();
-       if (runData->update_draw_list_timer >= 0.2
-                       || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
+       if (runData.update_draw_list_timer >= 0.2
+                       || runData.update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
                        || flags.camera_offset_changed) {
-               runData->update_draw_list_timer = 0;
+               runData.update_draw_list_timer = 0;
                client->getEnv().getClientMap().updateDrawList(driver);
-               runData->update_draw_list_last_cam_dir = camera_direction;
+               runData.update_draw_list_last_cam_dir = camera_direction;
        }
 
-       updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
+       updateGui(*stats, dtime, flags, cam);
 
        /*
           make sure menu is on top
@@ -4284,16 +4186,13 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
        /*
                Damage flash
        */
-       if (runData->damage_flash > 0.0) {
-               video::SColor color(std::min(runData->damage_flash, 180.0f),
-                               180,
-                               0,
-                               0);
+       if (runData.damage_flash > 0.0) {
+               video::SColor color(runData.damage_flash, 180, 0, 0);
                driver->draw2DRectangle(color,
                                        core::rect<s32>(0, 0, screensize.X, screensize.Y),
                                        NULL);
 
-               runData->damage_flash -= 100.0 * dtime;
+               runData.damage_flash -= 100.0 * dtime;
        }
 
        /*
@@ -4339,8 +4238,7 @@ inline static const char *yawToDirectionString(int yaw)
 }
 
 
-void Game::updateGui(float *statustext_time, const RunStats &stats,
-               const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
+void Game::updateGui(const RunStats &stats, f32 dtime, const VolatileRunFlags &flags,
                const CameraOrientation &cam)
 {
        v2u32 screensize = driver->getScreenSize();
@@ -4352,7 +4250,6 @@ void Game::updateGui(float *statustext_time, const RunStats &stats,
                drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
 
                u16 fps = 1.0 / stats.dtime_jitter.avg;
-               //s32 fps = driver->getFPS();
 
                std::ostringstream os(std::ios_base::binary);
                os << std::fixed
@@ -4423,11 +4320,11 @@ void Game::updateGui(float *statustext_time, const RunStats &stats,
        float statustext_time_max = 1.5;
 
        if (!statustext.empty()) {
-               *statustext_time += dtime;
+               runData.statustext_time += dtime;
 
-               if (*statustext_time >= statustext_time_max) {
+               if (runData.statustext_time >= statustext_time_max) {
                        statustext = L"";
-                       *statustext_time = 0;
+                       runData.statustext_time = 0;
                }
        }
 
@@ -4455,7 +4352,7 @@ void Game::updateGui(float *statustext_time, const RunStats &stats,
                final_color.setAlpha(0);
                video::SColor fade_color = initial_color.getInterpolated_quadratic(
                                initial_color, final_color,
-                               pow(*statustext_time / statustext_time_max, 2.0f));
+                               pow(runData.statustext_time / statustext_time_max, 2.0f));
                guitext_status->setOverrideColor(fade_color);
                guitext_status->enableOverrideColor(true);
        }
@@ -4547,7 +4444,18 @@ void Game::readSettings()
        m_cache_enable_noclip                = g_settings->getBool("noclip");
        m_cache_enable_free_move             = g_settings->getBool("free_move");
 
+       m_cache_fog_start                    = g_settings->getFloat("fog_start");
+
+       m_cache_cam_smoothing = 0;
+       if (g_settings->getBool("cinematic"))
+               m_cache_cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
+       else
+               m_cache_cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
+
+       m_cache_fog_start = rangelim(m_cache_fog_start, 0.0f, 0.99f);
+       m_cache_cam_smoothing = rangelim(m_cache_cam_smoothing, 0.01f, 1.0f);
        m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
+
 }
 
 /****************************************************************************/