]> git.lizzy.rs Git - minetest.git/blobdiff - src/server.cpp
Initial directory structure rework
[minetest.git] / src / server.cpp
index 70638a0a6f79cede78c9fca003ff34184b5c6daa..69f655e6acd7b244a2bc4a7cdd62dca0f8d96281 100644 (file)
@@ -27,13 +27,10 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "main.h"
 #include "constants.h"
 #include "voxel.h"
-#include "materials.h"
-#include "mineral.h"
 #include "config.h"
 #include "servercommand.h"
 #include "filesys.h"
 #include "content_mapnode.h"
-#include "content_craft.h"
 #include "content_nodemeta.h"
 #include "mapblock.h"
 #include "serverobject.h"
@@ -43,11 +40,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "script.h"
 #include "scriptapi.h"
 #include "nodedef.h"
-#include "tooldef.h"
+#include "itemdef.h"
 #include "craftdef.h"
-#include "craftitemdef.h"
 #include "mapgen.h"
 #include "content_abm.h"
+#include "mods.h"
+#include "sha1.h"
+#include "base64.h"
+#include "tool.h"
 
 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
 
@@ -249,7 +249,7 @@ void * EmergeThread::Thread()
                                        t.stop(true); // Hide output
                        }
                        
-                       {
+                       do{ // enable break
                                // Lock environment again to access the map
                                JMutexAutoLock envlock(m_server->m_env_mutex);
                                
@@ -262,6 +262,11 @@ void * EmergeThread::Thread()
 
                                // Get central block
                                block = map.getBlockNoCreateNoEx(p);
+                               
+                               // If block doesn't exist, don't try doing anything with it
+                               // This happens if the block is not in generation boundaries
+                               if(!block)
+                                       break;
 
                                /*
                                        Do some post-generate stuff
@@ -285,7 +290,7 @@ void * EmergeThread::Thread()
                                
                                // Activate objects and stuff
                                m_server->m_env->activateBlock(block, 0);
-                       }
+                       }while(false);
                }
 
                if(block == NULL)
@@ -749,105 +754,6 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                infostream<<"GetNextBlocks duration: "<<timer_result<<" (!=0)"<<std::endl;*/
 }
 
-void RemoteClient::SendObjectData(
-               Server *server,
-               float dtime,
-               core::map<v3s16, bool> &stepped_blocks
-       )
-{
-       DSTACK(__FUNCTION_NAME);
-
-       // Can't send anything without knowing version
-       if(serialization_version == SER_FMT_VER_INVALID)
-       {
-               infostream<<"RemoteClient::SendObjectData(): Not sending, no version."
-                               <<std::endl;
-               return;
-       }
-
-       /*
-               Send a TOCLIENT_OBJECTDATA packet.
-               Sent as unreliable.
-
-               u16 command
-               u16 number of player positions
-               for each player:
-                       u16 peer_id
-                       v3s32 position*100
-                       v3s32 speed*100
-                       s32 pitch*100
-                       s32 yaw*100
-               u16 count of blocks
-               for each block:
-                       block objects
-       */
-
-       std::ostringstream os(std::ios_base::binary);
-       u8 buf[12];
-       
-       // Write command
-       writeU16(buf, TOCLIENT_OBJECTDATA);
-       os.write((char*)buf, 2);
-       
-       /*
-               Get and write player data
-       */
-       
-       // Get connected players
-       core::list<Player*> players = server->m_env->getPlayers(true);
-
-       // Write player count
-       u16 playercount = players.size();
-       writeU16(buf, playercount);
-       os.write((char*)buf, 2);
-
-       core::list<Player*>::Iterator i;
-       for(i = players.begin();
-                       i != players.end(); i++)
-       {
-               Player *player = *i;
-
-               v3f pf = player->getPosition();
-               v3f sf = player->getSpeed();
-
-               v3s32 position_i(pf.X*100, pf.Y*100, pf.Z*100);
-               v3s32 speed_i   (sf.X*100, sf.Y*100, sf.Z*100);
-               s32   pitch_i   (player->getPitch() * 100);
-               s32   yaw_i     (player->getYaw() * 100);
-               
-               writeU16(buf, player->peer_id);
-               os.write((char*)buf, 2);
-               writeV3S32(buf, position_i);
-               os.write((char*)buf, 12);
-               writeV3S32(buf, speed_i);
-               os.write((char*)buf, 12);
-               writeS32(buf, pitch_i);
-               os.write((char*)buf, 4);
-               writeS32(buf, yaw_i);
-               os.write((char*)buf, 4);
-       }
-       
-       /*
-               Get and write object data (dummy, for compatibility)
-       */
-
-       // Write block count
-       writeU16(buf, 0);
-       os.write((char*)buf, 2);
-
-       /*
-               Send data
-       */
-       
-       //infostream<<"Server: Sending object data to "<<peer_id<<std::endl;
-
-       // Make data buffer
-       std::string s = os.str();
-       SharedBuffer<u8> data((u8*)s.c_str(), s.size());
-       // Send as unreliable
-       server->m_con.Send(peer_id, 0, data, false);
-}
-
 void RemoteClient::GotBlock(v3s16 p)
 {
        if(m_blocks_sending.find(p) != NULL)
@@ -932,120 +838,40 @@ u32 PIChecksum(core::list<PlayerInfo> &l)
        return checksum;
 }
 
-/*
-       Mods
-*/
-
-struct ModSpec
-{
-       std::string name;
-       std::string path;
-       std::set<std::string> depends;
-       std::set<std::string> unsatisfied_depends;
-
-       ModSpec(const std::string &name_="", const std::string path_="",
-                       const std::set<std::string> &depends_=std::set<std::string>()):
-               name(name_),
-               path(path_),
-               depends(depends_),
-               unsatisfied_depends(depends_)
-       {}
-};
-
-// Get a dependency-sorted list of ModSpecs
-static core::list<ModSpec> getMods(core::list<std::string> &modspaths)
-{
-       std::queue<ModSpec> mods_satisfied;
-       core::list<ModSpec> mods_unsorted;
-       core::list<ModSpec> mods_sorted;
-       for(core::list<std::string>::Iterator i = modspaths.begin();
-                       i != modspaths.end(); i++){
-               std::string modspath = *i;
-               std::vector<fs::DirListNode> dirlist = fs::GetDirListing(modspath);
-               for(u32 j=0; j<dirlist.size(); j++){
-                       if(!dirlist[j].dir)
-                               continue;
-                       std::string modname = dirlist[j].name;
-                       std::string modpath = modspath + DIR_DELIM + modname;
-                       std::set<std::string> depends;
-                       std::ifstream is((modpath+DIR_DELIM+"depends.txt").c_str(),
-                                       std::ios_base::binary);
-                       while(is.good()){
-                               std::string dep;
-                               std::getline(is, dep);
-                               dep = trim(dep);
-                               if(dep != "")
-                                       depends.insert(dep);
-                       }
-                       ModSpec spec(modname, modpath, depends);
-                       mods_unsorted.push_back(spec);
-                       if(depends.empty())
-                               mods_satisfied.push(spec);
-               }
-       }
-       // Sort by depencencies
-       while(!mods_satisfied.empty()){
-               ModSpec mod = mods_satisfied.front();
-               mods_satisfied.pop();
-               mods_sorted.push_back(mod);
-               for(core::list<ModSpec>::Iterator i = mods_unsorted.begin();
-                               i != mods_unsorted.end(); i++){
-                       ModSpec &mod2 = *i;
-                       if(mod2.unsatisfied_depends.empty())
-                               continue;
-                       mod2.unsatisfied_depends.erase(mod.name);
-                       if(!mod2.unsatisfied_depends.empty())
-                               continue;
-                       mods_satisfied.push(mod2);
-               }
-       }
-       // Check unsatisfied dependencies
-       for(core::list<ModSpec>::Iterator i = mods_unsorted.begin();
-                       i != mods_unsorted.end(); i++){
-               ModSpec &mod = *i;
-               if(mod.unsatisfied_depends.empty())
-                       continue;
-               errorstream<<"mod \""<<mod.name
-                               <<"\" has unsatisfied dependencies:";
-               for(std::set<std::string>::iterator
-                               i = mod.unsatisfied_depends.begin();
-                               i != mod.unsatisfied_depends.end(); i++){
-                       errorstream<<" \""<<(*i)<<"\"";
-               }
-               errorstream<<". Loading nevertheless."<<std::endl;
-               mods_sorted.push_back(mod);
-       }
-       return mods_sorted;
-}
-
 /*
        Server
 */
 
 Server::Server(
-               std::string mapsavedir,
-               std::string configpath
+               std::string path_world,
+               std::string path_config,
+               std::string gamename
        ):
+       m_gamename(gamename),
+       m_path_world(path_world),
+       m_path_config(path_config),
        m_env(NULL),
        m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
-       m_authmanager(mapsavedir+DIR_DELIM+"auth.txt"),
-       m_banmanager(mapsavedir+DIR_DELIM+"ipban.txt"),
+       m_authmanager(path_world+DIR_DELIM+"auth.txt"),
+       m_banmanager(path_world+DIR_DELIM+"ipban.txt"),
        m_lua(NULL),
-       m_toolmgr(createToolDefManager()),
+       m_itemdef(createItemDefManager()),
        m_nodedef(createNodeDefManager()),
        m_craftdef(createCraftDefManager()),
-       m_craftitemdef(createCraftItemDefManager()),
        m_thread(this),
        m_emergethread(this),
        m_time_counter(0),
        m_time_of_day_send_timer(0),
        m_uptime(0),
-       m_mapsavedir(mapsavedir),
-       m_configpath(configpath),
        m_shutdown_requested(false),
        m_ignore_map_edit_events(false),
        m_ignore_map_edit_events_peer_id(0)
 {
+       infostream<<"Server created."<<std::endl;
+       infostream<<"- path_world  = "<<path_world<<std::endl;
+       infostream<<"- path_config = "<<path_config<<std::endl;
+       infostream<<"- gamename    = "<<gamename<<std::endl;
+
        m_liquid_transform_timer = 0.0;
        m_print_info_timer = 0.0;
        m_objectdata_timer = 0.0;
@@ -1057,15 +883,34 @@ Server::Server(
        m_step_dtime_mutex.Init();
        m_step_dtime = 0.0;
 
-       JMutexAutoLock envlock(m_env_mutex);
-       JMutexAutoLock conlock(m_con_mutex);
+       // Figure out some paths
+       m_path_share = porting::path_share + DIR_DELIM + "server";
+       m_path_game = m_path_share + DIR_DELIM + "games" + DIR_DELIM + m_gamename;
 
-       infostream<<"m_nodedef="<<m_nodedef<<std::endl;
-       
        // Path to builtin.lua
-       std::string builtinpath = porting::path_data + DIR_DELIM + "builtin.lua";
-       // Add default global mod path
-       m_modspaths.push_back(porting::path_data + DIR_DELIM + "mods");
+       std::string builtinpath = m_path_share + DIR_DELIM + "builtin.lua";
+
+       // Add default global mod search path
+       m_modspaths.push_front(m_path_game + DIR_DELIM "mods");
+       // Add world mod search path
+       m_modspaths.push_front(m_path_world + DIR_DELIM + "worldmods");
+       // Add addon mod search path
+       for(std::set<std::string>::const_iterator i = m_path_addons.begin();
+                       i != m_path_addons.end(); i++){
+               m_modspaths.push_front((*i) + DIR_DELIM + "mods");
+       }
+       
+       // Print out mod search paths
+       infostream<<"- mod search paths:"<<std::endl;
+       for(core::list<std::string>::Iterator i = m_modspaths.begin();
+                       i != m_modspaths.end(); i++){
+               std::string modspath = *i;
+               infostream<<"    "<<modspath<<std::endl;
+       }
+       
+       // Lock environment
+       JMutexAutoLock envlock(m_env_mutex);
+       JMutexAutoLock conlock(m_con_mutex);
 
        // Initialize scripting
        
@@ -1077,30 +922,36 @@ Server::Server(
        // Load and run builtin.lua
        infostream<<"Server: Loading builtin Lua stuff from \""<<builtinpath
                        <<"\""<<std::endl;
-       bool success = script_load(m_lua, builtinpath.c_str());
+       bool success = scriptapi_loadmod(m_lua, builtinpath, "__builtin");
        if(!success){
                errorstream<<"Server: Failed to load and run "
                                <<builtinpath<<std::endl;
-               assert(0);
+               throw ModError("Failed to load and run "+builtinpath);
        }
        // Load and run "mod" scripts
-       core::list<ModSpec> mods = getMods(m_modspaths);
-       for(core::list<ModSpec>::Iterator i = mods.begin();
-                       i != mods.end(); i++){
-               ModSpec mod = *i;
+       m_mods = getMods(m_modspaths);
+       for(core::list<ModSpec>::Iterator i = m_mods.begin();
+                       i != m_mods.end(); i++){
+               const ModSpec &mod = *i;
                infostream<<"Server: Loading mod \""<<mod.name<<"\""<<std::endl;
                std::string scriptpath = mod.path + DIR_DELIM + "init.lua";
-               bool success = script_load(m_lua, scriptpath.c_str());
+               bool success = scriptapi_loadmod(m_lua, scriptpath, mod.name);
                if(!success){
                        errorstream<<"Server: Failed to load and run "
                                        <<scriptpath<<std::endl;
-                       assert(0);
+                       throw ModError("Failed to load and run "+scriptpath);
                }
        }
        
+       // Read Textures and calculate sha1 sums
+       PrepareTextures();
+
+       // Apply item aliases in the node definition manager
+       m_nodedef->updateAliases(m_itemdef);
+
        // Initialize Environment
        
-       m_env = new ServerEnvironment(new ServerMap(mapsavedir, this), m_lua,
+       m_env = new ServerEnvironment(new ServerMap(path_world, this), m_lua,
                        this, this);
 
        // Give environment reference to scripting api
@@ -1110,15 +961,15 @@ Server::Server(
        m_env->getMap().addEventReceiver(this);
 
        // If file exists, load environment metadata
-       if(fs::PathExists(m_mapsavedir+DIR_DELIM+"env_meta.txt"))
+       if(fs::PathExists(m_path_world+DIR_DELIM+"env_meta.txt"))
        {
                infostream<<"Server: Loading environment metadata"<<std::endl;
-               m_env->loadMeta(m_mapsavedir);
+               m_env->loadMeta(m_path_world);
        }
 
        // Load players
        infostream<<"Server: Loading players"<<std::endl;
-       m_env->deSerializePlayers(m_mapsavedir);
+       m_env->deSerializePlayers(m_path_world);
 
        /*
                Add some test ActiveBlockModifiers to environment
@@ -1166,13 +1017,13 @@ Server::~Server()
                        Save players
                */
                infostream<<"Server: Saving players"<<std::endl;
-               m_env->serializePlayers(m_mapsavedir);
+               m_env->serializePlayers(m_path_world);
 
                /*
                        Save environment metadata
                */
                infostream<<"Server: Saving environment metadata"<<std::endl;
-               m_env->saveMeta(m_mapsavedir);
+               m_env->saveMeta(m_path_world);
        }
                
        /*
@@ -1206,10 +1057,9 @@ Server::~Server()
        // Delete Environment
        delete m_env;
 
-       delete m_toolmgr;
+       delete m_itemdef;
        delete m_nodedef;
        delete m_craftdef;
-       delete m_craftitemdef;
        
        // Deinitialize scripting
        infostream<<"Server: Deinitializing scripting"<<std::endl;
@@ -1230,7 +1080,7 @@ void Server::start(unsigned short port)
        m_thread.setRun(true);
        m_thread.Start();
        
-       infostream<<"Server: Started on port "<<port<<std::endl;
+       infostream<<"Server started on port "<<port<<"."<<std::endl;
 }
 
 void Server::stop()
@@ -1273,7 +1123,6 @@ void Server::AsyncRunStep()
        }
        
        {
-               ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
                // Send blocks to clients
                SendBlocks(dtime);
        }
@@ -1376,17 +1225,14 @@ void Server::AsyncRunStep()
        */
 
        /*
-               Check player movements
-
-               NOTE: Actually the server should handle player physics like the
-               client does and compare player's position to what is calculated
-               on our side. This is required when eg. players fly due to an
-               explosion.
+               Handle players
        */
        {
                JMutexAutoLock lock(m_env_mutex);
                JMutexAutoLock lock2(m_con_mutex);
 
+               ScopeProfiler sp(g_profiler, "Server: handle players");
+
                //float player_max_speed = BS * 4.0; // Normal speed
                float player_max_speed = BS * 20; // Fast speed
                float player_max_speed_up = BS * 20;
@@ -1404,8 +1250,17 @@ void Server::AsyncRunStep()
                                        (m_env->getPlayer(client->peer_id));
                        if(player==NULL)
                                continue;
+                       
+                       /*
+                               Check player movements
+
+                               NOTE: Actually the server should handle player physics like the
+                               client does and compare player's position to what is calculated
+                               on our side. This is required when eg. players fly due to an
+                               explosion.
+                       */
                        player->m_last_good_position_age += dtime;
-                       if(player->m_last_good_position_age >= 2.0){
+                       if(player->m_last_good_position_age >= 1.0){
                                float age = player->m_last_good_position_age;
                                v3f diff = (player->getPosition() - player->m_last_good_position);
                                float d_vert = diff.Y;
@@ -1425,6 +1280,32 @@ void Server::AsyncRunStep()
                                }
                                player->m_last_good_position_age = 0;
                        }
+
+                       /*
+                               Handle player HPs (die if hp=0)
+                       */
+                       if(player->hp == 0 && player->m_hp_not_sent)
+                               DiePlayer(player);
+
+                       /*
+                               Send player inventories and HPs if necessary
+                       */
+                       if(player->m_inventory_not_sent){
+                               UpdateCrafting(player->peer_id);
+                               SendInventory(player->peer_id);
+                       }
+                       if(player->m_hp_not_sent){
+                               SendPlayerHP(player);
+                       }
+
+                       /*
+                               Add to environment
+                       */
+                       if(!player->m_is_in_environment){
+                               player->m_removed = false;
+                               player->setId(0);
+                               m_env->addActiveObject(player);
+                       }
                }
        }
        
@@ -1526,6 +1407,12 @@ void Server::AsyncRunStep()
                        i.atEnd() == false; i++)
                {
                        RemoteClient *client = i.getNode()->getValue();
+
+                       // If definitions and textures have not been sent, don't
+                       // send objects either
+                       if(!client->definitions_sent)
+                               continue;
+
                        Player *player = m_env->getPlayer(client->peer_id);
                        if(player==NULL)
                        {
@@ -1664,7 +1551,7 @@ void Server::AsyncRunStep()
                JMutexAutoLock envlock(m_env_mutex);
                JMutexAutoLock conlock(m_con_mutex);
 
-               //ScopeProfiler sp(g_profiler, "Server: sending object messages");
+               ScopeProfiler sp(g_profiler, "Server: sending object messages");
 
                // Key = object id
                // Value = data sent by object
@@ -1893,25 +1780,6 @@ void Server::AsyncRunStep()
                
        }
 
-       /*
-               Send object positions
-       */
-       {
-               float &counter = m_objectdata_timer;
-               counter += dtime;
-               if(counter >= g_settings->getFloat("objectdata_interval"))
-               {
-                       JMutexAutoLock lock1(m_env_mutex);
-                       JMutexAutoLock lock2(m_con_mutex);
-
-                       //ScopeProfiler sp(g_profiler, "Server: sending player positions");
-
-                       SendObjectData(counter);
-
-                       counter = 0.0;
-               }
-       }
-       
        /*
                Trigger emergethread (it somehow gets to a non-triggered but
                bysy state sometimes)
@@ -1934,6 +1802,7 @@ void Server::AsyncRunStep()
                if(counter >= g_settings->getFloat("server_map_save_interval"))
                {
                        counter = 0.0;
+                       JMutexAutoLock lock(m_env_mutex);
 
                        ScopeProfiler sp(g_profiler, "Server: saving stuff");
 
@@ -1941,21 +1810,18 @@ void Server::AsyncRunStep()
                        if(m_authmanager.isModified())
                                m_authmanager.save();
 
-                       //Bann stuff
+                       //Ban stuff
                        if(m_banmanager.isModified())
                                m_banmanager.save();
                        
-                       // Map
-                       JMutexAutoLock lock(m_env_mutex);
-
                        // Save changed parts of map
                        m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
 
                        // Save players
-                       m_env->serializePlayers(m_mapsavedir);
+                       m_env->serializePlayers(m_path_world);
                        
                        // Save environment metadata
-                       m_env->saveMeta(m_mapsavedir);
+                       m_env->saveMeta(m_path_world);
                }
        }
 }
@@ -2008,6 +1874,8 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        JMutexAutoLock envlock(m_env_mutex);
        JMutexAutoLock conlock(m_con_mutex);
        
+       ScopeProfiler sp(g_profiler, "Server::ProcessData");
+       
        try{
                Address address = m_con.GetPeerAddress(peer_id);
 
@@ -2069,8 +1937,11 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        infostream<<"Server: Cannot negotiate "
                                        "serialization version with peer "
                                        <<peer_id<<std::endl;
-                       SendAccessDenied(m_con, peer_id,
-                                       L"Your client is too old (map format)");
+                       SendAccessDenied(m_con, peer_id, std::wstring(
+                                       L"Your client's version is not supported.\n"
+                                       L"Server version is ")
+                                       + narrow_to_wide(VERSION_STRING) + L"."
+                       );
                        return;
                }
                
@@ -2088,18 +1959,27 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
 
                if(net_proto_version == 0)
                {
-                       SendAccessDenied(m_con, peer_id,
-                                       L"Your client is too old. Please upgrade.");
+                       SendAccessDenied(m_con, peer_id, std::wstring(
+                                       L"Your client's version is not supported.\n"
+                                       L"Server version is ")
+                                       + narrow_to_wide(VERSION_STRING) + L"."
+                       );
                        return;
                }
                
-               /* Uhh... this should actually be a warning but let's do it like this */
                if(g_settings->getBool("strict_protocol_version_checking"))
                {
-                       if(net_proto_version < PROTOCOL_VERSION)
+                       if(net_proto_version != PROTOCOL_VERSION)
                        {
-                               SendAccessDenied(m_con, peer_id,
-                                               L"Your client is too old. Please upgrade.");
+                               SendAccessDenied(m_con, peer_id, std::wstring(
+                                               L"Your client's version is not supported.\n"
+                                               L"Server version is ")
+                                               + narrow_to_wide(VERSION_STRING) + L",\n"
+                                               + L"server's PROTOCOL_VERSION is "
+                                               + narrow_to_wide(itos(PROTOCOL_VERSION))
+                                               + L", client's PROTOCOL_VERSION is "
+                                               + narrow_to_wide(itos(net_proto_version))
+                               );
                                return;
                        }
                }
@@ -2148,20 +2028,33 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                password[PASSWORD_SIZE-1] = 0;
                }
                
-               std::string checkpwd;
-               if(m_authmanager.exists(playername))
-               {
-                       checkpwd = m_authmanager.getPassword(playername);
-               }
-               else
+               // Add player to auth manager
+               if(m_authmanager.exists(playername) == false)
                {
-                       checkpwd = g_settings->get("default_password");
+                       std::wstring default_password =
+                               narrow_to_wide(g_settings->get("default_password"));
+                       std::string translated_default_password =
+                               translatePassword(playername, default_password);
+
+                       // If default_password is empty, allow any initial password
+                       if (default_password.length() == 0)
+                               translated_default_password = password;
+
+                       infostream<<"Server: adding player "<<playername
+                                       <<" to auth manager"<<std::endl;
+                       m_authmanager.add(playername);
+                       m_authmanager.setPassword(playername, translated_default_password);
+                       m_authmanager.setPrivs(playername,
+                                       stringToPrivs(g_settings->get("default_privs")));
+                       m_authmanager.save();
                }
-               
+
+               std::string checkpwd = m_authmanager.getPassword(playername);
+
                /*infostream<<"Server: Client gave password '"<<password
                                <<"', the correct one is '"<<checkpwd<<"'"<<std::endl;*/
-               
-               if(password != checkpwd && m_authmanager.exists(playername))
+
+               if(password != checkpwd)
                {
                        infostream<<"Server: peer_id="<<peer_id
                                        <<": supplied invalid password for "
@@ -2170,23 +2063,11 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        return;
                }
                
-               // Add player to auth manager
-               if(m_authmanager.exists(playername) == false)
-               {
-                       infostream<<"Server: adding player "<<playername
-                                       <<" to auth manager"<<std::endl;
-                       m_authmanager.add(playername);
-                       m_authmanager.setPassword(playername, checkpwd);
-                       m_authmanager.setPrivs(playername,
-                                       stringToPrivs(g_settings->get("default_privs")));
-                       m_authmanager.save();
-               }
-               
                // Enforce user limit.
                // Don't enforce for users that have some admin right
                if(m_clients.size() >= g_settings->getU16("max_users") &&
                                (m_authmanager.getPrivs(playername)
-                                       & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS)) == 0 &&
+                                       & (PRIV_SERVER|PRIV_BAN|PRIV_PRIVS|PRIV_PASSWORD)) == 0 &&
                                playername != g_settings->get("name"))
                {
                        SendAccessDenied(m_con, peer_id, L"Too many users.");
@@ -2194,7 +2075,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                }
 
                // Get player
-               Player *player = emergePlayer(playername, password, peer_id);
+               ServerRemotePlayer *player = emergePlayer(playername, peer_id);
 
                // If failed, cancel
                if(player == NULL)
@@ -2239,25 +2120,22 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        Send some initialization data
                */
 
-               // Send tool definitions
-               SendToolDef(m_con, peer_id, m_toolmgr);
+               // Send item definitions
+               SendItemDef(m_con, peer_id, m_itemdef);
                
                // Send node definitions
                SendNodeDef(m_con, peer_id, m_nodedef);
                
-               // Send CraftItem definitions
-               SendCraftItemDef(m_con, peer_id, m_craftitemdef);
-               
-               // Send textures
-               SendTextures(peer_id);
+               // Send texture announcement
+               SendTextureAnnouncement(peer_id);
                
                // Send player info to all players
-               SendPlayerInfos();
+               //SendPlayerInfos();
 
                // Send inventory to player
                UpdateCrafting(peer_id);
                SendInventory(peer_id);
-
+               
                // Send player items to all players
                SendPlayerItems();
 
@@ -2266,6 +2144,10 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                // Send HP
                SendPlayerHP(player);
                
+               // Show death screen if necessary
+               if(player->hp == 0)
+                       SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
+
                // Send time of day
                {
                        SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
@@ -2296,11 +2178,6 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
                }
 
-               /*
-                       Check HP, respawn if necessary
-               */
-               HandlePlayerHP(player, 0);
-
                /*
                        Print out action
                */
@@ -2338,6 +2215,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        }
        
        Player *player = m_env->getPlayer(peer_id);
+       ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
 
        if(player == NULL){
                infostream<<"Server::ProcessData(): Cancelling: "
@@ -2450,7 +2328,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        }
        else if(command == TOSERVER_SIGNNODETEXT)
        {
-               if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
+               if((getPlayerPrivs(player) & PRIV_INTERACT) == 0)
                        return;
                /*
                        u16 command
@@ -2494,175 +2372,182 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        }
        else if(command == TOSERVER_INVENTORY_ACTION)
        {
-               /*// Ignore inventory changes if in creative mode
-               if(g_settings->getBool("creative_mode") == true)
-               {
-                       infostream<<"TOSERVER_INVENTORY_ACTION: ignoring in creative mode"
-                                       <<std::endl;
-                       return;
-               }*/
                // Strip command and create a stream
                std::string datastring((char*)&data[2], datasize-2);
                infostream<<"TOSERVER_INVENTORY_ACTION: data="<<datastring<<std::endl;
                std::istringstream is(datastring, std::ios_base::binary);
                // Create an action
                InventoryAction *a = InventoryAction::deSerialize(is);
-               if(a != NULL)
+               if(a == NULL)
+               {
+                       infostream<<"TOSERVER_INVENTORY_ACTION: "
+                                       <<"InventoryAction::deSerialize() returned NULL"
+                                       <<std::endl;
+                       return;
+               }
+
+               /*
+                       Note: Always set inventory not sent, to repair cases
+                       where the client made a bad prediction.
+               */
+
+               /*
+                       Handle restrictions and special cases of the move action
+               */
+               if(a->getType() == IACTION_MOVE)
                {
-                       // Create context
-                       InventoryContext c;
-                       c.current_player = player;
+                       IMoveAction *ma = (IMoveAction*)a;
+
+                       ma->from_inv.applyCurrentPlayer(player->getName());
+                       ma->to_inv.applyCurrentPlayer(player->getName());
+
+                       setInventoryModified(ma->from_inv);
+                       setInventoryModified(ma->to_inv);
+
+                       bool from_inv_is_current_player =
+                               (ma->from_inv.type == InventoryLocation::PLAYER) &&
+                               (ma->from_inv.name == player->getName());
+
+                       bool to_inv_is_current_player =
+                               (ma->to_inv.type == InventoryLocation::PLAYER) &&
+                               (ma->to_inv.name == player->getName());
 
                        /*
-                               Handle craftresult specially if not in creative mode
+                               Disable moving items out of craftpreview
                        */
-                       bool disable_action = false;
-                       if(a->getType() == IACTION_MOVE
-                                       && g_settings->getBool("creative_mode") == false)
+                       if(ma->from_list == "craftpreview")
                        {
-                               IMoveAction *ma = (IMoveAction*)a;
-                               if(ma->to_inv == "current_player" &&
-                                               ma->from_inv == "current_player")
-                               {
-                                       InventoryList *rlist = player->inventory.getList("craftresult");
-                                       assert(rlist);
-                                       InventoryList *clist = player->inventory.getList("craft");
-                                       assert(clist);
-                                       InventoryList *mlist = player->inventory.getList("main");
-                                       assert(mlist);
-                                       /*
-                                               Craftresult is no longer preview if something
-                                               is moved into it
-                                       */
-                                       if(ma->to_list == "craftresult"
-                                                       && ma->from_list != "craftresult")
-                                       {
-                                               // If it currently is a preview, remove
-                                               // its contents
-                                               if(player->craftresult_is_preview)
-                                               {
-                                                       rlist->deleteItem(0);
-                                               }
-                                               player->craftresult_is_preview = false;
-                                       }
-                                       /*
-                                               Crafting takes place if this condition is true.
-                                       */
-                                       if(player->craftresult_is_preview &&
-                                                       ma->from_list == "craftresult")
-                                       {
-                                               player->craftresult_is_preview = false;
-                                               clist->decrementMaterials(1);
-                                               
-                                               /* Print out action */
-                                               InventoryList *list =
-                                                               player->inventory.getList("craftresult");
-                                               assert(list);
-                                               InventoryItem *item = list->getItem(0);
-                                               std::string itemname = "NULL";
-                                               if(item)
-                                                       itemname = item->getName();
-                                               actionstream<<player->getName()<<" crafts "
-                                                               <<itemname<<std::endl;
-                                       }
-                                       /*
-                                               If the craftresult is placed on itself, move it to
-                                               main inventory instead of doing the action
-                                       */
-                                       if(ma->to_list == "craftresult"
-                                                       && ma->from_list == "craftresult")
-                                       {
-                                               disable_action = true;
-                                               
-                                               InventoryItem *item1 = rlist->changeItem(0, NULL);
-                                               mlist->addItem(item1);
-                                       }
-                               }
-                               // Disallow moving items if not allowed to build
-                               else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
-                               {
-                                       disable_action = true;
-                               }
-                               // if it's a locking chest, only allow the owner or server admins to move items
-                               else if (ma->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                               infostream<<"Ignoring IMoveAction from "
+                                               <<(ma->from_inv.dump())<<":"<<ma->from_list
+                                               <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
+                                               <<" because src is "<<ma->from_list<<std::endl;
+                               delete a;
+                               return;
+                       }
+
+                       /*
+                               Disable moving items into craftresult and craftpreview
+                       */
+                       if(ma->to_list == "craftpreview" || ma->to_list == "craftresult")
+                       {
+                               infostream<<"Ignoring IMoveAction from "
+                                               <<(ma->from_inv.dump())<<":"<<ma->from_list
+                                               <<" to "<<(ma->to_inv.dump())<<":"<<ma->to_list
+                                               <<" because dst is "<<ma->to_list<<std::endl;
+                               delete a;
+                               return;
+                       }
+
+                       // Disallow moving items in elsewhere than player's inventory
+                       // if not allowed to interact
+                       if((getPlayerPrivs(player) & PRIV_INTERACT) == 0
+                                       && (!from_inv_is_current_player
+                                       || !to_inv_is_current_player))
+                       {
+                               infostream<<"Cannot move outside of player's inventory: "
+                                               <<"No interact privilege"<<std::endl;
+                               delete a;
+                               return;
+                       }
+
+                       // If player is not an admin, check for ownership of src and dst
+                       if((getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                       {
+                               std::string owner_from = getInventoryOwner(ma->from_inv);
+                               if(owner_from != "" && owner_from != player->getName())
                                {
-                                       Strfnd fn(ma->from_inv);
-                                       std::string id0 = fn.next(":");
-                                       if(id0 == "nodemeta")
-                                       {
-                                               v3s16 p;
-                                               p.X = stoi(fn.next(","));
-                                               p.Y = stoi(fn.next(","));
-                                               p.Z = stoi(fn.next(","));
-                                               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
-                                               if(meta->getOwner() != ""){
-                                                       if(meta->getOwner() != player->getName())
-                                                               disable_action = true;
-                                               }
-                                       }
+                                       infostream<<"WARNING: "<<player->getName()
+                                               <<" tried to access an inventory that"
+                                               <<" belongs to "<<owner_from<<std::endl;
+                                       delete a;
+                                       return;
                                }
-                               else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+
+                               std::string owner_to = getInventoryOwner(ma->to_inv);
+                               if(owner_to != "" && owner_to != player->getName())
                                {
-                                       Strfnd fn(ma->to_inv);
-                                       std::string id0 = fn.next(":");
-                                       if(id0 == "nodemeta")
-                                       {
-                                               v3s16 p;
-                                               p.X = stoi(fn.next(","));
-                                               p.Y = stoi(fn.next(","));
-                                               p.Z = stoi(fn.next(","));
-                                               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
-                                               if(meta->getOwner() != ""){
-                                                       if(meta->getOwner() != player->getName())
-                                                               disable_action = true;
-                                               }
-                                       }
+                                       infostream<<"WARNING: "<<player->getName()
+                                               <<" tried to access an inventory that"
+                                               <<" belongs to "<<owner_to<<std::endl;
+                                       delete a;
+                                       return;
                                }
                        }
+               }
+               /*
+                       Handle restrictions and special cases of the drop action
+               */
+               else if(a->getType() == IACTION_DROP)
+               {
+                       IDropAction *da = (IDropAction*)a;
 
-                       if(a->getType() == IACTION_DROP)
+                       da->from_inv.applyCurrentPlayer(player->getName());
+
+                       setInventoryModified(da->from_inv);
+
+                       // Disallow dropping items if not allowed to interact
+                       if((getPlayerPrivs(player) & PRIV_INTERACT) == 0)
                        {
-                               IDropAction *da = (IDropAction*)a;
-                               // Disallow dropping items if not allowed to build
-                               if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
-                               {
-                                       disable_action = true;
-                               }
-                               // if it's a locking chest, only allow the owner or server admins to drop items
-                               else if (da->from_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                               delete a;
+                               return;
+                       }
+                       // If player is not an admin, check for ownership
+                       else if((getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                       {
+                               std::string owner_from = getInventoryOwner(da->from_inv);
+                               if(owner_from != "" && owner_from != player->getName())
                                {
-                                       Strfnd fn(da->from_inv);
-                                       std::string id0 = fn.next(":");
-                                       if(id0 == "nodemeta")
-                                       {
-                                               v3s16 p;
-                                               p.X = stoi(fn.next(","));
-                                               p.Y = stoi(fn.next(","));
-                                               p.Z = stoi(fn.next(","));
-                                               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
-                                               if(meta->getOwner() != ""){
-                                                       if(meta->getOwner() != player->getName())
-                                                               disable_action = true;
-                                               }
-                                       }
+                                       infostream<<"WARNING: "<<player->getName()
+                                               <<" tried to access an inventory that"
+                                               <<" belongs to "<<owner_from<<std::endl;
+                                       delete a;
+                                       return;
                                }
                        }
-                       
-                       if(disable_action == false)
+               }
+               /*
+                       Handle restrictions and special cases of the craft action
+               */
+               else if(a->getType() == IACTION_CRAFT)
+               {
+                       ICraftAction *ca = (ICraftAction*)a;
+
+                       ca->craft_inv.applyCurrentPlayer(player->getName());
+
+                       setInventoryModified(ca->craft_inv);
+
+                       //bool craft_inv_is_current_player =
+                       //      (ca->craft_inv.type == InventoryLocation::PLAYER) &&
+                       //      (ca->craft_inv.name == player->getName());
+
+                       // Disallow crafting if not allowed to interact
+                       if((getPlayerPrivs(player) & PRIV_INTERACT) == 0)
                        {
-                               // Feed action to player inventory
-                               a->apply(&c, this, m_env);
+                               infostream<<"Cannot craft: "
+                                               <<"No interact privilege"<<std::endl;
+                               delete a;
+                               return;
                        }
 
-                       // Eat the action
-                       delete a;
-               }
-               else
-               {
-                       infostream<<"TOSERVER_INVENTORY_ACTION: "
-                                       <<"InventoryAction::deSerialize() returned NULL"
-                                       <<std::endl;
+                       // If player is not an admin, check for ownership of inventory
+                       if((getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                       {
+                               std::string owner_craft = getInventoryOwner(ca->craft_inv);
+                               if(owner_craft != "" && owner_craft != player->getName())
+                               {
+                                       infostream<<"WARNING: "<<player->getName()
+                                               <<" tried to access an inventory that"
+                                               <<" belongs to "<<owner_craft<<std::endl;
+                                       delete a;
+                                       return;
+                               }
+                       }
                }
+               
+               // Do the action
+               a->apply(this, srp, this);
+               // Eat the action
+               delete a;
        }
        else if(command == TOSERVER_CHAT_MESSAGE)
        {
@@ -2791,16 +2676,25 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                std::istringstream is(datastring, std::ios_base::binary);
                u8 damage = readU8(is);
 
-               if(g_settings->getBool("enable_damage"))
+               ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
+
+               if(g_settings->getBool("enable_damage"))
                {
                        actionstream<<player->getName()<<" damaged by "
                                        <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
                                        <<std::endl;
-                               
-                       HandlePlayerHP(player, damage);
+
+                       srp->setHP(srp->getHP() - damage);
+
+                       if(srp->getHP() == 0 && srp->m_hp_not_sent)
+                               DiePlayer(srp);
+
+                       if(srp->m_hp_not_sent)
+                               SendPlayerHP(player);
                }
                else
                {
+                       // Force send (to correct the client's predicted HP)
                        SendPlayerHP(player);
                }
        }
@@ -2872,8 +2766,8 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        return;
 
                u16 item = readU16(&data[2]);
-               player->wieldItem(item);
-               SendWieldedItem(player);
+               srp->setWieldIndex(item);
+               SendWieldedItem(srp);
        }
        else if(command == TOSERVER_RESPAWN)
        {
@@ -2884,6 +2778,33 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                
                actionstream<<player->getName()<<" respawns at "
                                <<PP(player->getPosition()/BS)<<std::endl;
+
+               // ActiveObject is added to environment in AsyncRunStep after
+               // the previous addition has been succesfully removed
+       }
+       else if(command == TOSERVER_REQUEST_TEXTURES) {
+               std::string datastring((char*)&data[2], datasize-2);
+               std::istringstream is(datastring, std::ios_base::binary);
+
+               infostream<<"TOSERVER_REQUEST_TEXTURES: "<<std::endl;
+
+               core::list<TextureRequest> tosend;
+
+               u16 numtextures = readU16(is);
+
+               for(int i = 0; i < numtextures; i++) {
+
+                       std::string name = deSerializeString(is);
+
+                       tosend.push_back(TextureRequest(name));
+                       infostream<<"TOSERVER_REQUEST_TEXTURES: requested texture " << name <<std::endl;
+               }
+
+               SendTexturesRequested(peer_id, tosend);
+
+               // Now the client should know about everything
+               // (definitions and textures)
+               getClient(peer_id)->definitions_sent = true;
        }
        else if(command == TOSERVER_INTERACT)
        {
@@ -2911,11 +2832,21 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
 
                infostream<<"TOSERVER_INTERACT: action="<<(int)action<<", item="<<item_i<<", pointed="<<pointed.dump()<<std::endl;
 
-               ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
+               if(player->hp == 0)
+               {
+                       infostream<<"TOSERVER_INTERACT: "<<srp->getName()
+                               <<" tried to interact, but is dead!"<<std::endl;
+                       return;
+               }
+
                v3f player_pos = srp->m_last_good_position;
 
                // Update wielded item
-               srp->wieldItem(item_i);
+               if(srp->getWieldIndex() != item_i)
+               {
+                       srp->setWieldIndex(item_i);
+                       SendWieldedItem(srp);
+               }
 
                // Get pointed to node (undefined if not POINTEDTYPE_NODE)
                v3s16 p_under = pointed.node_undersurface;
@@ -2935,24 +2866,27 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
 
                }
 
+               v3f pointed_pos_under = player_pos;
+               v3f pointed_pos_above = player_pos;
+               if(pointed.type == POINTEDTHING_NODE)
+               {
+                       pointed_pos_under = intToFloat(p_under, BS);
+                       pointed_pos_above = intToFloat(p_above, BS);
+               }
+               else if(pointed.type == POINTEDTHING_OBJECT)
+               {
+                       pointed_pos_under = pointed_object->getBasePosition();
+                       pointed_pos_above = pointed_pos_under;
+               }
+
                /*
                        Check that target is reasonably close
                        (only when digging or placing things)
                */
                if(action == 0 || action == 2 || action == 3)
                {
-                       v3f pointed_pos = player_pos;
-                       if(pointed.type == POINTEDTHING_NODE)
-                       {
-                               pointed_pos = intToFloat(p_under, BS);
-                       }
-                       else if(pointed.type == POINTEDTHING_OBJECT)
-                       {
-                               pointed_pos = pointed_object->getBasePosition();
-                       }
-
-                       float d = player_pos.getDistanceFrom(pointed_pos);
-                       float max_d = BS * 10; // Just some large enough value
+                       float d = player_pos.getDistanceFrom(pointed_pos_under);
+                       float max_d = BS * 14; // Just some large enough value
                        if(d > max_d){
                                actionstream<<"Player "<<player->getName()
                                                <<" tried to access "<<pointed.dump()
@@ -2961,7 +2895,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                                <<". ignoring."<<std::endl;
                                // Re-send block to revert change on client-side
                                RemoteClient *client = getClient(peer_id);
-                               v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos, BS));
+                               v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_under, BS));
                                client->SetBlockNotSent(blockpos);
                                // Do nothing else
                                return;
@@ -2971,13 +2905,12 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                /*
                        Make sure the player is allowed to do it
                */
-               bool build_priv = (getPlayerPrivs(player) & PRIV_BUILD) != 0;
-               if(!build_priv)
+               if((getPlayerPrivs(player) & PRIV_INTERACT) == 0)
                {
                        infostream<<"Ignoring interaction from player "<<player->getName()
                                        <<" because privileges are "<<getPlayerPrivs(player)
                                        <<std::endl;
-                       // NOTE: no return; here, fall through
+                       return;
                }
 
                /*
@@ -2991,10 +2924,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                        NOTE: This can be used in the future to check if
                                        somebody is cheating, by checking the timing.
                                */
-                               bool cannot_punch_node = !build_priv;
-
                                MapNode n(CONTENT_IGNORE);
-
                                try
                                {
                                        n = m_env->getMap().getNode(p_under);
@@ -3006,22 +2936,12 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                                        <<std::endl;
                                        m_emerge_queue.addBlock(peer_id,
                                                        getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
-                                       cannot_punch_node = true;
                                }
-
-                               if(cannot_punch_node)
-                                       return;
-
-                               /*
-                                       Run script hook
-                               */
-                               scriptapi_environment_on_punchnode(m_lua, p_under, n, srp);
+                               if(n.getContent() != CONTENT_IGNORE)
+                                       scriptapi_node_on_punch(m_lua, p_under, n, srp);
                        }
                        else if(pointed.type == POINTEDTHING_OBJECT)
                        {
-                               if(!build_priv)
-                                       return;
-
                                // Skip if object has been removed
                                if(pointed_object->m_removed)
                                        return;
@@ -3029,8 +2949,15 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                actionstream<<player->getName()<<" punches object "
                                        <<pointed.object_id<<std::endl;
 
-                               // Do stuff
-                               pointed_object->punch(srp);
+                               ItemStack punchitem = srp->getWieldedItem();
+                               ToolCapabilities toolcap =
+                                               punchitem.getToolCapabilities(m_itemdef);
+                               v3f dir = (pointed_object->getBasePosition() -
+                                               (srp->getPosition() + srp->getEyeOffset())
+                                                       ).normalize();
+                               pointed_object->punch(dir, &toolcap, srp,
+                                               srp->m_time_from_last_punch);
+                               srp->m_time_from_last_punch = 0;
                        }
 
                } // action == 0
@@ -3048,212 +2975,24 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                else if(action == 2)
                {
                        // Only complete digging of nodes
-                       if(pointed.type != POINTEDTHING_NODE)
-                               return;
-
-                       // Mandatory parameter; actually used for nothing
-                       core::map<v3s16, MapBlock*> modified_blocks;
-
-                       content_t material = CONTENT_IGNORE;
-                       u8 mineral = MINERAL_NONE;
-
-                       bool cannot_remove_node = !build_priv;
-                       
-                       MapNode n(CONTENT_IGNORE);
-                       try
-                       {
-                               n = m_env->getMap().getNode(p_under);
-                               // Get mineral
-                               mineral = n.getMineral(m_nodedef);
-                               // Get material at position
-                               material = n.getContent();
-                               // If not yet cancelled
-                               if(cannot_remove_node == false)
-                               {
-                                       // If it's not diggable, do nothing
-                                       if(m_nodedef->get(material).diggable == false)
-                                       {
-                                               infostream<<"Server: Not finishing digging: "
-                                                               <<"Node not diggable"
-                                                               <<std::endl;
-                                               cannot_remove_node = true;
-                                       }
-                               }
-                               // If not yet cancelled
-                               if(cannot_remove_node == false)
-                               {
-                                       // Get node metadata
-                                       NodeMetadata *meta = m_env->getMap().getNodeMetadata(p_under);
-                                       if(meta && meta->nodeRemovalDisabled() == true)
-                                       {
-                                               infostream<<"Server: Not finishing digging: "
-                                                               <<"Node metadata disables removal"
-                                                               <<std::endl;
-                                               cannot_remove_node = true;
-                                       }
-                               }
-                       }
-                       catch(InvalidPositionException &e)
-                       {
-                               infostream<<"Server: Not finishing digging: Node not found."
-                                               <<" Adding block to emerge queue."
-                                               <<std::endl;
-                               m_emerge_queue.addBlock(peer_id,
-                                               getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
-                               cannot_remove_node = true;
-                       }
-
-                       /*
-                               If node can't be removed, set block to be re-sent to
-                               client and quit.
-                       */
-                       if(cannot_remove_node)
-                       {
-                               infostream<<"Server: Not finishing digging."<<std::endl;
-
-                               // Client probably has wrong data.
-                               // Set block not sent, so that client will get
-                               // a valid one.
-                               infostream<<"Client "<<peer_id<<" tried to dig "
-                                               <<"node; but node cannot be removed."
-                                               <<" setting MapBlock not sent."<<std::endl;
-                               RemoteClient *client = getClient(peer_id);
-                               v3s16 blockpos = getNodeBlockPos(p_under);
-                               client->SetBlockNotSent(blockpos);
-                                       
-                               return;
-                       }
-                       
-                       actionstream<<player->getName()<<" digs "<<PP(p_under)
-                                       <<", gets material "<<(int)material<<", mineral "
-                                       <<(int)mineral<<std::endl;
-                       
-                       /*
-                               Send the removal to all close-by players.
-                               - If other player is close, send REMOVENODE
-                               - Otherwise set blocks not sent
-                       */
-                       core::list<u16> far_players;
-                       sendRemoveNode(p_under, peer_id, &far_players, 30);
-                       
-                       /*
-                               Update and send inventory
-                       */
-
-                       if(g_settings->getBool("creative_mode") == false)
+                       if(pointed.type == POINTEDTHING_NODE)
                        {
-                               /*
-                                       Wear out tool
-                               */
-                               InventoryList *mlist = player->inventory.getList("main");
-                               if(mlist != NULL)
-                               {
-                                       InventoryItem *item = mlist->getItem(item_i);
-                                       if(item && (std::string)item->getName() == "ToolItem")
-                                       {
-                                               ToolItem *titem = (ToolItem*)item;
-                                               std::string toolname = titem->getToolName();
-
-                                               // Get digging properties for material and tool
-                                               ToolDiggingProperties tp =
-                                                               m_toolmgr->getDiggingProperties(toolname);
-                                               DiggingProperties prop =
-                                                               getDiggingProperties(material, &tp, m_nodedef);
-
-                                               if(prop.diggable == false)
-                                               {
-                                                       infostream<<"Server: WARNING: Player digged"
-                                                                       <<" with impossible material + tool"
-                                                                       <<" combination"<<std::endl;
-                                               }
-                                               
-                                               bool weared_out = titem->addWear(prop.wear);
-
-                                               if(weared_out)
-                                               {
-                                                       mlist->deleteItem(item_i);
-                                               }
-                                       }
-                               }
-
-                               /*
-                                       Add dug item to inventory
-                               */
-
-                               InventoryItem *item = NULL;
-
-                               if(mineral != MINERAL_NONE)
-                                       item = getDiggedMineralItem(mineral, this);
-                               
-                               // If not mineral
-                               if(item == NULL)
-                               {
-                                       const std::string &dug_s = m_nodedef->get(material).dug_item;
-                                       if(dug_s != "")
-                                       {
-                                               std::istringstream is(dug_s, std::ios::binary);
-                                               item = InventoryItem::deSerialize(is, this);
-                                       }
-                               }
-                               
-                               if(item != NULL)
-                               {
-                                       // Add a item to inventory
-                                       player->inventory.addItem("main", item);
-                               }
-
-                               item = NULL;
-
-                               if(mineral != MINERAL_NONE)
-                                 item = getDiggedMineralItem(mineral, this);
-                       
-                               // If not mineral
-                               if(item == NULL)
+                               MapNode n(CONTENT_IGNORE);
+                               try
                                {
-                                       const std::string &extra_dug_s = m_nodedef->get(material).extra_dug_item;
-                                       s32 extra_rarity = m_nodedef->get(material).extra_dug_item_rarity;
-                                       if(extra_dug_s != "" && extra_rarity != 0
-                                          && myrand() % extra_rarity == 0)
-                                       {
-                                               std::istringstream is(extra_dug_s, std::ios::binary);
-                                               item = InventoryItem::deSerialize(is, this);
-                                       }
+                                       n = m_env->getMap().getNode(p_under);
                                }
-                       
-                               if(item != NULL)
+                               catch(InvalidPositionException &e)
                                {
-                                       // Add a item to inventory
-                                       player->inventory.addItem("main", item);
+                                       infostream<<"Server: Not finishing digging: Node not found."
+                                                       <<" Adding block to emerge queue."
+                                                       <<std::endl;
+                                       m_emerge_queue.addBlock(peer_id,
+                                                       getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
                                }
+                               if(n.getContent() != CONTENT_IGNORE)
+                                       scriptapi_node_on_dig(m_lua, p_under, n, srp);
                        }
-
-                       /*
-                               Remove the node
-                               (this takes some time so it is done after the quick stuff)
-                       */
-                       {
-                               MapEditEventIgnorer ign(&m_ignore_map_edit_events);
-
-                               m_env->getMap().removeNodeAndUpdate(p_under, modified_blocks);
-                       }
-                       /*
-                               Set blocks not sent to far players
-                       */
-                       for(core::list<u16>::Iterator
-                                       i = far_players.begin();
-                                       i != far_players.end(); i++)
-                       {
-                               u16 peer_id = *i;
-                               RemoteClient *client = getClient(peer_id);
-                               if(client==NULL)
-                                       continue;
-                               client->SetBlocksNotSent(modified_blocks);
-                       }
-
-                       /*
-                               Run script hook
-                       */
-                       scriptapi_environment_on_dignode(m_lua, p_under, n, srp);
                } // action == 2
                
                /*
@@ -3261,230 +3000,17 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                */
                else if(action == 3)
                {
-                       if(pointed.type == POINTEDTHING_NODE)
-                       {
-                               InventoryList *ilist = player->inventory.getList("main");
-                               if(ilist == NULL)
-                                       return;
-
-                               // Get item
-                               InventoryItem *item = ilist->getItem(item_i);
-                               
-                               // If there is no item, it is not possible to add it anywhere
-                               if(item == NULL)
-                                       return;
-
-                               /*
-                                       Handle material items
-                               */
-                               if(std::string("MaterialItem") == item->getName())
-                               {
-                                       bool cannot_place_node = !build_priv;
-
-                                       try{
-                                               // Don't add a node if this is not a free space
-                                               MapNode n2 = m_env->getMap().getNode(p_above);
-                                               if(m_nodedef->get(n2).buildable_to == false)
-                                               {
-                                                       infostream<<"Client "<<peer_id<<" tried to place"
-                                                                       <<" node in invalid position."<<std::endl;
-                                                       cannot_place_node = true;
-                                               }
-                                       }
-                                       catch(InvalidPositionException &e)
-                                       {
-                                               infostream<<"Server: Ignoring ADDNODE: Node not found"
-                                                               <<" Adding block to emerge queue."
-                                                               <<std::endl;
-                                               m_emerge_queue.addBlock(peer_id,
-                                                               getNodeBlockPos(p_above), BLOCK_EMERGE_FLAG_FROMDISK);
-                                               cannot_place_node = true;
-                                       }
-
-                                       if(cannot_place_node)
-                                       {
-                                               // Client probably has wrong data.
-                                               // Set block not sent, so that client will get
-                                               // a valid one.
-                                               RemoteClient *client = getClient(peer_id);
-                                               v3s16 blockpos = getNodeBlockPos(p_above);
-                                               client->SetBlockNotSent(blockpos);
-                                               return;
-                                       }
-
-                                       // Reset build time counter
-                                       getClient(peer_id)->m_time_from_building = 0.0;
-                                       
-                                       // Create node data
-                                       MaterialItem *mitem = (MaterialItem*)item;
-                                       MapNode n;
-                                       n.setContent(mitem->getMaterial());
-
-                                       actionstream<<player->getName()<<" places material "
-                                                       <<(int)mitem->getMaterial()
-                                                       <<" at "<<PP(p_under)<<std::endl;
-                               
-                                       // Calculate direction for wall mounted stuff
-                                       if(m_nodedef->get(n).wall_mounted)
-                                               n.param2 = packDir(p_under - p_above);
-
-                                       // Calculate the direction for furnaces and chests and stuff
-                                       if(m_nodedef->get(n).param_type == CPT_FACEDIR_SIMPLE)
-                                       {
-                                               v3f playerpos = player->getPosition();
-                                               v3f blockpos = intToFloat(p_above, BS) - playerpos;
-                                               blockpos = blockpos.normalize();
-                                               n.param1 = 0;
-                                               if (fabs(blockpos.X) > fabs(blockpos.Z)) {
-                                                       if (blockpos.X < 0)
-                                                               n.param1 = 3;
-                                                       else
-                                                               n.param1 = 1;
-                                               } else {
-                                                       if (blockpos.Z < 0)
-                                                               n.param1 = 2;
-                                                       else
-                                                               n.param1 = 0;
-                                               }
-                                       }
+                       ItemStack item = srp->getWieldedItem();
 
-                                       /*
-                                               Send to all close-by players
-                                       */
-                                       core::list<u16> far_players;
-                                       sendAddNode(p_above, n, 0, &far_players, 30);
-                                       
-                                       /*
-                                               Handle inventory
-                                       */
-                                       InventoryList *ilist = player->inventory.getList("main");
-                                       if(g_settings->getBool("creative_mode") == false && ilist)
-                                       {
-                                               // Remove from inventory and send inventory
-                                               if(mitem->getCount() == 1)
-                                                       ilist->deleteItem(item_i);
-                                               else
-                                                       mitem->remove(1);
-                                       }
-                                       
-                                       /*
-                                               Add node.
-
-                                               This takes some time so it is done after the quick stuff
-                                       */
-                                       core::map<v3s16, MapBlock*> modified_blocks;
-                                       {
-                                               MapEditEventIgnorer ign(&m_ignore_map_edit_events);
-
-                                               std::string p_name = std::string(player->getName());
-                                               m_env->getMap().addNodeAndUpdate(p_above, n, modified_blocks, p_name);
-                                       }
-                                       /*
-                                               Set blocks not sent to far players
-                                       */
-                                       for(core::list<u16>::Iterator
-                                                       i = far_players.begin();
-                                                       i != far_players.end(); i++)
-                                       {
-                                               u16 peer_id = *i;
-                                               RemoteClient *client = getClient(peer_id);
-                                               if(client==NULL)
-                                                       continue;
-                                               client->SetBlocksNotSent(modified_blocks);
-                                       }
-
-                                       /*
-                                               Run script hook
-                                       */
-                                       scriptapi_environment_on_placenode(m_lua, p_above, n, srp);
-
-                                       /*
-                                               Calculate special events
-                                       */
-                                       
-                                       /*if(n.d == LEGN(m_nodedef, "CONTENT_MESE"))
-                                       {
-                                               u32 count = 0;
-                                               for(s16 z=-1; z<=1; z++)
-                                               for(s16 y=-1; y<=1; y++)
-                                               for(s16 x=-1; x<=1; x++)
-                                               {
-                                                       
-                                               }
-                                       }*/
-                               }
-                               /*
-                                       Place other item (not a block)
-                               */
-                               else
-                               {
-                                       if(!build_priv)
-                                       {
-                                               infostream<<"Not allowing player to place item: "
-                                                               "no build privileges"<<std::endl;
-                                               return;
-                                       }
-
-                                       // Calculate a position for it
-                                       v3f pos = player_pos;
-                                       if(pointed.type == POINTEDTHING_NOTHING)
-                                       {
-                                               infostream<<"Not allowing player to place item: "
-                                                               "pointing to nothing"<<std::endl;
-                                               return;
-                                       }
-                                       else if(pointed.type == POINTEDTHING_NODE)
-                                       {
-                                               pos = intToFloat(p_above, BS);
-                                       }
-                                       else if(pointed.type == POINTEDTHING_OBJECT)
-                                       {
-                                               pos = pointed_object->getBasePosition();
-
-                                               // Randomize a bit
-                                               pos.X += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
-                                               pos.Z += BS*0.2*(float)myrand_range(-1000,1000)/1000.0;
-                                       }
-
-                                       //pos.Y -= BS*0.45;
-                                       //pos.Y -= BS*0.25; // let it drop a bit
-
-                                       /*
-                                               Check that the block is loaded so that the item
-                                               can properly be added to the static list too
-                                       */
-                                       v3s16 blockpos = getNodeBlockPos(floatToInt(pos, BS));
-                                       MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
-                                       if(block==NULL)
-                                       {
-                                               infostream<<"Error while placing item: "
-                                                               "block not found"<<std::endl;
-                                               return;
-                                       }
+                       // Reset build time counter
+                       if(pointed.type == POINTEDTHING_NODE &&
+                                       item.getDefinition(m_itemdef).type == ITEM_NODE)
+                               getClient(peer_id)->m_time_from_building = 0.0;
 
-                                       actionstream<<player->getName()<<" places "<<item->getName()
-                                                       <<" at "<<PP(pos)<<std::endl;
-
-                                       /*
-                                               Place the item
-                                       */
-                                       bool remove = item->dropOrPlace(m_env, srp, pos, true, -1);
-                                       if(remove && g_settings->getBool("creative_mode") == false)
-                                       {
-                                               InventoryList *ilist = player->inventory.getList("main");
-                                               if(ilist)
-                                                       // Remove from inventory and send inventory
-                                                       ilist->deleteItem(item_i);
-                                       }
-                               }
-                       }
-                       else if(pointed.type == POINTEDTHING_OBJECT)
+                       if(pointed.type == POINTEDTHING_OBJECT)
                        {
                                // Right click object
 
-                               if(!build_priv)
-                                       return;
-
                                // Skip if object has been removed
                                if(pointed_object->m_removed)
                                        return;
@@ -3495,6 +3021,15 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                // Do stuff
                                pointed_object->rightClick(srp);
                        }
+                       else if(scriptapi_item_on_place(m_lua,
+                                       item, srp, pointed))
+                       {
+                               // Placement was handled in lua
+
+                               // Apply returned ItemStack
+                               if(g_settings->getBool("creative_mode") == false)
+                                       srp->setWieldedItem(item);
+                       }
 
                } // action == 3
 
@@ -3503,35 +3038,17 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                */
                else if(action == 4)
                {
-                       InventoryList *ilist = player->inventory.getList("main");
-                       if(ilist == NULL)
-                               return;
-
-                       // Get item
-                       InventoryItem *item = ilist->getItem(item_i);
-                       
-                       // If there is no item, it is not possible to add it anywhere
-                       if(item == NULL)
-                               return;
+                       ItemStack item = srp->getWieldedItem();
 
-                       // Requires build privs
-                       if(!build_priv)
-                       {
-                               infostream<<"Not allowing player to use item: "
-                                               "no build privileges"<<std::endl;
-                               return;
-                       }
-
-                       actionstream<<player->getName()<<" uses "<<item->getName()
+                       actionstream<<player->getName()<<" uses "<<item.name
                                        <<", pointing at "<<pointed.dump()<<std::endl;
 
-                       bool remove = item->use(m_env, srp, pointed);
-                       if(remove && g_settings->getBool("creative_mode") == false)
+                       if(scriptapi_item_on_use(m_lua,
+                                       item, srp, pointed))
                        {
-                               InventoryList *ilist = player->inventory.getList("main");
-                               if(ilist)
-                                       // Remove from inventory and send inventory
-                                       ilist->deleteItem(item_i);
+                               // Apply returned ItemStack
+                               if(g_settings->getBool("creative_mode") == false)
+                                       srp->setWieldedItem(item);
                        }
 
                } // action == 4
@@ -3544,14 +3061,6 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        infostream<<"WARNING: Server: Invalid action "
                                        <<action<<std::endl;
                }
-
-               // Complete add_to_inventory_later
-               srp->completeAddToInventoryLater(item_i);
-
-               // Send inventory
-               // FIXME: Shouldn't be done unless something changed.
-               UpdateCrafting(player->peer_id);
-               SendInventory(player->peer_id);
        }
        else
        {
@@ -3577,57 +3086,83 @@ void Server::onMapEditEvent(MapEditEvent *event)
        m_unsent_map_edit_queue.push_back(e);
 }
 
-Inventory* Server::getInventory(InventoryContext *c, std::string id)
+Inventory* Server::getInventory(const InventoryLocation &loc)
 {
-       if(id == "current_player")
+       switch(loc.type){
+       case InventoryLocation::UNDEFINED:
+       {}
+       break;
+       case InventoryLocation::CURRENT_PLAYER:
+       {}
+       break;
+       case InventoryLocation::PLAYER:
        {
-               assert(c->current_player);
-               return &(c->current_player->inventory);
+               Player *player = m_env->getPlayer(loc.name.c_str());
+               if(!player)
+                       return NULL;
+               return &player->inventory;
        }
-       
-       Strfnd fn(id);
-       std::string id0 = fn.next(":");
-
-       if(id0 == "nodemeta")
+       break;
+       case InventoryLocation::NODEMETA:
        {
-               v3s16 p;
-               p.X = stoi(fn.next(","));
-               p.Y = stoi(fn.next(","));
-               p.Z = stoi(fn.next(","));
-               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
-               if(meta)
-                       return meta->getInventory();
-               infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
-                               <<"no metadata found"<<std::endl;
-               return NULL;
+               NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
+               if(!meta)
+                       return NULL;
+               return meta->getInventory();
+       }
+       break;
+       default:
+               assert(0);
        }
-
-       infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
        return NULL;
 }
-void Server::inventoryModified(InventoryContext *c, std::string id)
+std::string Server::getInventoryOwner(const InventoryLocation &loc)
 {
-       if(id == "current_player")
+       switch(loc.type){
+       case InventoryLocation::UNDEFINED:
+       {}
+       break;
+       case InventoryLocation::CURRENT_PLAYER:
+       {}
+       break;
+       case InventoryLocation::PLAYER:
        {
-               assert(c->current_player);
-               // Send inventory
-               UpdateCrafting(c->current_player->peer_id);
-               SendInventory(c->current_player->peer_id);
-               return;
+               return loc.name;
        }
-       
-       Strfnd fn(id);
-       std::string id0 = fn.next(":");
-
-       if(id0 == "nodemeta")
+       break;
+       case InventoryLocation::NODEMETA:
        {
-               v3s16 p;
-               p.X = stoi(fn.next(","));
-               p.Y = stoi(fn.next(","));
-               p.Z = stoi(fn.next(","));
-               v3s16 blockpos = getNodeBlockPos(p);
+               NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
+               if(!meta)
+                       return "";
+               return meta->getOwner();
+       }
+       break;
+       default:
+               assert(0);
+       }
+       return "";
+}
+void Server::setInventoryModified(const InventoryLocation &loc)
+{
+       switch(loc.type){
+       case InventoryLocation::UNDEFINED:
+       {}
+       break;
+       case InventoryLocation::PLAYER:
+       {
+               ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>
+                               (m_env->getPlayer(loc.name.c_str()));
+               if(!srp)
+                       return;
+               srp->m_inventory_not_sent = true;
+       }
+       break;
+       case InventoryLocation::NODEMETA:
+       {
+               v3s16 blockpos = getNodeBlockPos(loc.p);
 
-               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
+               NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p);
                if(meta)
                        meta->inventoryModified();
                
@@ -3636,11 +3171,11 @@ void Server::inventoryModified(InventoryContext *c, std::string id)
                        block->raiseModified(MOD_STATE_WRITE_NEEDED);
                
                setBlockNotSent(blockpos);
-
-               return;
        }
-
-       infostream<<__FUNCTION_NAME<<": unknown id "<<id<<std::endl;
+       break;
+       default:
+               assert(0);
+       }
 }
 
 core::list<PlayerInfo> Server::getPlayerInfo()
@@ -3763,8 +3298,8 @@ void Server::SendDeathscreen(con::Connection &con, u16 peer_id,
        con.Send(peer_id, 0, data, true);
 }
 
-void Server::SendToolDef(con::Connection &con, u16 peer_id,
-               IToolDefManager *tooldef)
+void Server::SendItemDef(con::Connection &con, u16 peer_id,
+               IItemDefManager *itemdef)
 {
        DSTACK(__FUNCTION_NAME);
        std::ostringstream os(std::ios_base::binary);
@@ -3772,16 +3307,18 @@ void Server::SendToolDef(con::Connection &con, u16 peer_id,
        /*
                u16 command
                u32 length of the next item
-               serialized ToolDefManager
+               zlib-compressed serialized ItemDefManager
        */
-       writeU16(os, TOCLIENT_TOOLDEF);
+       writeU16(os, TOCLIENT_ITEMDEF);
        std::ostringstream tmp_os(std::ios::binary);
-       tooldef->serialize(tmp_os);
-       os<<serializeLongString(tmp_os.str());
+       itemdef->serialize(tmp_os);
+       std::ostringstream tmp_os2(std::ios::binary);
+       compressZlib(tmp_os.str(), tmp_os2);
+       os<<serializeLongString(tmp_os2.str());
 
        // Make data buffer
        std::string s = os.str();
-       infostream<<"Server::SendToolDef(): Sending tool definitions: size="
+       infostream<<"Server::SendItemDef(): Sending item definitions: size="
                        <<s.size()<<std::endl;
        SharedBuffer<u8> data((u8*)s.c_str(), s.size());
        // Send as reliable
@@ -3797,12 +3334,14 @@ void Server::SendNodeDef(con::Connection &con, u16 peer_id,
        /*
                u16 command
                u32 length of the next item
-               serialized NodeDefManager
+               zlib-compressed serialized NodeDefManager
        */
        writeU16(os, TOCLIENT_NODEDEF);
        std::ostringstream tmp_os(std::ios::binary);
        nodedef->serialize(tmp_os);
-       os<<serializeLongString(tmp_os.str());
+       std::ostringstream tmp_os2(std::ios::binary);
+       compressZlib(tmp_os.str(), tmp_os2);
+       os<<serializeLongString(tmp_os2.str());
 
        // Make data buffer
        std::string s = os.str();
@@ -3813,100 +3352,20 @@ void Server::SendNodeDef(con::Connection &con, u16 peer_id,
        con.Send(peer_id, 0, data, true);
 }
 
-void Server::SendCraftItemDef(con::Connection &con, u16 peer_id,
-               ICraftItemDefManager *craftitemdef)
-{
-       DSTACK(__FUNCTION_NAME);
-       std::ostringstream os(std::ios_base::binary);
-
-       /*
-               u16 command
-               u32 length of the next item
-               serialized CraftItemDefManager
-       */
-       writeU16(os, TOCLIENT_CRAFTITEMDEF);
-       std::ostringstream tmp_os(std::ios::binary);
-       craftitemdef->serialize(tmp_os);
-       os<<serializeLongString(tmp_os.str());
-
-       // Make data buffer
-       std::string s = os.str();
-       infostream<<"Server::SendCraftItemDef(): Sending craft item definitions: size="
-                       <<s.size()<<std::endl;
-       SharedBuffer<u8> data((u8*)s.c_str(), s.size());
-       // Send as reliable
-       con.Send(peer_id, 0, data, true);
-}
-
 /*
        Non-static send methods
 */
 
-void Server::SendObjectData(float dtime)
-{
-       DSTACK(__FUNCTION_NAME);
-
-       core::map<v3s16, bool> stepped_blocks;
-       
-       for(core::map<u16, RemoteClient*>::Iterator
-               i = m_clients.getIterator();
-               i.atEnd() == false; i++)
-       {
-               u16 peer_id = i.getNode()->getKey();
-               RemoteClient *client = i.getNode()->getValue();
-               assert(client->peer_id == peer_id);
-               
-               if(client->serialization_version == SER_FMT_VER_INVALID)
-                       continue;
-               
-               client->SendObjectData(this, dtime, stepped_blocks);
-       }
-}
-
-void Server::SendPlayerInfos()
-{
-       DSTACK(__FUNCTION_NAME);
-
-       //JMutexAutoLock envlock(m_env_mutex);
-       
-       // Get connected players
-       core::list<Player*> players = m_env->getPlayers(true);
-       
-       u32 player_count = players.getSize();
-       u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
-
-       SharedBuffer<u8> data(datasize);
-       writeU16(&data[0], TOCLIENT_PLAYERINFO);
-       
-       u32 start = 2;
-       core::list<Player*>::Iterator i;
-       for(i = players.begin();
-                       i != players.end(); i++)
-       {
-               Player *player = *i;
-
-               /*infostream<<"Server sending player info for player with "
-                               "peer_id="<<player->peer_id<<std::endl;*/
-               
-               writeU16(&data[start], player->peer_id);
-               memset((char*)&data[start+2], 0, PLAYERNAME_SIZE);
-               snprintf((char*)&data[start+2], PLAYERNAME_SIZE, "%s", player->getName());
-               start += 2+PLAYERNAME_SIZE;
-       }
-
-       //JMutexAutoLock conlock(m_con_mutex);
-
-       // Send as reliable
-       m_con.SendToAll(0, data, true);
-}
-
 void Server::SendInventory(u16 peer_id)
 {
        DSTACK(__FUNCTION_NAME);
        
-       Player* player = m_env->getPlayer(peer_id);
+       ServerRemotePlayer* player =
+                       static_cast<ServerRemotePlayer*>(m_env->getPlayer(peer_id));
        assert(player);
 
+       player->m_inventory_not_sent = false;
+
        /*
                Serialize it
        */
@@ -3926,28 +3385,18 @@ void Server::SendInventory(u16 peer_id)
        m_con.Send(peer_id, 0, data, true);
 }
 
-std::string getWieldedItemString(const Player *player)
-{
-       const InventoryItem *item = player->getWieldItem();
-       if (item == NULL)
-               return std::string("");
-       std::ostringstream os(std::ios_base::binary);
-       item->serialize(os);
-       return os.str();
-}
-
-void Server::SendWieldedItem(const Player* player)
+void Server::SendWieldedItem(const ServerRemotePlayer* srp)
 {
        DSTACK(__FUNCTION_NAME);
 
-       assert(player);
+       assert(srp);
 
        std::ostringstream os(std::ios_base::binary);
 
        writeU16(os, TOCLIENT_PLAYERITEM);
        writeU16(os, 1);
-       writeU16(os, player->peer_id);
-       os<<serializeString(getWieldedItemString(player));
+       writeU16(os, srp->peer_id);
+       os<<serializeString(srp->getWieldedItem().getItemString());
 
        // Make data buffer
        std::string s = os.str();
@@ -3969,8 +3418,10 @@ void Server::SendPlayerItems()
        for(i = players.begin(); i != players.end(); ++i)
        {
                Player *p = *i;
+               ServerRemotePlayer *srp =
+                       static_cast<ServerRemotePlayer*>(p);
                writeU16(os, p->peer_id);
-               os<<serializeString(getWieldedItemString(p));
+               os<<serializeString(srp->getWieldedItem().getItemString());
        }
 
        // Make data buffer
@@ -4029,6 +3480,7 @@ void Server::BroadcastChatMessage(const std::wstring &message)
 void Server::SendPlayerHP(Player *player)
 {
        SendHP(m_con, player->peer_id, player->hp);
+       static_cast<ServerRemotePlayer*>(player)->m_hp_not_sent = false;
 }
 
 void Server::SendMovePlayer(Player *player)
@@ -4201,7 +3653,7 @@ void Server::SendBlockNoLock(u16 peer_id, MapBlock *block, u8 ver)
        */
        
        std::ostringstream os(std::ios_base::binary);
-       block->serialize(os, ver);
+       block->serialize(os, ver, false);
        std::string s = os.str();
        SharedBuffer<u8> blockdata((u8*)s.c_str(), s.size());
 
@@ -4229,7 +3681,7 @@ void Server::SendBlocks(float dtime)
        JMutexAutoLock envlock(m_env_mutex);
        JMutexAutoLock conlock(m_con_mutex);
 
-       //TimeTaker timer("Server::SendBlocks");
+       ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
 
        core::array<PrioritySortedBlockTransfer> queue;
 
@@ -4245,6 +3697,11 @@ void Server::SendBlocks(float dtime)
                        RemoteClient *client = i.getNode()->getValue();
                        assert(client->peer_id == i.getNode()->getKey());
 
+                       // If definitions and textures have not been sent, don't
+                       // send MapBlocks either
+                       if(!client->definitions_sent)
+                               continue;
+
                        total_sending += client->SendingCount();
                        
                        if(client->serialization_version == SER_FMT_VER_INVALID)
@@ -4288,6 +3745,135 @@ void Server::SendBlocks(float dtime)
        }
 }
 
+void Server::PrepareTextures() {
+       DSTACK(__FUNCTION_NAME);
+
+       infostream<<"Server::PrepareTextures(): Calculate sha1 sums of textures"<<std::endl;
+
+       for(core::list<ModSpec>::Iterator i = m_mods.begin();
+                                       i != m_mods.end(); i++){
+                       const ModSpec &mod = *i;
+                       std::string texturepath = mod.path + DIR_DELIM + "textures";
+                       std::vector<fs::DirListNode> dirlist = fs::GetDirListing(texturepath);
+                       for(u32 j=0; j<dirlist.size(); j++){
+                               if(dirlist[j].dir) // Ignode dirs
+                                       continue;
+                               std::string tname = dirlist[j].name;
+                               // if name contains illegal characters, ignore the texture
+                               if(!string_allowed(tname, TEXTURENAME_ALLOWED_CHARS)){
+                                       errorstream<<"Server: ignoring illegal texture name: \""
+                                                       <<tname<<"\""<<std::endl;
+                                       continue;
+                               }
+                               std::string tpath = texturepath + DIR_DELIM + tname;
+                               // Read data
+                               std::ifstream fis(tpath.c_str(), std::ios_base::binary);
+                               if(fis.good() == false){
+                                       errorstream<<"Server::PrepareTextures(): Could not open \""
+                                                       <<tname<<"\" for reading"<<std::endl;
+                                       continue;
+                               }
+                               std::ostringstream tmp_os(std::ios_base::binary);
+                               bool bad = false;
+                               for(;;){
+                                       char buf[1024];
+                                       fis.read(buf, 1024);
+                                       std::streamsize len = fis.gcount();
+                                       tmp_os.write(buf, len);
+                                       if(fis.eof())
+                                               break;
+                                       if(!fis.good()){
+                                               bad = true;
+                                               break;
+                                       }
+                               }
+                               if(bad){
+                                       errorstream<<"Server::PrepareTextures(): Failed to read \""
+                                                       <<tname<<"\""<<std::endl;
+                                       continue;
+                               }
+                               if(tmp_os.str().length() == 0){
+                                       errorstream<<"Server::PrepareTextures(): Empty file \""
+                                                       <<tpath<<"\""<<std::endl;
+                                       continue;
+                               }
+
+                               SHA1 sha1;
+                               sha1.addBytes(tmp_os.str().c_str(), tmp_os.str().length());
+
+                               unsigned char *digest = sha1.getDigest();
+                               std::string digest_string = base64_encode(digest, 20);
+
+                               free(digest);
+
+                               // Put in list
+                               this->m_Textures[tname] = TextureInformation(tpath,digest_string);
+                               infostream<<"Server::PrepareTextures(): added sha1 for "<< tname <<std::endl;
+                       }
+       }
+}
+
+struct SendableTextureAnnouncement
+       {
+               std::string name;
+               std::string sha1_digest;
+
+               SendableTextureAnnouncement(const std::string name_="",
+                               const std::string sha1_digest_=""):
+                       name(name_),
+                       sha1_digest(sha1_digest_)
+               {
+               }
+       };
+
+void Server::SendTextureAnnouncement(u16 peer_id){
+       DSTACK(__FUNCTION_NAME);
+
+       infostream<<"Server::SendTextureAnnouncement()"<<std::endl;
+
+       core::list<SendableTextureAnnouncement> texture_announcements;
+
+       for (std::map<std::string,TextureInformation>::iterator i = m_Textures.begin();i != m_Textures.end(); i++ ) {
+
+               // Put in list
+               texture_announcements.push_back(
+                               SendableTextureAnnouncement(i->first, i->second.sha1_digest));
+       }
+
+       //send announcements
+
+       /*
+               u16 command
+               u32 number of textures
+               for each texture {
+                       u16 length of name
+                       string name
+                       u16 length of digest string
+                       string sha1_digest
+               }
+       */
+       std::ostringstream os(std::ios_base::binary);
+
+       writeU16(os,    TOCLIENT_ANNOUNCE_TEXTURES);
+       writeU16(os, texture_announcements.size());
+
+       for(core::list<SendableTextureAnnouncement>::Iterator
+                       j = texture_announcements.begin();
+                       j != texture_announcements.end(); j++){
+               os<<serializeString(j->name);
+               os<<serializeString(j->sha1_digest);
+       }
+
+       // Make data buffer
+       std::string s = os.str();
+       infostream<<"Server::SendTextureAnnouncement(): Send to client"<<std::endl;
+       SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+
+       // Send as reliable
+       m_con.Send(peer_id, 0, data, true);
+
+}
+
 struct SendableTexture
 {
        std::string name;
@@ -4302,159 +3888,146 @@ struct SendableTexture
        {}
 };
 
-void Server::SendTextures(u16 peer_id)
-{
+void Server::SendTexturesRequested(u16 peer_id,core::list<TextureRequest> tosend) {
        DSTACK(__FUNCTION_NAME);
 
-       infostream<<"Server::SendTextures(): Sending textures to client"<<std::endl;
-       
+       infostream<<"Server::SendTexturesRequested(): Sending textures to client"<<std::endl;
+
        /* Read textures */
-       
+
        // Put 5kB in one bunch (this is not accurate)
        u32 bytes_per_bunch = 5000;
-       
+
        core::array< core::list<SendableTexture> > texture_bunches;
        texture_bunches.push_back(core::list<SendableTexture>());
-       
+
        u32 texture_size_bunch_total = 0;
-       core::list<ModSpec> mods = getMods(m_modspaths);
-       for(core::list<ModSpec>::Iterator i = mods.begin();
-                       i != mods.end(); i++){
-               ModSpec mod = *i;
-               std::string texturepath = mod.path + DIR_DELIM + "textures";
-               std::vector<fs::DirListNode> dirlist = fs::GetDirListing(texturepath);
-               for(u32 j=0; j<dirlist.size(); j++){
-                       if(dirlist[j].dir) // Ignode dirs
-                               continue;
-                       std::string tname = dirlist[j].name;
-                       std::string tpath = texturepath + DIR_DELIM + tname;
-                       // Read data
-                       std::ifstream fis(tpath.c_str(), std::ios_base::binary);
-                       if(fis.good() == false){
-                               errorstream<<"Server::SendTextures(): Could not open \""
-                                               <<tname<<"\" for reading"<<std::endl;
-                               continue;
-                       }
-                       std::ostringstream tmp_os(std::ios_base::binary);
-                       bool bad = false;
-                       for(;;){
-                               char buf[1024];
-                               fis.read(buf, 1024);
-                               std::streamsize len = fis.gcount();
-                               tmp_os.write(buf, len);
-                               texture_size_bunch_total += len;
-                               if(fis.eof())
-                                       break;
-                               if(!fis.good()){
-                                       bad = true;
-                                       break;
-                               }
-                       }
-                       if(bad){
-                               errorstream<<"Server::SendTextures(): Failed to read \""
-                                               <<tname<<"\""<<std::endl;
-                               continue;
-                       }
-                       /*infostream<<"Server::SendTextures(): Loaded \""
-                                       <<tname<<"\""<<std::endl;*/
-                       // Put in list
-                       texture_bunches[texture_bunches.size()-1].push_back(
-                                       SendableTexture(tname, tpath, tmp_os.str()));
-                       
-                       // Start next bunch if got enough data
-                       if(texture_size_bunch_total >= bytes_per_bunch){
-                               texture_bunches.push_back(core::list<SendableTexture>());
-                               texture_size_bunch_total = 0;
+
+       for(core::list<TextureRequest>::Iterator i = tosend.begin(); i != tosend.end(); i++) {
+               if(m_Textures.find(i->name) == m_Textures.end()){
+                       errorstream<<"Server::SendTexturesRequested(): Client asked for "
+                                       <<"unknown texture \""<<(i->name)<<"\""<<std::endl;
+                       continue;
+               }
+
+               //TODO get path + name
+               std::string tpath = m_Textures[(*i).name].path;
+
+               // Read data
+               std::ifstream fis(tpath.c_str(), std::ios_base::binary);
+               if(fis.good() == false){
+                       errorstream<<"Server::SendTexturesRequested(): Could not open \""
+                                       <<tpath<<"\" for reading"<<std::endl;
+                       continue;
+               }
+               std::ostringstream tmp_os(std::ios_base::binary);
+               bool bad = false;
+               for(;;){
+                       char buf[1024];
+                       fis.read(buf, 1024);
+                       std::streamsize len = fis.gcount();
+                       tmp_os.write(buf, len);
+                       texture_size_bunch_total += len;
+                       if(fis.eof())
+                               break;
+                       if(!fis.good()){
+                               bad = true;
+                               break;
                        }
                }
+               if(bad){
+                       errorstream<<"Server::SendTexturesRequested(): Failed to read \""
+                                       <<(*i).name<<"\""<<std::endl;
+                       continue;
+               }
+               /*infostream<<"Server::SendTexturesRequested(): Loaded \""
+                               <<tname<<"\""<<std::endl;*/
+               // Put in list
+               texture_bunches[texture_bunches.size()-1].push_back(
+                               SendableTexture((*i).name, tpath, tmp_os.str()));
+
+               // Start next bunch if got enough data
+               if(texture_size_bunch_total >= bytes_per_bunch){
+                       texture_bunches.push_back(core::list<SendableTexture>());
+                       texture_size_bunch_total = 0;
+               }
+
        }
 
        /* Create and send packets */
-       
-       u32 num_bunches = texture_bunches.size();
-       for(u32 i=0; i<num_bunches; i++)
-       {
-               /*
-                       u16 command
-                       u16 total number of texture bunches
-                       u16 index of this bunch
-                       u32 number of textures in this bunch
-                       for each texture {
-                               u16 length of name
-                               string name
-                               u32 length of data
-                               data
+
+               u32 num_bunches = texture_bunches.size();
+               for(u32 i=0; i<num_bunches; i++)
+               {
+                       /*
+                               u16 command
+                               u16 total number of texture bunches
+                               u16 index of this bunch
+                               u32 number of textures in this bunch
+                               for each texture {
+                                       u16 length of name
+                                       string name
+                                       u32 length of data
+                                       data
+                               }
+                       */
+                       std::ostringstream os(std::ios_base::binary);
+
+                       writeU16(os, TOCLIENT_TEXTURES);
+                       writeU16(os, num_bunches);
+                       writeU16(os, i);
+                       writeU32(os, texture_bunches[i].size());
+
+                       for(core::list<SendableTexture>::Iterator
+                                       j = texture_bunches[i].begin();
+                                       j != texture_bunches[i].end(); j++){
+                               os<<serializeString(j->name);
+                               os<<serializeLongString(j->data);
                        }
-               */
-               std::ostringstream os(std::ios_base::binary);
 
-               writeU16(os, TOCLIENT_TEXTURES);
-               writeU16(os, num_bunches);
-               writeU16(os, i);
-               writeU32(os, texture_bunches[i].size());
-               
-               for(core::list<SendableTexture>::Iterator
-                               j = texture_bunches[i].begin();
-                               j != texture_bunches[i].end(); j++){
-                       os<<serializeString(j->name);
-                       os<<serializeLongString(j->data);
+                       // Make data buffer
+                       std::string s = os.str();
+                       infostream<<"Server::SendTexturesRequested(): bunch "<<i<<"/"<<num_bunches
+                                       <<" textures="<<texture_bunches[i].size()
+                                       <<" size=" <<s.size()<<std::endl;
+                       SharedBuffer<u8> data((u8*)s.c_str(), s.size());
+                       // Send as reliable
+                       m_con.Send(peer_id, 0, data, true);
                }
-               
-               // Make data buffer
-               std::string s = os.str();
-               infostream<<"Server::SendTextures(): bunch "<<i<<"/"<<num_bunches
-                               <<" textures="<<texture_bunches[i].size()
-                               <<" size=" <<s.size()<<std::endl;
-               SharedBuffer<u8> data((u8*)s.c_str(), s.size());
-               // Send as reliable
-               m_con.Send(peer_id, 0, data, true);
-       }
+
+
 }
 
 /*
        Something random
 */
 
-void Server::HandlePlayerHP(Player *player, s16 damage)
+void Server::DiePlayer(Player *player)
 {
-       if(player->hp > damage)
-       {
-               player->hp -= damage;
-               SendPlayerHP(player);
-       }
-       else
-       {
-               infostream<<"Server::HandlePlayerHP(): Player "
-                               <<player->getName()<<" dies"<<std::endl;
-               
-               player->hp = 0;
-               
-               //TODO: Throw items around
-               
-               // Handle players that are not connected
-               if(player->peer_id == PEER_ID_INEXISTENT){
-                       RespawnPlayer(player);
-                       return;
-               }
+       ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
 
-               SendPlayerHP(player);
-               
-               RemoteClient *client = getClient(player->peer_id);
-               if(client->net_proto_version >= 3)
-               {
-                       SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
-               }
-               else
-               {
-                       RespawnPlayer(player);
-               }
+       infostream<<"Server::DiePlayer(): Player "
+                       <<player->getName()<<" dies"<<std::endl;
+       
+       srp->setHP(0);
+       
+       // Trigger scripted stuff
+       scriptapi_on_dieplayer(m_lua, srp);
+       
+       // Handle players that are not connected
+       if(player->peer_id == PEER_ID_INEXISTENT){
+               RespawnPlayer(player);
+               return;
        }
+
+       SendPlayerHP(player);
+       SendDeathscreen(m_con, player->peer_id, false, v3f(0,0,0));
 }
 
 void Server::RespawnPlayer(Player *player)
 {
-       player->hp = 20;
        ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
+       srp->setHP(20);
        bool repositioned = scriptapi_on_respawnplayer(m_lua, srp);
        if(!repositioned){
                v3f pos = findSpawnPos(m_env->getServerMap());
@@ -4473,41 +4046,17 @@ void Server::UpdateCrafting(u16 peer_id)
        Player* player = m_env->getPlayer(peer_id);
        assert(player);
 
-       /*
-               Calculate crafting stuff
-       */
+       // Get a preview for crafting
+       ItemStack preview;
+       // No crafting in creative mode
        if(g_settings->getBool("creative_mode") == false)
-       {
-               InventoryList *clist = player->inventory.getList("craft");
-               InventoryList *rlist = player->inventory.getList("craftresult");
+               getCraftingResult(&player->inventory, preview, false, this);
 
-               if(rlist && rlist->getUsedSlots() == 0)
-                       player->craftresult_is_preview = true;
-
-               if(rlist && player->craftresult_is_preview)
-               {
-                       rlist->clearItems();
-               }
-               if(clist && rlist && player->craftresult_is_preview)
-               {
-                       // Get result of crafting grid
-                       
-                       std::vector<InventoryItem*> items;
-                       for(u16 i=0; i<9; i++){
-                               if(clist->getItem(i) == NULL)
-                                       items.push_back(NULL);
-                               else
-                                       items.push_back(clist->getItem(i)->clone());
-                       }
-                       CraftPointerInput cpi(3, items);
-                       
-                       InventoryItem *result = m_craftdef->getCraftResult(cpi, this);
-                       //InventoryItem *result = craft_get_result(items, this);
-                       if(result)
-                               rlist->addItem(result);
-               }
-       
-       } // if creative_mode == false
+       // Put the new preview in
+       InventoryList *plist = player->inventory.getList("craftpreview");
+       assert(plist);
+       assert(plist->getSize() >= 1);
+       plist->changeItem(0, preview);
 }
 
 RemoteClient* Server::getClient(u16 peer_id)
@@ -4557,11 +4106,27 @@ std::wstring Server::getStatusString()
        return os.str();
 }
 
+void Server::setPlayerPassword(const std::string &name, const std::wstring &password)
+{
+       // Add player to auth manager
+       if(m_authmanager.exists(name) == false)
+       {
+               infostream<<"Server: adding player "<<name
+                               <<" to auth manager"<<std::endl;
+               m_authmanager.add(name);
+               m_authmanager.setPrivs(name,
+                       stringToPrivs(g_settings->get("default_privs")));
+       }
+       // Change password and save
+       m_authmanager.setPassword(name, translatePassword(name, password));
+       m_authmanager.save();
+}
+
 // Saves g_settings to configpath given at initialization
 void Server::saveConfig()
 {
-       if(m_configpath != "")
-               g_settings->updateConfigFile(m_configpath.c_str());
+       if(m_path_config != "")
+               g_settings->updateConfigFile(m_path_config.c_str());
 }
 
 void Server::notifyPlayer(const char *name, const std::wstring msg)
@@ -4587,9 +4152,9 @@ void Server::queueBlockEmerge(v3s16 blockpos, bool allow_generate)
 
 // IGameDef interface
 // Under envlock
-IToolDefManager* Server::getToolDefManager()
+IItemDefManager* Server::getItemDefManager()
 {
-       return m_toolmgr;
+       return m_itemdef;
 }
 INodeDefManager* Server::getNodeDefManager()
 {
@@ -4599,10 +4164,6 @@ ICraftDefManager* Server::getCraftDefManager()
 {
        return m_craftdef;
 }
-ICraftItemDefManager* Server::getCraftItemDefManager()
-{
-       return m_craftitemdef;
-}
 ITextureSource* Server::getTextureSource()
 {
        return NULL;
@@ -4612,9 +4173,9 @@ u16 Server::allocateUnknownNodeId(const std::string &name)
        return m_nodedef->allocateDummy(name);
 }
 
-IWritableToolDefManager* Server::getWritableToolDefManager()
+IWritableItemDefManager* Server::getWritableItemDefManager()
 {
-       return m_toolmgr;
+       return m_itemdef;
 }
 IWritableNodeDefManager* Server::getWritableNodeDefManager()
 {
@@ -4624,9 +4185,16 @@ IWritableCraftDefManager* Server::getWritableCraftDefManager()
 {
        return m_craftdef;
 }
-IWritableCraftItemDefManager* Server::getWritableCraftItemDefManager()
+
+const ModSpec* Server::getModSpec(const std::string &modname)
 {
-       return m_craftitemdef;
+       for(core::list<ModSpec>::Iterator i = m_mods.begin();
+                       i != m_mods.end(); i++){
+               const ModSpec &mod = *i;
+               if(mod.name == modname)
+                       return &mod;
+       }
+       return NULL;
 }
 
 v3f findSpawnPos(ServerMap &map)
@@ -4692,12 +4260,13 @@ v3f findSpawnPos(ServerMap &map)
        return intToFloat(nodepos, BS);
 }
 
-Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
+ServerRemotePlayer *Server::emergePlayer(const char *name, u16 peer_id)
 {
        /*
                Try to get an existing player
        */
-       Player *player = m_env->getPlayer(name);
+       ServerRemotePlayer *player =
+                       static_cast<ServerRemotePlayer*>(m_env->getPlayer(name));
        if(player != NULL)
        {
                // If player is already connected, cancel
@@ -4710,15 +4279,24 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
                // Got one.
                player->peer_id = peer_id;
                
+               // Re-add player to environment
+               if(player->m_removed)
+               {
+                       player->m_removed = false;
+                       player->setId(0);
+                       m_env->addActiveObject(player);
+               }
+
                // Reset inventory to creative if in creative mode
                if(g_settings->getBool("creative_mode"))
                {
                        // Warning: double code below
                        // Backup actual inventory
-                       player->inventory_backup = new Inventory();
+                       player->inventory_backup = new Inventory(m_itemdef);
                        *(player->inventory_backup) = player->inventory;
                        // Set creative inventory
-                       craft_set_creative_inventory(player, this);
+                       player->resetInventory();
+                       scriptapi_get_creative_inventory(m_lua, player);
                }
 
                return player;
@@ -4738,12 +4316,6 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
                Create a new player
        */
        {
-               // Add authentication stuff
-               m_authmanager.add(name);
-               m_authmanager.setPassword(name, password);
-               m_authmanager.setPrivs(name,
-                               stringToPrivs(g_settings->get("default_privs")));
-
                /* Set player position */
                
                infostream<<"Server: Finding spawn place for player \""
@@ -4752,12 +4324,13 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
                v3f pos = findSpawnPos(m_env->getServerMap());
 
                player = new ServerRemotePlayer(m_env, pos, peer_id, name);
+               ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
 
                /* Add player to environment */
                m_env->addPlayer(player);
+               m_env->addActiveObject(srp);
 
                /* Run scripts */
-               ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
                scriptapi_on_newplayer(m_lua, srp);
 
                /* Add stuff to inventory */
@@ -4765,10 +4338,11 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
                {
                        // Warning: double code above
                        // Backup actual inventory
-                       player->inventory_backup = new Inventory();
+                       player->inventory_backup = new Inventory(m_itemdef);
                        *(player->inventory_backup) = player->inventory;
                        // Set creative inventory
-                       craft_set_creative_inventory(player, this);
+                       player->resetInventory();
+                       scriptapi_get_creative_inventory(m_lua, player);
                }
 
                return player;
@@ -4828,10 +4402,12 @@ void Server::handlePeerChange(PeerChange &c)
                                obj->m_known_by_count--;
                }
 
+               ServerRemotePlayer* player =
+                               static_cast<ServerRemotePlayer*>(m_env->getPlayer(c.peer_id));
+
                // Collect information about leaving in chat
                std::wstring message;
                {
-                       Player *player = m_env->getPlayer(c.peer_id);
                        if(player != NULL)
                        {
                                std::wstring name = narrow_to_wide(player->getName());
@@ -4842,21 +4418,19 @@ void Server::handlePeerChange(PeerChange &c)
                                        message += L" (timed out)";
                        }
                }
-
-               /*// Delete player
-               {
-                       m_env->removePlayer(c.peer_id);
-               }*/
-
+               
+               // Remove from environment
+               if(player != NULL)
+                       player->m_removed = true;
+               
                // Set player client disconnected
+               if(player != NULL)
+                       player->peer_id = 0;
+       
+               /*
+                       Print out action
+               */
                {
-                       Player *player = m_env->getPlayer(c.peer_id);
-                       if(player != NULL)
-                               player->peer_id = 0;
-                       
-                       /*
-                               Print out action
-                       */
                        if(player != NULL)
                        {
                                std::ostringstream os(std::ios_base::binary);
@@ -4888,10 +4462,11 @@ void Server::handlePeerChange(PeerChange &c)
                m_clients.remove(c.peer_id);
 
                // Send player info to all remaining clients
-               SendPlayerInfos();
+               //SendPlayerInfos();
                
                // Send leave chat message to all remaining clients
-               BroadcastChatMessage(message);
+               if(message.length() != 0)
+                       BroadcastChatMessage(message);
                
        } // PEER_REMOVED
        else
@@ -4945,13 +4520,14 @@ void dedicated_server_loop(Server &server, bool &kill)
 
        for(;;)
        {
+               float steplen = g_settings->getFloat("dedicated_server_step");
                // This is kind of a hack but can be done like this
                // because server.step() is very light
                {
                        ScopeProfiler sp(g_profiler, "dedicated server sleep");
-                       sleep_ms(30);
+                       sleep_ms((int)(steplen*1000.0));
                }
-               server.step(0.030);
+               server.step(steplen);
 
                if(server.getShutdownRequested() || kill)
                {
@@ -4966,7 +4542,7 @@ void dedicated_server_loop(Server &server, bool &kill)
                                g_settings->getFloat("profiler_print_interval");
                if(profiler_print_interval != 0)
                {
-                       if(m_profiler_interval.step(0.030, profiler_print_interval))
+                       if(m_profiler_interval.step(steplen, profiler_print_interval))
                        {
                                infostream<<"Profiler:"<<std::endl;
                                g_profiler->print(infostream);