Add ObjectRef:punch and ObjectRef:right_click to Lua API
[oweals/minetest.git] / src / server.cpp
index 3e22a023aded7a77cd05e7b395dfbda301fad514..5646c0ac9c9dffdccff84b15f7e5ee00d83ce738 100644 (file)
@@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "server.h"
 #include "utility.h"
 #include <iostream>
+#include <queue>
 #include "clientserver.h"
 #include "map.h"
 #include "jmutexautolock.h"
@@ -39,6 +40,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "settings.h"
 #include "profiler.h"
 #include "log.h"
+#include "script.h"
+#include "scriptapi.h"
+#include "nodedef.h"
+#include "tooldef.h"
+#include "craftdef.h"
+#include "craftitemdef.h"
+#include "mapgen.h"
+#include "content_abm.h"
 
 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
 
@@ -138,12 +147,7 @@ void * EmergeThread::Thread()
                /*
                        Do not generate over-limit
                */
-               if(p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-               || p.X > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-               || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-               || p.Y > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-               || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
-               || p.Z > MAP_GENERATION_LIMIT / MAP_BLOCKSIZE)
+               if(blockpos_over_limit(p))
                        continue;
                        
                //infostream<<"EmergeThread::Thread(): running"<<std::endl;
@@ -185,126 +189,108 @@ void * EmergeThread::Thread()
                                        <<"("<<p.X<<","<<p.Y<<","<<p.Z<<") "
                                        <<"only_from_disk="<<only_from_disk<<std::endl;
                
-               ServerMap &map = ((ServerMap&)m_server->m_env.getMap());
+               ServerMap &map = ((ServerMap&)m_server->m_env->getMap());
                        
-               //core::map<v3s16, MapBlock*> changed_blocks;
-               //core::map<v3s16, MapBlock*> lighting_invalidated_blocks;
-
                MapBlock *block = NULL;
                bool got_block = true;
                core::map<v3s16, MapBlock*> modified_blocks;
-               
+
                /*
-                       Fetch block from map or generate a single block
+                       Try to fetch block from memory or disk.
+                       If not found and asked to generate, initialize generator.
                */
+               
+               bool started_generate = false;
+               mapgen::BlockMakeData data;
+
                {
                        JMutexAutoLock envlock(m_server->m_env_mutex);
                        
                        // Load sector if it isn't loaded
                        if(map.getSectorNoGenerateNoEx(p2d) == NULL)
-                               //map.loadSectorFull(p2d);
                                map.loadSectorMeta(p2d);
-
+                       
+                       // Attempt to load block
                        block = map.getBlockNoCreateNoEx(p);
                        if(!block || block->isDummy() || !block->isGenerated())
                        {
                                if(enable_mapgen_debug_info)
-                                       infostream<<"EmergeThread: not in memory, loading"<<std::endl;
-
-                               // Get, load or create sector
-                               /*ServerMapSector *sector =
-                                               (ServerMapSector*)map.createSector(p2d);*/
-
-                               // Load/generate block
-
-                               /*block = map.emergeBlock(p, sector, changed_blocks,
-                                               lighting_invalidated_blocks);*/
+                                       infostream<<"EmergeThread: not in memory, "
+                                                       <<"attempting to load from disk"<<std::endl;
 
                                block = map.loadBlock(p);
-                               
-                               if(only_from_disk == false)
-                               {
-                                       if(block == NULL || block->isGenerated() == false)
-                                       {
-                                               if(enable_mapgen_debug_info)
-                                                       infostream<<"EmergeThread: generating"<<std::endl;
-                                               block = map.generateBlock(p, modified_blocks);
-                                       }
-                               }
-
+                       }
+                       
+                       // If could not load and allowed to generate, start generation
+                       // inside this same envlock
+                       if(only_from_disk == false &&
+                                       (block == NULL || block->isGenerated() == false)){
                                if(enable_mapgen_debug_info)
-                                       infostream<<"EmergeThread: ended up with: "
-                                                       <<analyze_block(block)<<std::endl;
+                                       infostream<<"EmergeThread: generating"<<std::endl;
+                               started_generate = true;
 
-                               if(block == NULL)
-                               {
-                                       got_block = false;
-                               }
-                               else
-                               {
-                                       /*
-                                               Ignore map edit events, they will not need to be
-                                               sent to anybody because the block hasn't been sent
-                                               to anybody
-                                       */
-                                       MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
-                                       
-                                       // Activate objects and stuff
-                                       m_server->m_env.activateBlock(block, 3600);
-                               }
-                       }
-                       else
-                       {
-                               /*if(block->getLightingExpired()){
-                                       lighting_invalidated_blocks[block->getPos()] = block;
-                               }*/
+                               map.initBlockMake(&data, p);
                        }
-
-                       // TODO: Some additional checking and lighting updating,
-                       //       see emergeBlock
                }
 
-               {//envlock
-               JMutexAutoLock envlock(m_server->m_env_mutex);
-               
-               if(got_block)
+               /*
+                       If generator was initialized, generate now when envlock is free.
+               */
+               if(started_generate)
                {
-                       /*
-                               Collect a list of blocks that have been modified in
-                               addition to the fetched one.
-                       */
-
-#if 0
-                       if(lighting_invalidated_blocks.size() > 0)
                        {
-                               /*infostream<<"lighting "<<lighting_invalidated_blocks.size()
-                                               <<" blocks"<<std::endl;*/
+                               ScopeProfiler sp(g_profiler, "EmergeThread: mapgen::make_block",
+                                               SPT_AVG);
+                               TimeTaker t("mapgen::make_block()");
+
+                               mapgen::make_block(&data);
+
+                               if(enable_mapgen_debug_info == false)
+                                       t.stop(true); // Hide output
+                       }
                        
-                               // 50-100ms for single block generation
-                               //TimeTaker timer("** EmergeThread updateLighting");
+                       {
+                               // Lock environment again to access the map
+                               JMutexAutoLock envlock(m_server->m_env_mutex);
                                
-                               // Update lighting without locking the environment mutex,
-                               // add modified blocks to changed blocks
-                               map.updateLighting(lighting_invalidated_blocks, modified_blocks);
-                       }
+                               ScopeProfiler sp(g_profiler, "EmergeThread: after "
+                                               "mapgen::make_block (envlock)", SPT_AVG);
+
+                               // Blit data back on map, update lighting, add mobs and
+                               // whatever this does
+                               map.finishBlockMake(&data, modified_blocks);
+
+                               // Get central block
+                               block = map.getBlockNoCreateNoEx(p);
+
+                               /*
+                                       Do some post-generate stuff
+                               */
                                
-                       // Add all from changed_blocks to modified_blocks
-                       for(core::map<v3s16, MapBlock*>::Iterator i = changed_blocks.getIterator();
-                                       i.atEnd() == false; i++)
-                       {
-                               MapBlock *block = i.getNode()->getValue();
-                               modified_blocks.insert(block->getPos(), block);
+                               v3s16 minp = block->getPos()*MAP_BLOCKSIZE;
+                               v3s16 maxp = minp + v3s16(1,1,1)*(MAP_BLOCKSIZE-1);
+                               scriptapi_environment_on_generated(m_server->m_lua,
+                                               minp, maxp);
+                               
+                               if(enable_mapgen_debug_info)
+                                       infostream<<"EmergeThread: ended up with: "
+                                                       <<analyze_block(block)<<std::endl;
+
+                               /*
+                                       Ignore map edit events, they will not need to be
+                                       sent to anybody because the block hasn't been sent
+                                       to anybody
+                               */
+                               MapEditEventIgnorer ign(&m_server->m_ignore_map_edit_events);
+                               
+                               // Activate objects and stuff
+                               m_server->m_env->activateBlock(block, 0);
                        }
-#endif
-               }
-               // If we got no block, there should be no invalidated blocks
-               else
-               {
-                       //assert(lighting_invalidated_blocks.size() == 0);
                }
 
-               }//envlock
-
+               if(block == NULL)
+                       got_block = false;
+                       
                /*
                        Set sent status of modified blocks on clients
                */
@@ -341,6 +327,8 @@ void * EmergeThread::Thread()
 
        END_DEBUG_EXCEPTION_HANDLER(errorstream)
 
+       log_deregister_thread();
+
        return NULL;
 }
 
@@ -354,11 +342,10 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
        
        // Increment timers
        m_nothing_to_send_pause_timer -= dtime;
+       m_nearest_unsent_reset_timer += dtime;
        
        if(m_nothing_to_send_pause_timer >= 0)
        {
-               // Keep this reset
-               m_nearest_unsent_reset_timer = 0;
                return;
        }
 
@@ -372,7 +359,7 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
 
        //TimeTaker timer("RemoteClient::GetNextBlocks");
        
-       Player *player = server->m_env.getPlayer(peer_id);
+       Player *player = server->m_env->getPlayer(peer_id);
 
        assert(player != NULL);
 
@@ -410,17 +397,13 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
        /*infostream<<"m_nearest_unsent_reset_timer="
                        <<m_nearest_unsent_reset_timer<<std::endl;*/
                        
-       // This has to be incremented only when the nothing to send pause
-       // is not active
-       m_nearest_unsent_reset_timer += dtime;
-       
-       // Reset periodically to avoid possible bugs or other mishaps
-       if(m_nearest_unsent_reset_timer > 10.0)
+       // Reset periodically to workaround for some bugs or stuff
+       if(m_nearest_unsent_reset_timer > 20.0)
        {
                m_nearest_unsent_reset_timer = 0;
                m_nearest_unsent_d = 0;
-               /*infostream<<"Resetting m_nearest_unsent_d for "
-                               <<server->getPlayerName(peer_id)<<std::endl;*/
+               //infostream<<"Resetting m_nearest_unsent_d for "
+               //              <<server->getPlayerName(peer_id)<<std::endl;
        }
 
        //s16 last_nearest_unsent_d = m_nearest_unsent_d;
@@ -463,22 +446,24 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
        s16 d_max_gen = g_settings->getS16("max_block_generate_distance");
        
        // Don't loop very much at a time
-       if(d_max > d_start+1)
-               d_max = d_start+1;
+       s16 max_d_increment_at_time = 2;
+       if(d_max > d_start + max_d_increment_at_time)
+               d_max = d_start + max_d_increment_at_time;
        /*if(d_max_gen > d_start+2)
                d_max_gen = d_start+2;*/
        
        //infostream<<"Starting from "<<d_start<<std::endl;
 
-       bool sending_something = false;
-
-       bool no_blocks_found_for_sending = true;
-
+       s32 nearest_emerged_d = -1;
+       s32 nearest_emergefull_d = -1;
+       s32 nearest_sent_d = -1;
        bool queue_is_full = false;
        
        s16 d;
        for(d = d_start; d <= d_max; d++)
        {
+               /*errorstream<<"checking d="<<d<<" for "
+                               <<server->getPlayerName(peer_id)<<std::endl;*/
                //infostream<<"RemoteClient::SendBlocks(): d="<<d<<std::endl;
                
                /*
@@ -550,12 +535,12 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                                if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3)
                                        generate = false;*/
 
-                               // Limit the send area vertically to 2/3
-                               if(abs(p.Y - center.Y) > d_max_gen - d_max_gen / 3)
+                               // Limit the send area vertically to 1/2
+                               if(abs(p.Y - center.Y) > d_max / 2)
                                        continue;
                        }
 
-#if 1
+#if 0
                        /*
                                If block is far away, don't generate it unless it is
                                near ground level.
@@ -575,7 +560,7 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                                        MAP_BLOCKSIZE*p.Z);
                                
                                // Get ground height in nodes
-                               s16 gh = server->m_env.getServerMap().findGroundLevel(
+                               s16 gh = server->m_env->getServerMap().findGroundLevel(
                                                p2d_nodes_center);
 
                                // If differs a lot, don't generate
@@ -588,7 +573,7 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
 #endif
 
                        //infostream<<"d="<<d<<std::endl;
-                       
+#if 1
                        /*
                                Don't generate or send if not in sight
                                FIXME This only works if the client uses a small enough
@@ -600,7 +585,7 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                        {
                                continue;
                        }
-                       
+#endif
                        /*
                                Don't send already sent blocks
                        */
@@ -614,7 +599,7 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                        /*
                                Check if map has this block
                        */
-                       MapBlock *block = server->m_env.getMap().getBlockNoCreateNoEx(p);
+                       MapBlock *block = server->m_env->getMap().getBlockNoCreateNoEx(p);
                        
                        bool surely_not_found_on_disk = false;
                        bool block_is_invalid = false;
@@ -643,7 +628,7 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
 
 #if 0
                                v2s16 p2d(p.X, p.Z);
-                               ServerMap *map = (ServerMap*)(&server->m_env.getMap());
+                               ServerMap *map = (ServerMap*)(&server->m_env->getMap());
                                v2s16 chunkpos = map->sector_to_chunk(p2d);
                                if(map->chunkNonVolatile(chunkpos) == false)
                                        block_is_invalid = true;
@@ -658,7 +643,7 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                                        Block is near ground level if night-time mesh
                                        differs from day-time mesh.
                                */
-                               if(d > 3)
+                               if(d >= 4)
                                {
                                        if(block->dayNightDiffed() == false)
                                                continue;
@@ -676,18 +661,6 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                                continue;
                        }
 
-                       /*
-                               Record the lowest d from which a block has been
-                               found being not sent and possibly to exist
-                       */
-                       if(no_blocks_found_for_sending)
-                       {
-                               if(generate == true)
-                                       new_nearest_unsent_d = d;
-                       }
-
-                       no_blocks_found_for_sending = false;
-                                       
                        /*
                                Add inexistent block to emerge queue.
                        */
@@ -697,7 +670,12 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                                // Allow only one block in emerge queue
                                //if(server->m_emerge_queue.peerItemCount(peer_id) < 1)
                                // Allow two blocks in queue per client
-                               if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
+                               //if(server->m_emerge_queue.peerItemCount(peer_id) < 2)
+                               u32 max_emerge = 25;
+                               // Make it more responsive when needing to generate stuff
+                               if(surely_not_found_on_disk)
+                                       max_emerge = 5;
+                               if(server->m_emerge_queue.peerItemCount(peer_id) < max_emerge)
                                {
                                        //infostream<<"Adding block to emerge queue"<<std::endl;
                                        
@@ -709,55 +687,63 @@ void RemoteClient::GetNextBlocks(Server *server, float dtime,
                                        
                                        server->m_emerge_queue.addBlock(peer_id, p, flags);
                                        server->m_emergethread.trigger();
+
+                                       if(nearest_emerged_d == -1)
+                                               nearest_emerged_d = d;
+                               } else {
+                                       if(nearest_emergefull_d == -1)
+                                               nearest_emergefull_d = d;
                                }
                                
                                // get next one.
                                continue;
                        }
 
+                       if(nearest_sent_d == -1)
+                               nearest_sent_d = d;
+
                        /*
                                Add block to send queue
                        */
 
+                       /*errorstream<<"sending from d="<<d<<" to "
+                                       <<server->getPlayerName(peer_id)<<std::endl;*/
+
                        PrioritySortedBlockTransfer q((float)d, p, peer_id);
 
                        dest.push_back(q);
 
                        num_blocks_selected += 1;
-                       sending_something = true;
                }
        }
 queue_full_break:
 
        //infostream<<"Stopped at "<<d<<std::endl;
        
-       if(no_blocks_found_for_sending)
-       {
-               if(queue_is_full == false)
-                       new_nearest_unsent_d = d;
+       // If nothing was found for sending and nothing was queued for
+       // emerging, continue next time browsing from here
+       if(nearest_emerged_d != -1){
+               new_nearest_unsent_d = nearest_emerged_d;
+       } else if(nearest_emergefull_d != -1){
+               new_nearest_unsent_d = nearest_emergefull_d;
+       } else {
+               if(d > g_settings->getS16("max_block_send_distance")){
+                       new_nearest_unsent_d = 0;
+                       m_nothing_to_send_pause_timer = 2.0;
+                       /*infostream<<"GetNextBlocks(): d wrapped around for "
+                                       <<server->getPlayerName(peer_id)
+                                       <<"; setting to 0 and pausing"<<std::endl;*/
+               } else {
+                       if(nearest_sent_d != -1)
+                               new_nearest_unsent_d = nearest_sent_d;
+                       else
+                               new_nearest_unsent_d = d;
+               }
        }
 
        if(new_nearest_unsent_d != -1)
                m_nearest_unsent_d = new_nearest_unsent_d;
 
-       if(sending_something == false)
-       {
-               m_nothing_to_send_counter++;
-               if((s16)m_nothing_to_send_counter >=
-                               g_settings->getS16("max_block_send_distance"))
-               {
-                       // Pause time in seconds
-                       m_nothing_to_send_pause_timer = 1.0;
-                       /*infostream<<"nothing to send to "
-                                       <<server->getPlayerName(peer_id)
-                                       <<" (d="<<d<<")"<<std::endl;*/
-               }
-       }
-       else
-       {
-               m_nothing_to_send_counter = 0;
-       }
-
        /*timer_result = timer.stop(true);
        if(timer_result != 0)
                infostream<<"GetNextBlocks duration: "<<timer_result<<" (!=0)"<<std::endl;*/
@@ -808,7 +794,7 @@ void RemoteClient::SendObjectData(
        */
        
        // Get connected players
-       core::list<Player*> players = server->m_env.getPlayers(true);
+       core::list<Player*> players = server->m_env->getPlayers(true);
 
        // Write player count
        u16 playercount = players.size();
@@ -842,31 +828,9 @@ void RemoteClient::SendObjectData(
        }
        
        /*
-               Get and write object data
-       */
-
-       /*
-               Get nearby blocks.
-               
-               For making players to be able to build to their nearby
-               environment (building is not possible on blocks that are not
-               in memory):
-               - Set blocks changed
-               - Add blocks to emerge queue if they are not found
-
-               SUGGESTION: These could be ignored from the backside of the player
+               Get and write object data (dummy, for compatibility)
        */
 
-       Player *player = server->m_env.getPlayer(peer_id);
-
-       assert(player);
-
-       v3f playerpos = player->getPosition();
-       v3f playerspeed = player->getSpeed();
-
-       v3s16 center_nodepos = floatToInt(playerpos, BS);
-       v3s16 center = getNodeBlockPos(center_nodepos);
-
        // Write block count
        writeU16(buf, 0);
        os.write((char*)buf, 2);
@@ -968,6 +932,92 @@ 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
 */
@@ -976,10 +1026,15 @@ Server::Server(
                std::string mapsavedir,
                std::string configpath
        ):
-       m_env(new ServerMap(mapsavedir), this),
+       m_env(NULL),
        m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, this),
-       m_authmanager(mapsavedir+"/auth.txt"),
-       m_banmanager(mapsavedir+"/ipban.txt"),
+       m_authmanager(mapsavedir+DIR_DELIM+"auth.txt"),
+       m_banmanager(mapsavedir+DIR_DELIM+"ipban.txt"),
+       m_lua(NULL),
+       m_toolmgr(createToolDefManager()),
+       m_nodedef(createNodeDefManager()),
+       m_craftdef(createCraftDefManager()),
+       m_craftitemdef(createCraftItemDefManager()),
        m_thread(this),
        m_emergethread(this),
        m_time_counter(0),
@@ -1001,20 +1056,74 @@ Server::Server(
        m_con_mutex.Init();
        m_step_dtime_mutex.Init();
        m_step_dtime = 0.0;
+
+       JMutexAutoLock envlock(m_env_mutex);
+       JMutexAutoLock conlock(m_con_mutex);
+
+       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");
+
+       // Initialize scripting
+       
+       infostream<<"Server: Initializing scripting"<<std::endl;
+       m_lua = script_init();
+       assert(m_lua);
+       // Export API
+       scriptapi_export(m_lua, this);
+       // Load and run builtin.lua
+       infostream<<"Server: Loading builtin Lua stuff from \""<<builtinpath
+                       <<"\""<<std::endl;
+       bool success = script_load(m_lua, builtinpath.c_str());
+       if(!success){
+               errorstream<<"Server: Failed to load and run "
+                               <<builtinpath<<std::endl;
+               assert(0);
+       }
+       // 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;
+               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());
+               if(!success){
+                       errorstream<<"Server: Failed to load and run "
+                                       <<scriptpath<<std::endl;
+                       assert(0);
+               }
+       }
+       
+       // Initialize Environment
+       
+       m_env = new ServerEnvironment(new ServerMap(mapsavedir, this), m_lua,
+                       this, this);
+
+       // Give environment reference to scripting api
+       scriptapi_add_environment(m_lua, m_env);
        
        // Register us to receive map edit events
-       m_env.getMap().addEventReceiver(this);
+       m_env->getMap().addEventReceiver(this);
 
        // If file exists, load environment metadata
-       if(fs::PathExists(m_mapsavedir+"/env_meta.txt"))
+       if(fs::PathExists(m_mapsavedir+DIR_DELIM+"env_meta.txt"))
        {
                infostream<<"Server: Loading environment metadata"<<std::endl;
-               m_env.loadMeta(m_mapsavedir);
+               m_env->loadMeta(m_mapsavedir);
        }
 
        // Load players
        infostream<<"Server: Loading players"<<std::endl;
-       m_env.deSerializePlayers(m_mapsavedir);
+       m_env->deSerializePlayers(m_mapsavedir);
+
+       /*
+               Add some test ActiveBlockModifiers to environment
+       */
+       add_legacy_abms(m_env, m_nodedef);
 }
 
 Server::~Server()
@@ -1057,13 +1166,13 @@ Server::~Server()
                        Save players
                */
                infostream<<"Server: Saving players"<<std::endl;
-               m_env.serializePlayers(m_mapsavedir);
+               m_env->serializePlayers(m_mapsavedir);
 
                /*
                        Save environment metadata
                */
                infostream<<"Server: Saving environment metadata"<<std::endl;
-               m_env.saveMeta(m_mapsavedir);
+               m_env->saveMeta(m_mapsavedir);
        }
                
        /*
@@ -1086,13 +1195,25 @@ Server::~Server()
                        {
                                u16 peer_id = i.getNode()->getKey();
                                JMutexAutoLock envlock(m_env_mutex);
-                               m_env.removePlayer(peer_id);
+                               m_env->removePlayer(peer_id);
                        }*/
                        
                        // Delete client
                        delete i.getNode()->getValue();
                }
        }
+
+       // Delete Environment
+       delete m_env;
+
+       delete m_toolmgr;
+       delete m_nodedef;
+       delete m_craftdef;
+       delete m_craftitemdef;
+       
+       // Deinitialize scripting
+       infostream<<"Server: Deinitializing scripting"<<std::endl;
+       script_deinit(m_lua);
 }
 
 void Server::start(unsigned short port)
@@ -1102,7 +1223,7 @@ void Server::start(unsigned short port)
        m_thread.stop();
        
        // Initialize connection
-       m_con.setTimeoutMs(30);
+       m_con.SetTimeoutMs(30);
        m_con.Serve(port);
 
        // Start thread
@@ -1143,6 +1264,8 @@ void Server::AsyncRunStep()
 {
        DSTACK(__FUNCTION_NAME);
        
+       g_profiler->add("Server::AsyncRunStep (num)", 1);
+       
        float dtime;
        {
                JMutexAutoLock lock1(m_step_dtime_mutex);
@@ -1150,14 +1273,15 @@ void Server::AsyncRunStep()
        }
        
        {
-               ScopeProfiler sp(g_profiler, "Server: selecting and sending "
-                               "blocks to clients");
+               ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients");
                // Send blocks to clients
                SendBlocks(dtime);
        }
        
        if(dtime < 0.001)
                return;
+       
+       g_profiler->add("Server::AsyncRunStep with dtime (num)", 1);
 
        //infostream<<"Server steps "<<dtime<<std::endl;
        //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl;
@@ -1184,7 +1308,6 @@ void Server::AsyncRunStep()
        {
                // This has to be called so that the client list gets synced
                // with the peer list of the connection
-               ScopeProfiler sp(g_profiler, "Server: peer change handling");
                handlePeerChanges();
        }
 
@@ -1199,7 +1322,7 @@ void Server::AsyncRunStep()
                u32 units = (u32)(m_time_counter*speed);
                m_time_counter -= (f32)units / speed;
                
-               m_env.setTimeOfDay((m_env.getTimeOfDay() + units) % 24000);
+               m_env->setTimeOfDay((m_env->getTimeOfDay() + units) % 24000);
                
                //infostream<<"Server: m_time_of_day = "<<m_time_of_day.get()<<std::endl;
 
@@ -1220,10 +1343,10 @@ void Server::AsyncRunStep()
                                i.atEnd() == false; i++)
                        {
                                RemoteClient *client = i.getNode()->getValue();
-                               //Player *player = m_env.getPlayer(client->peer_id);
+                               //Player *player = m_env->getPlayer(client->peer_id);
                                
                                SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
-                                               m_env.getTimeOfDay());
+                                               m_env->getTimeOfDay());
                                // Send as reliable
                                m_con.Send(client->peer_id, 0, data, true);
                        }
@@ -1233,27 +1356,94 @@ void Server::AsyncRunStep()
        {
                JMutexAutoLock lock(m_env_mutex);
                // Step environment
-               ScopeProfiler sp(g_profiler, "Server: environment step");
-               m_env.step(dtime);
+               ScopeProfiler sp(g_profiler, "SEnv step");
+               ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG);
+               m_env->step(dtime);
        }
                
-       const float map_timer_and_unload_dtime = 5.15;
+       const float map_timer_and_unload_dtime = 2.92;
        if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime))
        {
                JMutexAutoLock lock(m_env_mutex);
                // Run Map's timers and unload unused data
                ScopeProfiler sp(g_profiler, "Server: map timer and unload");
-               m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
+               m_env->getMap().timerUpdate(map_timer_and_unload_dtime,
                                g_settings->getFloat("server_unload_unused_data_timeout"));
        }
        
        /*
                Do background stuff
        */
-       
+
        /*
-               Transform liquids
+               Handle players
        */
+       {
+               JMutexAutoLock lock(m_env_mutex);
+               JMutexAutoLock lock2(m_con_mutex);
+
+               //float player_max_speed = BS * 4.0; // Normal speed
+               float player_max_speed = BS * 20; // Fast speed
+               float player_max_speed_up = BS * 20;
+               
+               player_max_speed *= 2.5; // Tolerance
+               player_max_speed_up *= 2.5;
+
+               for(core::map<u16, RemoteClient*>::Iterator
+                       i = m_clients.getIterator();
+                       i.atEnd() == false; i++)
+               {
+                       RemoteClient *client = i.getNode()->getValue();
+                       ServerRemotePlayer *player =
+                                       static_cast<ServerRemotePlayer*>
+                                       (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){
+                               float age = player->m_last_good_position_age;
+                               v3f diff = (player->getPosition() - player->m_last_good_position);
+                               float d_vert = diff.Y;
+                               diff.Y = 0;
+                               float d_horiz = diff.getLength();
+                               /*infostream<<player->getName()<<"'s horizontal speed is "
+                                               <<(d_horiz/age)<<std::endl;*/
+                               if(d_horiz <= age * player_max_speed &&
+                                               (d_vert < 0 || d_vert < age * player_max_speed_up)){
+                                       player->m_last_good_position = player->getPosition();
+                               } else {
+                                       actionstream<<"Player "<<player->getName()
+                                                       <<" moved too fast; resetting position"
+                                                       <<std::endl;
+                                       player->setPosition(player->m_last_good_position);
+                                       SendMovePlayer(player);
+                               }
+                               player->m_last_good_position_age = 0;
+                       }
+
+                       /*
+                               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);
+                       }
+               }
+       }
+       
+       /* Transform liquids */
        m_liquid_transform_timer += dtime;
        if(m_liquid_transform_timer >= 1.00)
        {
@@ -1264,13 +1454,13 @@ void Server::AsyncRunStep()
                ScopeProfiler sp(g_profiler, "Server: liquid transform");
 
                core::map<v3s16, MapBlock*> modified_blocks;
-               m_env.getMap().transformLiquids(modified_blocks);
+               m_env->getMap().transformLiquids(modified_blocks);
 #if 0          
                /*
                        Update lighting
                */
                core::map<v3s16, MapBlock*> lighting_modified_blocks;
-               ServerMap &map = ((ServerMap&)m_env.getMap());
+               ServerMap &map = ((ServerMap&)m_env->getMap());
                map.updateLighting(modified_blocks, lighting_modified_blocks);
                
                // Add blocks modified by lighting to modified_blocks
@@ -1320,7 +1510,7 @@ void Server::AsyncRunStep()
                        {
                                //u16 peer_id = i.getNode()->getKey();
                                RemoteClient *client = i.getNode()->getValue();
-                               Player *player = m_env.getPlayer(client->peer_id);
+                               Player *player = m_env->getPlayer(client->peer_id);
                                if(player==NULL)
                                        continue;
                                infostream<<"* "<<player->getName()<<"\t";
@@ -1340,7 +1530,7 @@ void Server::AsyncRunStep()
                JMutexAutoLock envlock(m_env_mutex);
                JMutexAutoLock conlock(m_con_mutex);
 
-               ScopeProfiler sp(g_profiler, "Server: checking added and deleted objects");
+               ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs");
 
                // Radius inside which objects are active
                s16 radius = g_settings->getS16("active_object_send_range_blocks");
@@ -1351,7 +1541,7 @@ void Server::AsyncRunStep()
                        i.atEnd() == false; i++)
                {
                        RemoteClient *client = i.getNode()->getValue();
-                       Player *player = m_env.getPlayer(client->peer_id);
+                       Player *player = m_env->getPlayer(client->peer_id);
                        if(player==NULL)
                        {
                                // This can happen if the client timeouts somehow
@@ -1364,9 +1554,9 @@ void Server::AsyncRunStep()
 
                        core::map<u16, bool> removed_objects;
                        core::map<u16, bool> added_objects;
-                       m_env.getRemovedActiveObjects(pos, radius,
+                       m_env->getRemovedActiveObjects(pos, radius,
                                        client->m_known_objects, removed_objects);
-                       m_env.getAddedActiveObjects(pos, radius,
+                       m_env->getAddedActiveObjects(pos, radius,
                                        client->m_known_objects, added_objects);
                        
                        // Ignore if nothing happened
@@ -1389,7 +1579,7 @@ void Server::AsyncRunStep()
                        {
                                // Get object
                                u16 id = i.getNode()->getKey();
-                               ServerActiveObject* obj = m_env.getActiveObject(id);
+                               ServerActiveObject* obj = m_env->getActiveObject(id);
 
                                // Add to data buffer for sending
                                writeU16((u8*)buf, i.getNode()->getKey());
@@ -1411,7 +1601,7 @@ void Server::AsyncRunStep()
                        {
                                // Get object
                                u16 id = i.getNode()->getKey();
-                               ServerActiveObject* obj = m_env.getActiveObject(id);
+                               ServerActiveObject* obj = m_env->getActiveObject(id);
                                
                                // Get object type
                                u8 type = ACTIVEOBJECT_TYPE_INVALID;
@@ -1477,7 +1667,7 @@ void Server::AsyncRunStep()
                        }
                }
                
-               m_env.setKnownActiveObjects(whatever);
+               m_env->setKnownActiveObjects(whatever);
 #endif
 
        }
@@ -1489,7 +1679,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
@@ -1498,7 +1688,7 @@ void Server::AsyncRunStep()
                // Get active object messages from environment
                for(;;)
                {
-                       ActiveObjectMessage aom = m_env.getActiveObjectMessage();
+                       ActiveObjectMessage aom = m_env->getActiveObjectMessage();
                        if(aom.id == 0)
                                break;
                        
@@ -1687,7 +1877,7 @@ void Server::AsyncRunStep()
                                {
                                        v3s16 p = i.getNode()->getKey();
                                        modified_blocks2.insert(p,
-                                                       m_env.getMap().getBlockNoCreateNoEx(p));
+                                                       m_env->getMap().getBlockNoCreateNoEx(p));
                                }
                                // Set blocks not sent
                                for(core::list<u16>::Iterator
@@ -1720,7 +1910,6 @@ void Server::AsyncRunStep()
 
        /*
                Send object positions
-               TODO: Get rid of MapBlockObjects
        */
        {
                float &counter = m_objectdata_timer;
@@ -1730,7 +1919,7 @@ void Server::AsyncRunStep()
                        JMutexAutoLock lock1(m_env_mutex);
                        JMutexAutoLock lock2(m_con_mutex);
 
-                       ScopeProfiler sp(g_profiler, "Server: sending mbo positions");
+                       //ScopeProfiler sp(g_profiler, "Server: sending player positions");
 
                        SendObjectData(counter);
 
@@ -1774,28 +1963,14 @@ void Server::AsyncRunStep()
                        // Map
                        JMutexAutoLock lock(m_env_mutex);
 
-                       /*// Unload unused data (delete from memory)
-                       m_env.getMap().unloadUnusedData(
-                                       g_settings->getFloat("server_unload_unused_sectors_timeout"));
-                                       */
-                       /*u32 deleted_count = m_env.getMap().unloadUnusedData(
-                                       g_settings->getFloat("server_unload_unused_sectors_timeout"));
-                                       */
-
-                       // Save only changed parts
-                       m_env.getMap().save(true);
-
-                       /*if(deleted_count > 0)
-                       {
-                               infostream<<"Server: Unloaded "<<deleted_count
-                                               <<" blocks from memory"<<std::endl;
-                       }*/
+                       // Save changed parts of map
+                       m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
 
                        // Save players
-                       m_env.serializePlayers(m_mapsavedir);
+                       m_env->serializePlayers(m_mapsavedir);
                        
                        // Save environment metadata
-                       m_env.saveMeta(m_mapsavedir);
+                       m_env->saveMeta(m_mapsavedir);
                }
        }
 }
@@ -1803,14 +1978,13 @@ void Server::AsyncRunStep()
 void Server::Receive()
 {
        DSTACK(__FUNCTION_NAME);
-       u32 data_maxsize = 10000;
-       Buffer<u8> data(data_maxsize);
+       SharedBuffer<u8> data;
        u16 peer_id;
        u32 datasize;
        try{
                {
                        JMutexAutoLock conlock(m_con_mutex);
-                       datasize = m_con.Receive(peer_id, *data, data_maxsize);
+                       datasize = m_con.Receive(peer_id, data);
                }
 
                // This has to be called so that the client list gets synced
@@ -1838,7 +2012,7 @@ void Server::Receive()
                                <<" has apparently closed connection. "
                                <<"Removing player."<<std::endl;
 
-               m_env.removePlayer(peer_id);*/
+               m_env->removePlayer(peer_id);*/
        }
 }
 
@@ -1849,9 +2023,18 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        JMutexAutoLock envlock(m_env_mutex);
        JMutexAutoLock conlock(m_con_mutex);
        
-       con::Peer *peer;
        try{
-               peer = m_con.GetPeer(peer_id);
+               Address address = m_con.GetPeerAddress(peer_id);
+
+               // drop player if is ip is banned
+               if(m_banmanager.isIpBanned(address.serializeString())){
+                       SendAccessDenied(m_con, peer_id,
+                                       L"Your ip is banned. Banned name was "
+                                       +narrow_to_wide(m_banmanager.getBanName(
+                                               address.serializeString())));
+                       m_con.DeletePeer(peer_id);
+                       return;
+               }
        }
        catch(con::PeerNotFoundException &e)
        {
@@ -1860,17 +2043,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                return;
        }
 
-       // drop player if is ip is banned
-       if(m_banmanager.isIpBanned(peer->address.serializeString())){
-               SendAccessDenied(m_con, peer_id,
-                               L"Your ip is banned. Banned name was "
-                               +narrow_to_wide(m_banmanager.getBanName(
-                                       peer->address.serializeString())));
-               m_con.deletePeer(peer_id, false);
-               return;
-       }
-       
-       u8 peer_ser_ver = getClient(peer->id)->serialization_version;
+       u8 peer_ser_ver = getClient(peer_id)->serialization_version;
 
        try
        {
@@ -1891,7 +2064,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        return;
 
                infostream<<"Server: Got TOSERVER_INIT from "
-                               <<peer->id<<std::endl;
+                               <<peer_id<<std::endl;
 
                // First byte after command is maximum supported
                // serialization version
@@ -1904,15 +2077,18 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        deployed = SER_FMT_VER_INVALID;
 
                //peer->serialization_version = deployed;
-               getClient(peer->id)->pending_serialization_version = deployed;
+               getClient(peer_id)->pending_serialization_version = deployed;
                
                if(deployed == SER_FMT_VER_INVALID)
                {
                        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;
                }
                
@@ -1926,22 +2102,27 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        net_proto_version = readU16(&data[2+1+PLAYERNAME_SIZE+PASSWORD_SIZE]);
                }
 
-               getClient(peer->id)->net_proto_version = net_proto_version;
+               getClient(peer_id)->net_proto_version = net_proto_version;
 
                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"."
+                               );
                                return;
                        }
                }
@@ -2054,7 +2235,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                        writeU16(&reply[0], TOCLIENT_INIT);
                        writeU8(&reply[2], deployed);
                        writeV3S16(&reply[2+1], floatToInt(player->getPosition()+v3f(0,BS/2,0), BS));
-                       writeU64(&reply[2+1+6], m_env.getServerMap().getSeed());
+                       writeU64(&reply[2+1+6], m_env->getServerMap().getSeed());
                        
                        // Send as reliable
                        m_con.Send(peer_id, 0, reply, true);
@@ -2071,27 +2252,39 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        if(command == TOSERVER_INIT2)
        {
                infostream<<"Server: Got TOSERVER_INIT2 from "
-                               <<peer->id<<std::endl;
+                               <<peer_id<<std::endl;
 
 
-               getClient(peer->id)->serialization_version
-                               = getClient(peer->id)->pending_serialization_version;
+               getClient(peer_id)->serialization_version
+                               = getClient(peer_id)->pending_serialization_version;
 
                /*
                        Send some initialization data
                */
+
+               // Send tool definitions
+               SendToolDef(m_con, peer_id, m_toolmgr);
+               
+               // 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 player info to all players
                SendPlayerInfos();
 
                // Send inventory to player
-               UpdateCrafting(peer->id);
-               SendInventory(peer->id);
+               UpdateCrafting(peer_id);
+               SendInventory(peer_id);
 
                // Send player items to all players
                SendPlayerItems();
 
-               Player *player = m_env.getPlayer(peer_id);
+               Player *player = m_env->getPlayer(peer_id);
 
                // Send HP
                SendPlayerHP(player);
@@ -2099,8 +2292,8 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                // Send time of day
                {
                        SharedBuffer<u8> data = makePacket_TOCLIENT_TIME_OF_DAY(
-                                       m_env.getTimeOfDay());
-                       m_con.Send(peer->id, 0, data, true);
+                                       m_env->getTimeOfDay());
+                       m_con.Send(peer_id, 0, data, true);
                }
                
                // Send information about server to player in chat
@@ -2109,7 +2302,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                // Send information about joining in chat
                {
                        std::wstring name = L"unknown";
-                       Player *player = m_env.getPlayer(peer_id);
+                       Player *player = m_env->getPlayer(peer_id);
                        if(player != NULL)
                                name = narrow_to_wide(player->getName());
                        
@@ -2121,7 +2314,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                }
                
                // Warnings about protocol version can be issued here
-               if(getClient(peer->id)->net_proto_version < PROTOCOL_VERSION)
+               if(getClient(peer_id)->net_proto_version < PROTOCOL_VERSION)
                {
                        SendChatMessage(peer_id, L"# Server: WARNING: YOUR CLIENT IS OLD AND MAY WORK PROPERLY WITH THIS SERVER");
                }
@@ -2145,7 +2338,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                if(client->serialization_version == SER_FMT_VER_INVALID)
                                        continue;
                                // Get player
-                               Player *player = m_env.getPlayer(client->peer_id);
+                               Player *player = m_env->getPlayer(client->peer_id);
                                if(!player)
                                        continue;
                                // Get name of player
@@ -2167,7 +2360,8 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                return;
        }
        
-       Player *player = m_env.getPlayer(peer_id);
+       Player *player = m_env->getPlayer(peer_id);
+       ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
 
        if(player == NULL){
                infostream<<"Server::ProcessData(): Cancelling: "
@@ -2258,1090 +2452,1203 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        }
        else if(command == TOSERVER_CLICK_ACTIVEOBJECT)
        {
-               if(datasize < 7)
-                       return;
+               infostream<<"Server: CLICK_ACTIVEOBJECT not supported anymore"<<std::endl;
+               return;
+       }
+       else if(command == TOSERVER_GROUND_ACTION)
+       {
+               infostream<<"Server: GROUND_ACTION not supported anymore"<<std::endl;
+               return;
 
+       }
+       else if(command == TOSERVER_RELEASE)
+       {
+               infostream<<"Server: RELEASE not supported anymore"<<std::endl;
+               return;
+       }
+       else if(command == TOSERVER_SIGNTEXT)
+       {
+               infostream<<"Server: SIGNTEXT not supported anymore"
+                               <<std::endl;
+               return;
+       }
+       else if(command == TOSERVER_SIGNNODETEXT)
+       {
                if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
                        return;
-
                /*
-                       length: 7
-                       [0] u16 command
-                       [2] u8 button (0=left, 1=right)
-                       [3] u16 id
-                       [5] u16 item
+                       u16 command
+                       v3s16 p
+                       u16 textlen
+                       textdata
                */
-               u8 button = readU8(&data[2]);
-               u16 id = readS16(&data[3]);
-               u16 item_i = readU16(&data[5]);
-       
-               ServerActiveObject *obj = m_env.getActiveObject(id);
-
-               if(obj == NULL)
+               std::string datastring((char*)&data[2], datasize-2);
+               std::istringstream is(datastring, std::ios_base::binary);
+               u8 buf[6];
+               // Read stuff
+               is.read((char*)buf, 6);
+               v3s16 p = readV3S16(buf);
+               is.read((char*)buf, 2);
+               u16 textlen = readU16(buf);
+               std::string text;
+               for(u16 i=0; i<textlen; i++)
                {
-                       infostream<<"Server: CLICK_ACTIVEOBJECT: object not found"
-                                       <<std::endl;
-                       return;
+                       is.read((char*)buf, 1);
+                       text += (char)buf[0];
                }
 
-               // Skip if object has been removed
-               if(obj->m_removed)
+               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
+               if(!meta)
                        return;
+
+               meta->setText(text);
                
-               //TODO: Check that object is reasonably close
-               
-               // Left click, pick object up (usually)
-               if(button == 0)
-               {
-                       /*
-                               Try creating inventory item
-                       */
-                       InventoryItem *item = obj->createPickedUpItem();
-                       
-                       if(item)
-                       {
-                               InventoryList *ilist = player->inventory.getList("main");
-                               if(ilist != NULL)
-                               {
-                                       actionstream<<player->getName()<<" picked up "
-                                                       <<item->getName()<<std::endl;
-                                       if(g_settings->getBool("creative_mode") == false)
-                                       {
-                                               // Skip if inventory has no free space
-                                               if(ilist->roomForItem(item) == false)
-                                               {
-                                                       infostream<<"Player inventory has no free space"<<std::endl;
-                                                       return;
-                                               }
-
-                                               // Add to inventory and send inventory
-                                               ilist->addItem(item);
-                                               UpdateCrafting(player->peer_id);
-                                               SendInventory(player->peer_id);
-                                       }
-
-                                       // Remove object from environment
-                                       obj->m_removed = true;
-                               }
-                       }
-                       else
-                       {
-                               /*
-                                       Item cannot be picked up. Punch it instead.
-                               */
-
-                               actionstream<<player->getName()<<" punches object "
-                                               <<obj->getId()<<std::endl;
-
-                               ToolItem *titem = NULL;
-                               std::string toolname = "";
-
-                               InventoryList *mlist = player->inventory.getList("main");
-                               if(mlist != NULL)
-                               {
-                                       InventoryItem *item = mlist->getItem(item_i);
-                                       if(item && (std::string)item->getName() == "ToolItem")
-                                       {
-                                               titem = (ToolItem*)item;
-                                               toolname = titem->getToolName();
-                                       }
-                               }
-
-                               v3f playerpos = player->getPosition();
-                               v3f objpos = obj->getBasePosition();
-                               v3f dir = (objpos - playerpos).normalize();
-                               
-                               u16 wear = obj->punch(toolname, dir, player->getName());
+               actionstream<<player->getName()<<" writes \""<<text<<"\" to sign"
+                               <<" at "<<PP(p)<<std::endl;
                                
-                               if(titem)
-                               {
-                                       bool weared_out = titem->addWear(wear);
-                                       if(weared_out)
-                                               mlist->deleteItem(item_i);
-                                       SendInventory(player->peer_id);
-                               }
-                       }
-               }
-               // Right click, do something with object
-               if(button == 1)
+               v3s16 blockpos = getNodeBlockPos(p);
+               MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
+               if(block)
                {
-                       actionstream<<player->getName()<<" right clicks object "
-                                       <<obj->getId()<<std::endl;
-
-                       // Track hp changes super-crappily
-                       u16 oldhp = player->hp;
-                       
-                       // Do stuff
-                       obj->rightClick(player);
-                       
-                       // Send back stuff
-                       if(player->hp != oldhp)
-                       {
-                               SendPlayerHP(player);
-                       }
+                       block->raiseModified(MOD_STATE_WRITE_NEEDED,
+                                       "sign node text");
                }
+
+               setBlockNotSent(blockpos);
        }
-       else if(command == TOSERVER_GROUND_ACTION)
+       else if(command == TOSERVER_INVENTORY_ACTION)
        {
-               if(datasize < 17)
-                       return;
-               /*
-                       length: 17
-                       [0] u16 command
-                       [2] u8 action
-                       [3] v3s16 nodepos_undersurface
-                       [9] v3s16 nodepos_abovesurface
-                       [15] u16 item
-                       actions:
-                       0: start digging
-                       1: place block
-                       2: stop digging (all parameters ignored)
-                       3: digging completed
-               */
-               u8 action = readU8(&data[2]);
-               v3s16 p_under;
-               p_under.X = readS16(&data[3]);
-               p_under.Y = readS16(&data[5]);
-               p_under.Z = readS16(&data[7]);
-               v3s16 p_over;
-               p_over.X = readS16(&data[9]);
-               p_over.Y = readS16(&data[11]);
-               p_over.Z = readS16(&data[13]);
-               u16 item_i = readU16(&data[15]);
-
-               //TODO: Check that target is reasonably close
-               
-               /*
-                       0: start digging
-               */
-               if(action == 0)
+               /*// Ignore inventory changes if in creative mode
+               if(g_settings->getBool("creative_mode") == true)
                {
-                       /*
-                               NOTE: This can be used in the future to check if
-                               somebody is cheating, by checking the timing.
-                       */
-               } // action == 0
-
-               /*
-                       2: stop digging
-               */
-               else if(action == 2)
+                       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 0
-                       RemoteClient *client = getClient(peer->id);
-                       JMutexAutoLock digmutex(client->m_dig_mutex);
-                       client->m_dig_tool_item = -1;
-#endif
+                       infostream<<"TOSERVER_INVENTORY_ACTION: "
+                                       <<"InventoryAction::deSerialize() returned NULL"
+                                       <<std::endl;
+                       return;
                }
+               // Create context
+               InventoryContext c;
+               c.current_player = player;
 
                /*
-                       3: Digging completed
+                       Handle restrictions and special cases of the move action
                */
-               else if(action == 3)
+               if(a->getType() == IACTION_MOVE
+                               && g_settings->getBool("creative_mode") == false)
                {
-                       // 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 = false;
-
-                       try
-                       {
-                               MapNode n = m_env.getMap().getNode(p_under);
-                               // Get mineral
-                               mineral = n.getMineral();
-                               // Get material at position
-                               material = n.getContent();
-                               // If not yet cancelled
-                               if(cannot_remove_node == false)
-                               {
-                                       // If it's not diggable, do nothing
-                                       if(content_diggable(material) == 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_over), BLOCK_EMERGE_FLAG_FROMDISK);
-                               cannot_remove_node = true;
-                       }
+                       InventoryList *rlist = player->inventory.getList("craftresult");
+                       assert(rlist);
+                       InventoryList *clist = player->inventory.getList("craft");
+                       assert(clist);
+                       InventoryList *mlist = player->inventory.getList("main");
+                       assert(mlist);
 
-                       // Make sure the player is allowed to do it
-                       if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
-                       {
-                               infostream<<"Player "<<player->getName()<<" cannot remove node"
-                                               <<" because privileges are "<<getPlayerPrivs(player)
-                                               <<std::endl;
-                               cannot_remove_node = true;
-                       }
+                       IMoveAction *ma = (IMoveAction*)a;
 
                        /*
-                               If node can't be removed, set block to be re-sent to
-                               client and quit.
+                               Disable moving items into craftresult from elsewhere
                        */
-                       if(cannot_remove_node)
+                       if(ma->to_inv == "current_player"
+                                       && ma->to_list == "craftresult"
+                                       && (ma->from_inv != "current_player"
+                                       || ma->from_list != "craftresult"))
                        {
-                               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);
-                                       
+                               infostream<<"Ignoring IMoveAction from "
+                                               <<ma->from_inv<<":"<<ma->from_list
+                                               <<" to "<<ma->to_inv<<":"<<ma->to_list
+                                               <<" because dst is craftresult"
+                                               <<" and src isn't craftresult"<<std::endl;
+                               delete a;
                                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
+                               Handle crafting (source is craftresult, which is preview)
                        */
-
-                       if(g_settings->getBool("creative_mode") == false)
+                       if(ma->from_inv == "current_player"
+                                       && ma->from_list == "craftresult"
+                                       && player->craftresult_is_preview)
                        {
                                /*
-                                       Wear out tool
+                                       If the craftresult is placed on itself, crafting takes
+                                       place and result is moved into main list
                                */
-                               InventoryList *mlist = player->inventory.getList("main");
-                               if(mlist != NULL)
+                               if(ma->to_inv == "current_player"
+                                               && ma->to_list == "craftresult")
                                {
-                                       InventoryItem *item = mlist->getItem(item_i);
-                                       if(item && (std::string)item->getName() == "ToolItem")
-                                       {
-                                               ToolItem *titem = (ToolItem*)item;
-                                               std::string toolname = titem->getToolName();
+                                       // Except if main list doesn't have free slots
+                                       if(mlist->getFreeSlots() == 0){
+                                               infostream<<"Cannot craft: Main list doesn't have"
+                                                               <<" free slots"<<std::endl;
+                                               delete a;
+                                               return;
+                                       }
+                                       
+                                       player->craftresult_is_preview = false;
+                                       clist->decrementMaterials(1);
 
-                                               // Get digging properties for material and tool
-                                               DiggingProperties prop =
-                                                               getDiggingProperties(material, toolname);
+                                       InventoryItem *item1 = rlist->changeItem(0, NULL);
+                                       mlist->addItem(item1);
 
-                                               if(prop.diggable == false)
-                                               {
-                                                       infostream<<"Server: WARNING: Player digged"
-                                                                       <<" with impossible material + tool"
-                                                                       <<" combination"<<std::endl;
-                                               }
-                                               
-                                               bool weared_out = titem->addWear(prop.wear);
+                                       srp->m_inventory_not_sent = true;
 
-                                               if(weared_out)
-                                               {
-                                                       mlist->deleteItem(item_i);
-                                               }
-                                       }
+                                       delete a;
+                                       return;
                                }
-
                                /*
-                                       Add dug item to inventory
+                                       Disable action if there are no free slots in
+                                       destination
+                                       
+                                       If the item is placed on an item that is not of the
+                                       same kind, the existing item will be first moved to
+                                       craftresult and immediately moved to the free slot.
                                */
+                               do{
+                                       Inventory *inv_to = getInventory(&c, ma->to_inv);
+                                       if(!inv_to) break;
+                                       InventoryList *list_to = inv_to->getList(ma->to_list);
+                                       if(!list_to) break;
+                                       if(list_to->getFreeSlots() == 0){
+                                               infostream<<"Cannot craft: Destination doesn't have"
+                                                               <<" free slots"<<std::endl;
+                                               delete a;
+                                               return;
+                                       }
+                               }while(0); // Allow break
 
-                               InventoryItem *item = NULL;
-
-                               if(mineral != MINERAL_NONE)
-                                       item = getDiggedMineralItem(mineral);
+                               /*
+                                       Ok, craft normally.
+                               */
+                               player->craftresult_is_preview = false;
+                               clist->decrementMaterials(1);
                                
-                               // If not mineral
-                               if(item == NULL)
-                               {
-                                       std::string &dug_s = content_features(material).dug_item;
-                                       if(dug_s != "")
-                                       {
-                                               std::istringstream is(dug_s, std::ios::binary);
-                                               item = InventoryItem::deSerialize(is);
-                                       }
-                               }
+                               /* Print out action */
+                               InventoryItem *item = rlist->getItem(0);
+                               std::string itemstring = "NULL";
+                               if(item)
+                                       itemstring = item->getItemString();
+                               actionstream<<player->getName()<<" crafts "
+                                               <<itemstring<<std::endl;
+
+                               // Do the action
+                               a->apply(&c, this, m_env);
                                
-                               if(item != NULL)
-                               {
-                                       // Add a item to inventory
-                                       player->inventory.addItem("main", item);
-
-                                       // Send inventory
-                                       UpdateCrafting(player->peer_id);
-                                       SendInventory(player->peer_id);
-                               }
-
-                               item = NULL;
+                               delete a;
+                               return;
+                       }
 
-                               if(mineral != MINERAL_NONE)
-                                 item = getDiggedMineralItem(mineral);
+                       /*
+                               Non-crafting move
+                       */
                        
-                               // If not mineral
-                               if(item == NULL)
+                       // Disallow moving items in elsewhere than player's inventory
+                       // if not allowed to build
+                       if((getPlayerPrivs(player) & PRIV_BUILD) == 0
+                                       && (ma->from_inv != "current_player"
+                                       || ma->to_inv != "current_player"))
+                       {
+                               infostream<<"Cannot move outside of player's inventory: "
+                                               <<"No build privilege"<<std::endl;
+                               delete a;
+                               return;
+                       }
+
+                       // If player is not an admin, check for ownership of src
+                       if(ma->from_inv != "current_player"
+                                       && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                       {
+                               Strfnd fn(ma->from_inv);
+                               std::string id0 = fn.next(":");
+                               if(id0 == "nodemeta")
                                {
-                                       std::string &extra_dug_s = content_features(material).extra_dug_item;
-                                       s32 extra_rarity = content_features(material).extra_dug_item_rarity;
-                                       if(extra_dug_s != "" && extra_rarity != 0
-                                          && myrand() % extra_rarity == 0)
+                                       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() != "" &&
+                                                       meta->getOwner() != player->getName())
                                        {
-                                               std::istringstream is(extra_dug_s, std::ios::binary);
-                                               item = InventoryItem::deSerialize(is);
+                                               infostream<<"Cannot move item: "
+                                                               "not owner of metadata"
+                                                               <<std::endl;
+                                               delete a;
+                                               return;
                                        }
                                }
-                       
-                               if(item != NULL)
+                       }
+                       // If player is not an admin, check for ownership of dst
+                       if(ma->to_inv != "current_player"
+                                       && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                       {
+                               Strfnd fn(ma->to_inv);
+                               std::string id0 = fn.next(":");
+                               if(id0 == "nodemeta")
                                {
-                                       // Add a item to inventory
-                                       player->inventory.addItem("main", item);
-
-                                       // Send inventory
-                                       UpdateCrafting(player->peer_id);
-                                       SendInventory(player->peer_id);
+                                       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() != "" &&
+                                                       meta->getOwner() != player->getName())
+                                       {
+                                               infostream<<"Cannot move item: "
+                                                               "not owner of metadata"
+                                                               <<std::endl;
+                                               delete a;
+                                               return;
+                                       }
                                }
                        }
-
-                       /*
-                               Remove the node
-                               (this takes some time so it is done after the quick stuff)
-                       */
+               }
+               /*
+                       Handle restrictions and special cases of the drop action
+               */
+               else if(a->getType() == IACTION_DROP)
+               {
+                       IDropAction *da = (IDropAction*)a;
+                       // Disallow dropping items if not allowed to build
+                       if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
                        {
-                               MapEditEventIgnorer ign(&m_ignore_map_edit_events);
-
-                               m_env.getMap().removeNodeAndUpdate(p_under, modified_blocks);
+                               delete a;
+                               return;
                        }
-                       /*
-                               Set blocks not sent to far players
-                       */
-                       for(core::list<u16>::Iterator
-                                       i = far_players.begin();
-                                       i != far_players.end(); i++)
+                       // If player is not an admin, check for ownership
+                       else if (da->from_inv != "current_player"
+                                       && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
                        {
-                               u16 peer_id = *i;
-                               RemoteClient *client = getClient(peer_id);
-                               if(client==NULL)
-                                       continue;
-                               client->SetBlocksNotSent(modified_blocks);
+                               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() != "" &&
+                                                       meta->getOwner() != player->getName())
+                                       {
+                                               infostream<<"Cannot move item: "
+                                                               "not owner of metadata"
+                                                               <<std::endl;
+                                               delete a;
+                                               return;
+                                       }
+                               }
                        }
                }
                
+               // Do the action
+               a->apply(&c, this, m_env);
+               // Eat the action
+               delete a;
+       }
+       else if(command == TOSERVER_CHAT_MESSAGE)
+       {
                /*
-                       1: place block
+                       u16 command
+                       u16 length
+                       wstring message
                */
-               else if(action == 1)
+               u8 buf[6];
+               std::string datastring((char*)&data[2], datasize-2);
+               std::istringstream is(datastring, std::ios_base::binary);
+               
+               // Read stuff
+               is.read((char*)buf, 2);
+               u16 len = readU16(buf);
+               
+               std::wstring message;
+               for(u16 i=0; i<len; i++)
                {
+                       is.read((char*)buf, 2);
+                       message += (wchar_t)readU16(buf);
+               }
 
-                       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())
-                       {
-                               try{
-                                       // Don't add a node if this is not a free space
-                                       MapNode n2 = m_env.getMap().getNode(p_over);
-                                       bool no_enough_privs =
-                                                       ((getPlayerPrivs(player) & PRIV_BUILD)==0);
-                                       if(no_enough_privs)
-                                               infostream<<"Player "<<player->getName()<<" cannot add node"
-                                                       <<" because privileges are "<<getPlayerPrivs(player)
-                                                       <<std::endl;
+               // Get player name of this client
+               std::wstring name = narrow_to_wide(player->getName());
+               
+               // Run script hook
+               bool ate = scriptapi_on_chat_message(m_lua, player->getName(),
+                               wide_to_narrow(message));
+               // If script ate the message, don't proceed
+               if(ate)
+                       return;
+               
+               // Line to send to players
+               std::wstring line;
+               // Whether to send to the player that sent the line
+               bool send_to_sender = false;
+               // Whether to send to other players
+               bool send_to_others = false;
+               
+               // Local player gets all privileges regardless of
+               // what's set on their account.
+               u64 privs = getPlayerPrivs(player);
 
-                                       if(content_features(n2).buildable_to == false
-                                               || no_enough_privs)
-                                       {
-                                               // Client probably has wrong data.
-                                               // Set block not sent, so that client will get
-                                               // a valid one.
-                                               infostream<<"Client "<<peer_id<<" tried to place"
-                                                               <<" node in invalid position; setting"
-                                                               <<" MapBlock not sent."<<std::endl;
-                                               RemoteClient *client = getClient(peer_id);
-                                               v3s16 blockpos = getNodeBlockPos(p_over);
-                                               client->SetBlockNotSent(blockpos);
-                                               return;
-                                       }
-                               }
-                               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_over), BLOCK_EMERGE_FLAG_FROMDISK);
-                                       return;
-                               }
+               // Parse commands
+               if(message[0] == L'/')
+               {
+                       size_t strip_size = 1;
+                       if (message[1] == L'#') // support old-style commans
+                               ++strip_size;
+                       message = message.substr(strip_size);
 
-                               // 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(content_features(n).wall_mounted)
-                                       n.param2 = packDir(p_under - p_over);
+                       WStrfnd f1(message);
+                       f1.next(L" "); // Skip over /#whatever
+                       std::wstring paramstring = f1.next(L"");
 
-                               // Calculate the direction for furnaces and chests and stuff
-                               if(content_features(n).param_type == CPT_FACEDIR_SIMPLE)
-                               {
-                                       v3f playerpos = player->getPosition();
-                                       v3f blockpos = intToFloat(p_over, 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;
-                                       }
-                               }
+                       ServerCommandContext *ctx = new ServerCommandContext(
+                               str_split(message, L' '),
+                               paramstring,
+                               this,
+                               m_env,
+                               player,
+                               privs);
 
-                               /*
-                                       Send to all close-by players
-                               */
-                               core::list<u16> far_players;
-                               sendAddNode(p_over, 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);
-                                       // Send inventory
-                                       UpdateCrafting(peer_id);
-                                       SendInventory(peer_id);
-                               }
-                               
-                               /*
-                                       Add node.
+                       std::wstring reply(processServerCommand(ctx));
+                       send_to_sender = ctx->flags & SEND_TO_SENDER;
+                       send_to_others = ctx->flags & SEND_TO_OTHERS;
 
-                                       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);
+                       if (ctx->flags & SEND_NO_PREFIX)
+                               line += reply;
+                       else
+                               line += L"Server: " + reply;
 
-                                       std::string p_name = std::string(player->getName());
-                                       m_env.getMap().addNodeAndUpdate(p_over, 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);
-                               }
+                       delete ctx;
 
-                               /*
-                                       Calculate special events
-                               */
-                               
-                               /*if(n.d == 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++)
-                                       {
-                                               
-                                       }
-                               }*/
+               }
+               else
+               {
+                       if(privs & PRIV_SHOUT)
+                       {
+                               line += L"<";
+                               line += name;
+                               line += L"> ";
+                               line += message;
+                               send_to_others = true;
                        }
-                       /*
-                               Place other item (not a block)
-                       */
                        else
                        {
-                               v3s16 blockpos = getNodeBlockPos(p_over);
-                               
-                               /*
-                                       Check that the block is loaded so that the item
-                                       can properly be added to the static list too
-                               */
-                               MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos);
-                               if(block==NULL)
-                               {
-                                       infostream<<"Error while placing object: "
-                                                       "block not found"<<std::endl;
-                                       return;
-                               }
-
-                               /*
-                                       If in creative mode, item dropping is disabled unless
-                                       player has build privileges
-                               */
-                               if(g_settings->getBool("creative_mode") &&
-                                       (getPlayerPrivs(player) & PRIV_BUILD) == 0)
-                               {
-                                       infostream<<"Not allowing player to drop item: "
-                                                       "creative mode and no build privs"<<std::endl;
-                                       return;
-                               }
-
-                               // Calculate a position for it
-                               v3f pos = intToFloat(p_over, BS);
-                               //pos.Y -= BS*0.45;
-                               pos.Y -= BS*0.25; // let it drop a bit
-                               // 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;
+                               line += L"Server: You are not allowed to shout";
+                               send_to_sender = true;
+                       }
+               }
+               
+               if(line != L"")
+               {
+                       if(send_to_others)
+                               actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
 
-                               /*
-                                       Create the object
-                               */
-                               ServerActiveObject *obj = item->createSAO(&m_env, 0, pos);
+                       /*
+                               Send the message to clients
+                       */
+                       for(core::map<u16, RemoteClient*>::Iterator
+                               i = m_clients.getIterator();
+                               i.atEnd() == false; i++)
+                       {
+                               // Get client and check that it is valid
+                               RemoteClient *client = i.getNode()->getValue();
+                               assert(client->peer_id == i.getNode()->getKey());
+                               if(client->serialization_version == SER_FMT_VER_INVALID)
+                                       continue;
 
-                               if(obj == NULL)
-                               {
-                                       infostream<<"WARNING: item resulted in NULL object, "
-                                                       <<"not placing onto map"
-                                                       <<std::endl;
-                               }
-                               else
-                               {
-                                       actionstream<<player->getName()<<" places "<<item->getName()
-                                                       <<" at "<<PP(p_over)<<std::endl;
-                               
-                                       // Add the object to the environment
-                                       m_env.addActiveObject(obj);
-                                       
-                                       infostream<<"Placed object"<<std::endl;
+                               // Filter recipient
+                               bool sender_selected = (peer_id == client->peer_id);
+                               if(sender_selected == true && send_to_sender == false)
+                                       continue;
+                               if(sender_selected == false && send_to_others == false)
+                                       continue;
 
-                                       if(g_settings->getBool("creative_mode") == false)
-                                       {
-                                               // Delete the right amount of items from the slot
-                                               u16 dropcount = item->getDropCount();
-                                               
-                                               // Delete item if all gone
-                                               if(item->getCount() <= dropcount)
-                                               {
-                                                       if(item->getCount() < dropcount)
-                                                               infostream<<"WARNING: Server: dropped more items"
-                                                                               <<" than the slot contains"<<std::endl;
-                                                       
-                                                       InventoryList *ilist = player->inventory.getList("main");
-                                                       if(ilist)
-                                                               // Remove from inventory and send inventory
-                                                               ilist->deleteItem(item_i);
-                                               }
-                                               // Else decrement it
-                                               else
-                                                       item->remove(dropcount);
-                                               
-                                               // Send inventory
-                                               UpdateCrafting(peer_id);
-                                               SendInventory(peer_id);
-                                       }
-                               }
+                               SendChatMessage(client->peer_id, line);
                        }
+               }
+       }
+       else if(command == TOSERVER_DAMAGE)
+       {
+               std::string datastring((char*)&data[2], datasize-2);
+               std::istringstream is(datastring, std::ios_base::binary);
+               u8 damage = readU8(is);
 
-               } // action == 1
-
-               /*
-                       Catch invalid actions
-               */
+               if(g_settings->getBool("enable_damage"))
+               {
+                       actionstream<<player->getName()<<" damaged by "
+                                       <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
+                                       <<std::endl;
+                               
+                       HandlePlayerHP(player, damage);
+               }
                else
                {
-                       infostream<<"WARNING: Server: Invalid action "
-                                       <<action<<std::endl;
+                       SendPlayerHP(player);
                }
        }
-#if 0
-       else if(command == TOSERVER_RELEASE)
+       else if(command == TOSERVER_PASSWORD)
        {
-               if(datasize < 3)
-                       return;
                /*
-                       length: 3
-                       [0] u16 command
-                       [2] u8 button
+                       [0] u16 TOSERVER_PASSWORD
+                       [2] u8[28] old password
+                       [30] u8[28] new password
                */
-               infostream<<"TOSERVER_RELEASE ignored"<<std::endl;
+
+               if(datasize != 2+PASSWORD_SIZE*2)
+                       return;
+               /*char password[PASSWORD_SIZE];
+               for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+                       password[i] = data[2+i];
+               password[PASSWORD_SIZE-1] = 0;*/
+               std::string oldpwd;
+               for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+               {
+                       char c = data[2+i];
+                       if(c == 0)
+                               break;
+                       oldpwd += c;
+               }
+               std::string newpwd;
+               for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+               {
+                       char c = data[2+PASSWORD_SIZE+i];
+                       if(c == 0)
+                               break;
+                       newpwd += c;
+               }
+
+               infostream<<"Server: Client requests a password change from "
+                               <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
+
+               std::string playername = player->getName();
+
+               if(m_authmanager.exists(playername) == false)
+               {
+                       infostream<<"Server: playername not found in authmanager"<<std::endl;
+                       // Wrong old password supplied!!
+                       SendChatMessage(peer_id, L"playername not found in authmanager");
+                       return;
+               }
+
+               std::string checkpwd = m_authmanager.getPassword(playername);
+
+               if(oldpwd != checkpwd)
+               {
+                       infostream<<"Server: invalid old password"<<std::endl;
+                       // Wrong old password supplied!!
+                       SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
+                       return;
+               }
+
+               actionstream<<player->getName()<<" changes password"<<std::endl;
+
+               m_authmanager.setPassword(playername, newpwd);
+               
+               infostream<<"Server: password change successful for "<<playername
+                               <<std::endl;
+               SendChatMessage(peer_id, L"Password change successful");
        }
-#endif
-       else if(command == TOSERVER_SIGNTEXT)
+       else if(command == TOSERVER_PLAYERITEM)
        {
-               infostream<<"Server: TOSERVER_SIGNTEXT not supported anymore"
-                               <<std::endl;
-               return;
+               if (datasize < 2+2)
+                       return;
+
+               u16 item = readU16(&data[2]);
+               player->wieldItem(item);
+               SendWieldedItem(player);
        }
-       else if(command == TOSERVER_SIGNNODETEXT)
+       else if(command == TOSERVER_RESPAWN)
        {
-               if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
+               if(player->hp != 0)
                        return;
-               /*
-                       u16 command
-                       v3s16 p
-                       u16 textlen
-                       textdata
-               */
+               
+               RespawnPlayer(player);
+               
+               actionstream<<player->getName()<<" respawns at "
+                               <<PP(player->getPosition()/BS)<<std::endl;
+       }
+       else if(command == TOSERVER_INTERACT)
+       {
                std::string datastring((char*)&data[2], datasize-2);
                std::istringstream is(datastring, std::ios_base::binary);
-               u8 buf[6];
-               // Read stuff
-               is.read((char*)buf, 6);
-               v3s16 p = readV3S16(buf);
-               is.read((char*)buf, 2);
-               u16 textlen = readU16(buf);
-               std::string text;
-               for(u16 i=0; i<textlen; i++)
+
+               /*
+                       [0] u16 command
+                       [2] u8 action
+                       [3] u16 item
+                       [5] u32 length of the next item
+                       [9] serialized PointedThing
+                       actions:
+                       0: start digging (from undersurface) or use
+                       1: stop digging (all parameters ignored)
+                       2: digging completed
+                       3: place block or item (to abovesurface)
+                       4: use item
+               */
+               u8 action = readU8(is);
+               u16 item_i = readU16(is);
+               std::istringstream tmp_is(deSerializeLongString(is), std::ios::binary);
+               PointedThing pointed;
+               pointed.deSerialize(tmp_is);
+
+               infostream<<"TOSERVER_INTERACT: action="<<(int)action<<", item="<<item_i<<", pointed="<<pointed.dump()<<std::endl;
+
+               v3f player_pos = srp->m_last_good_position;
+
+               // Update wielded item
+               srp->wieldItem(item_i);
+
+               // Get pointed to node (undefined if not POINTEDTYPE_NODE)
+               v3s16 p_under = pointed.node_undersurface;
+               v3s16 p_above = pointed.node_abovesurface;
+
+               // Get pointed to object (NULL if not POINTEDTYPE_OBJECT)
+               ServerActiveObject *pointed_object = NULL;
+               if(pointed.type == POINTEDTHING_OBJECT)
                {
-                       is.read((char*)buf, 1);
-                       text += (char)buf[0];
+                       pointed_object = m_env->getActiveObject(pointed.object_id);
+                       if(pointed_object == NULL)
+                       {
+                               infostream<<"TOSERVER_INTERACT: "
+                                       "pointed object is NULL"<<std::endl;
+                               return;
+                       }
+
                }
 
-               NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
-               if(!meta)
-                       return;
-               if(meta->typeId() != CONTENT_SIGN_WALL)
-                       return;
-               SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
-               signmeta->setText(text);
-               
-               actionstream<<player->getName()<<" writes \""<<text<<"\" to sign "
-                               <<" at "<<PP(p)<<std::endl;
-                               
-               v3s16 blockpos = getNodeBlockPos(p);
-               MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(blockpos);
-               if(block)
+               /*
+                       Check that target is reasonably close
+                       (only when digging or placing things)
+               */
+               if(action == 0 || action == 2 || action == 3)
                {
-                       block->setChangedFlag();
+                       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
+                       if(d > max_d){
+                               actionstream<<"Player "<<player->getName()
+                                               <<" tried to access "<<pointed.dump()
+                                               <<" from too far: "
+                                               <<"d="<<d<<", max_d="<<max_d
+                                               <<". ignoring."<<std::endl;
+                               // Re-send block to revert change on client-side
+                               RemoteClient *client = getClient(peer_id);
+                               v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos, BS));
+                               client->SetBlockNotSent(blockpos);
+                               // Do nothing else
+                               return;
+                       }
                }
 
-               for(core::map<u16, RemoteClient*>::Iterator
-                       i = m_clients.getIterator();
-                       i.atEnd()==false; i++)
+               /*
+                       Make sure the player is allowed to do it
+               */
+               bool build_priv = (getPlayerPrivs(player) & PRIV_BUILD) != 0;
+               if(!build_priv)
                {
-                       RemoteClient *client = i.getNode()->getValue();
-                       client->SetBlockNotSent(blockpos);
+                       infostream<<"Ignoring interaction from player "<<player->getName()
+                                       <<" because privileges are "<<getPlayerPrivs(player)
+                                       <<std::endl;
+                       // NOTE: no return; here, fall through
                }
-       }
-       else if(command == TOSERVER_INVENTORY_ACTION)
-       {
-               /*// Ignore inventory changes if in creative mode
-               if(g_settings->getBool("creative_mode") == true)
+
+               /*
+                       0: start digging or punch object
+               */
+               if(action == 0)
                {
-                       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(pointed.type == POINTEDTHING_NODE)
+                       {
+                               /*
+                                       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);
+                               }
+                               catch(InvalidPositionException &e)
+                               {
+                                       infostream<<"Server: Not punching: Node not found."
+                                                       <<" Adding block to emerge queue."
+                                                       <<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);
+                       }
+                       else if(pointed.type == POINTEDTHING_OBJECT)
+                       {
+                               if(!build_priv)
+                                       return;
+
+                               // Skip if object has been removed
+                               if(pointed_object->m_removed)
+                                       return;
+
+                               actionstream<<player->getName()<<" punches object "
+                                       <<pointed.object_id<<std::endl;
+
+                               // Do stuff
+                               pointed_object->punch(srp);
+                       }
+
+               } // action == 0
+
+               /*
+                       1: stop digging
+               */
+               else if(action == 1)
+               {
+               } // action == 1
+
+               /*
+                       2: Digging completed
+               */
+               else if(action == 2)
                {
-                       // Create context
-                       InventoryContext c;
-                       c.current_player = player;
+                       // 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)
+                       {
+                               /*
+                                       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);
+                                               }
+
+                                               srp->m_inventory_not_sent = true;
+                                       }
+                               }
+
+                               /*
+                                       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);
+                                       srp->m_inventory_not_sent = true;
+                               }
+
+                               item = NULL;
+
+                               if(mineral != MINERAL_NONE)
+                                       item = getDiggedMineralItem(mineral, this);
+                       
+                               // If not mineral
+                               if(item == NULL)
+                               {
+                                       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);
+                                       }
+                               }
+                       
+                               if(item != NULL)
+                               {
+                                       // Add a item to inventory
+                                       player->inventory.addItem("main", item);
+                                       srp->m_inventory_not_sent = true;
+                               }
+                       }
+
+                       /*
+                               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);
+                       }
 
                        /*
-                               Handle craftresult specially if not in creative mode
+                               Run script hook
                        */
-                       bool disable_action = false;
-                       if(a->getType() == IACTION_MOVE
-                                       && g_settings->getBool("creative_mode") == false)
+                       scriptapi_environment_on_dignode(m_lua, p_under, n, srp);
+               } // action == 2
+               
+               /*
+                       3: place block or right-click object
+               */
+               else if(action == 3)
+               {
+                       if(pointed.type == POINTEDTHING_NODE)
                        {
-                               IMoveAction *ma = (IMoveAction*)a;
-                               if(ma->to_inv == "current_player" &&
-                                               ma->from_inv == "current_player")
+                               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())
                                {
-                                       InventoryList *rlist = player->inventory.getList("craftresult");
-                                       assert(rlist);
-                                       InventoryList *clist = player->inventory.getList("craft");
-                                       assert(clist);
-                                       InventoryList *mlist = player->inventory.getList("main");
-                                       assert(mlist);
+                                       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;
+                                               }
+                                       }
+
+                                       /*
+                                               Send to all close-by players
+                                       */
+                                       core::list<u16> far_players;
+                                       sendAddNode(p_above, n, 0, &far_players, 30);
+                                       
                                        /*
-                                               Craftresult is no longer preview if something
-                                               is moved into it
+                                               Handle inventory
                                        */
-                                       if(ma->to_list == "craftresult"
-                                                       && ma->from_list != "craftresult")
+                                       InventoryList *ilist = player->inventory.getList("main");
+                                       if(g_settings->getBool("creative_mode") == false && ilist)
                                        {
-                                               // If it currently is a preview, remove
-                                               // its contents
-                                               if(player->craftresult_is_preview)
-                                               {
-                                                       rlist->deleteItem(0);
-                                               }
-                                               player->craftresult_is_preview = false;
+                                               // Remove from inventory and send inventory
+                                               if(mitem->getCount() <= 1)
+                                                       ilist->deleteItem(item_i);
+                                               else
+                                                       mitem->remove(1);
+                                               srp->m_inventory_not_sent = true;
                                        }
+                                       
                                        /*
-                                               Crafting takes place if this condition is true.
+                                               Add node.
+
+                                               This takes some time so it is done after the quick stuff
                                        */
-                                       if(player->craftresult_is_preview &&
-                                                       ma->from_list == "craftresult")
+                                       core::map<v3s16, MapBlock*> modified_blocks;
                                        {
-                                               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;
+                                               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);
                                        }
                                        /*
-                                               If the craftresult is placed on itself, move it to
-                                               main inventory instead of doing the action
+                                               Set blocks not sent to far players
                                        */
-                                       if(ma->to_list == "craftresult"
-                                                       && ma->from_list == "craftresult")
+                                       for(core::list<u16>::Iterator
+                                                       i = far_players.begin();
+                                                       i != far_players.end(); i++)
                                        {
-                                               disable_action = true;
-                                               
-                                               InventoryItem *item1 = rlist->changeItem(0, NULL);
-                                               mlist->addItem(item1);
+                                               u16 peer_id = *i;
+                                               RemoteClient *client = getClient(peer_id);
+                                               if(client==NULL)
+                                                       continue;
+                                               client->SetBlocksNotSent(modified_blocks);
                                        }
-                               }
-                               // Disallow moving items if not allowed to build
-                               else if((getPlayerPrivs(player) & PRIV_BUILD) == 0)
-                               {
-                                       return;
-                               }
-                               // 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)
-                               {
-                                       Strfnd fn(ma->from_inv);
-                                       std::string id0 = fn.next(":");
-                                       if(id0 == "nodemeta")
+
+                                       /*
+                                               Run script hook
+                                       */
+                                       scriptapi_environment_on_placenode(m_lua, p_above, n, srp);
+
+                                       /*
+                                               Calculate special events
+                                       */
+                                       
+                                       /*if(n.d == LEGN(m_nodedef, "CONTENT_MESE"))
                                        {
-                                               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 && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
-                                                       LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
-                                                       if (lcm->getOwner() != player->getName())
-                                                               return;
+                                               u32 count = 0;
+                                               for(s16 z=-1; z<=1; z++)
+                                               for(s16 y=-1; y<=1; y++)
+                                               for(s16 x=-1; x<=1; x++)
+                                               {
+                                                       
                                                }
-                                       }
+                                       }*/
                                }
-                               else if (ma->to_inv != "current_player" && (getPlayerPrivs(player) & PRIV_SERVER) == 0)
+                               /*
+                                       Place other item (not a block)
+                               */
+                               else
                                {
-                                       Strfnd fn(ma->to_inv);
-                                       std::string id0 = fn.next(":");
-                                       if(id0 == "nodemeta")
+                                       if(!build_priv)
                                        {
-                                               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 && meta->typeId() == CONTENT_LOCKABLE_CHEST) {
-                                                       LockingChestNodeMetadata *lcm = (LockingChestNodeMetadata*)meta;
-                                                       if (lcm->getOwner() != player->getName())
-                                                               return;
-                                               }
+                                               infostream<<"Not allowing player to place item: "
+                                                               "no build privileges"<<std::endl;
+                                               return;
                                        }
-                               }
-                       }
-                       
-                       if(disable_action == false)
-                       {
-                               // Feed action to player inventory
-                               a->apply(&c, this);
-                               // Eat the action
-                               delete a;
-                       }
-                       else
-                       {
-                               // Send inventory
-                               UpdateCrafting(player->peer_id);
-                               SendInventory(player->peer_id);
-                       }
-               }
-               else
-               {
-                       infostream<<"TOSERVER_INVENTORY_ACTION: "
-                                       <<"InventoryAction::deSerialize() returned NULL"
-                                       <<std::endl;
-               }
-       }
-       else if(command == TOSERVER_CHAT_MESSAGE)
-       {
-               /*
-                       u16 command
-                       u16 length
-                       wstring message
-               */
-               u8 buf[6];
-               std::string datastring((char*)&data[2], datasize-2);
-               std::istringstream is(datastring, std::ios_base::binary);
-               
-               // Read stuff
-               is.read((char*)buf, 2);
-               u16 len = readU16(buf);
-               
-               std::wstring message;
-               for(u16 i=0; i<len; i++)
-               {
-                       is.read((char*)buf, 2);
-                       message += (wchar_t)readU16(buf);
-               }
-
-               // Get player name of this client
-               std::wstring name = narrow_to_wide(player->getName());
-               
-               // Line to send to players
-               std::wstring line;
-               // Whether to send to the player that sent the line
-               bool send_to_sender = false;
-               // Whether to send to other players
-               bool send_to_others = false;
-               
-               // Local player gets all privileges regardless of
-               // what's set on their account.
-               u64 privs = getPlayerPrivs(player);
-
-               // Parse commands
-               if(message[0] == L'/')
-               {
-                       size_t strip_size = 1;
-                       if (message[1] == L'#') // support old-style commans
-                               ++strip_size;
-                       message = message.substr(strip_size);
 
-                       WStrfnd f1(message);
-                       f1.next(L" "); // Skip over /#whatever
-                       std::wstring paramstring = f1.next(L"");
+                                       // 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();
 
-                       ServerCommandContext *ctx = new ServerCommandContext(
-                               str_split(message, L' '),
-                               paramstring,
-                               this,
-                               &m_env,
-                               player,
-                               privs);
+                                               // 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;
+                                       }
 
-                       std::wstring reply(processServerCommand(ctx));
-                       send_to_sender = ctx->flags & SEND_TO_SENDER;
-                       send_to_others = ctx->flags & SEND_TO_OTHERS;
+                                       //pos.Y -= BS*0.45;
+                                       //pos.Y -= BS*0.25; // let it drop a bit
 
-                       if (ctx->flags & SEND_NO_PREFIX)
-                               line += reply;
-                       else
-                               line += L"Server: " + reply;
+                                       /*
+                                               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;
+                                       }
 
-                       delete ctx;
+                                       actionstream<<player->getName()<<" places "<<item->getName()
+                                                       <<" at "<<PP(pos)<<std::endl;
 
-               }
-               else
-               {
-                       if(privs & PRIV_SHOUT)
-                       {
-                               line += L"<";
-                               line += name;
-                               line += L"> ";
-                               line += message;
-                               send_to_others = true;
+                                       /*
+                                               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);
+                                                       srp->m_inventory_not_sent = true;
+                                               }
+                                       }
+                               }
                        }
-                       else
+                       else if(pointed.type == POINTEDTHING_OBJECT)
                        {
-                               line += L"Server: You are not allowed to shout";
-                               send_to_sender = true;
-                       }
-               }
-               
-               if(line != L"")
-               {
-                       if(send_to_others)
-                               actionstream<<"CHAT: "<<wide_to_narrow(line)<<std::endl;
+                               // Right click object
 
-                       /*
-                               Send the message to clients
-                       */
-                       for(core::map<u16, RemoteClient*>::Iterator
-                               i = m_clients.getIterator();
-                               i.atEnd() == false; i++)
-                       {
-                               // Get client and check that it is valid
-                               RemoteClient *client = i.getNode()->getValue();
-                               assert(client->peer_id == i.getNode()->getKey());
-                               if(client->serialization_version == SER_FMT_VER_INVALID)
-                                       continue;
+                               if(!build_priv)
+                                       return;
 
-                               // Filter recipient
-                               bool sender_selected = (peer_id == client->peer_id);
-                               if(sender_selected == true && send_to_sender == false)
-                                       continue;
-                               if(sender_selected == false && send_to_others == false)
-                                       continue;
+                               // Skip if object has been removed
+                               if(pointed_object->m_removed)
+                                       return;
 
-                               SendChatMessage(client->peer_id, line);
+                               actionstream<<player->getName()<<" right-clicks object "
+                                       <<pointed.object_id<<std::endl;
+
+                               // Do stuff
+                               pointed_object->rightClick(srp);
                        }
-               }
-       }
-       else if(command == TOSERVER_DAMAGE)
-       {
-               std::string datastring((char*)&data[2], datasize-2);
-               std::istringstream is(datastring, std::ios_base::binary);
-               u8 damage = readU8(is);
 
-               if(g_settings->getBool("enable_damage"))
-               {
-                       actionstream<<player->getName()<<" damaged by "
-                                       <<(int)damage<<" hp at "<<PP(player->getPosition()/BS)
-                                       <<std::endl;
-                               
-                       HandlePlayerHP(player, damage);
-               }
-               else
-               {
-                       SendPlayerHP(player);
-               }
-       }
-       else if(command == TOSERVER_PASSWORD)
-       {
+               } // action == 3
+
                /*
-                       [0] u16 TOSERVER_PASSWORD
-                       [2] u8[28] old password
-                       [30] u8[28] new password
+                       4: use
                */
-
-               if(datasize != 2+PASSWORD_SIZE*2)
-                       return;
-               /*char password[PASSWORD_SIZE];
-               for(u32 i=0; i<PASSWORD_SIZE-1; i++)
-                       password[i] = data[2+i];
-               password[PASSWORD_SIZE-1] = 0;*/
-               std::string oldpwd;
-               for(u32 i=0; i<PASSWORD_SIZE-1; i++)
-               {
-                       char c = data[2+i];
-                       if(c == 0)
-                               break;
-                       oldpwd += c;
-               }
-               std::string newpwd;
-               for(u32 i=0; i<PASSWORD_SIZE-1; i++)
+               else if(action == 4)
                {
-                       char c = data[2+PASSWORD_SIZE+i];
-                       if(c == 0)
-                               break;
-                       newpwd += c;
-               }
+                       InventoryList *ilist = player->inventory.getList("main");
+                       if(ilist == NULL)
+                               return;
 
-               infostream<<"Server: Client requests a password change from "
-                               <<"'"<<oldpwd<<"' to '"<<newpwd<<"'"<<std::endl;
+                       // 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;
 
-               std::string playername = player->getName();
+                       // Requires build privs
+                       if(!build_priv)
+                       {
+                               infostream<<"Not allowing player to use item: "
+                                               "no build privileges"<<std::endl;
+                               return;
+                       }
 
-               if(m_authmanager.exists(playername) == false)
-               {
-                       infostream<<"Server: playername not found in authmanager"<<std::endl;
-                       // Wrong old password supplied!!
-                       SendChatMessage(peer_id, L"playername not found in authmanager");
-                       return;
-               }
+                       actionstream<<player->getName()<<" uses "<<item->getName()
+                                       <<", pointing at "<<pointed.dump()<<std::endl;
 
-               std::string checkpwd = m_authmanager.getPassword(playername);
+                       bool remove = item->use(m_env, srp, pointed);
+                       
+                       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);
+                                       srp->m_inventory_not_sent = true;
+                               }
+                       }
 
-               if(oldpwd != checkpwd)
+               } // action == 4
+
+               /*
+                       Catch invalid actions
+               */
+               else
                {
-                       infostream<<"Server: invalid old password"<<std::endl;
-                       // Wrong old password supplied!!
-                       SendChatMessage(peer_id, L"Invalid old password supplied. Password NOT changed.");
-                       return;
+                       infostream<<"WARNING: Server: Invalid action "
+                                       <<action<<std::endl;
                }
 
-               actionstream<<player->getName()<<" changes password"<<std::endl;
-
-               m_authmanager.setPassword(playername, newpwd);
-               
-               infostream<<"Server: password change successful for "<<playername
-                               <<std::endl;
-               SendChatMessage(peer_id, L"Password change successful");
-       }
-       else if(command == TOSERVER_PLAYERITEM)
-       {
-               if (datasize < 2+2)
-                       return;
-
-               u16 item = readU16(&data[2]);
-               player->wieldItem(item);
-               SendWieldedItem(player);
-       }
-       else if(command == TOSERVER_RESPAWN)
-       {
-               if(player->hp != 0)
-                       return;
-               
-               RespawnPlayer(player);
-               
-               actionstream<<player->getName()<<" respawns at "
-                               <<PP(player->getPosition()/BS)<<std::endl;
+               // Complete add_to_inventory_later
+               srp->completeAddToInventoryLater(item_i);
        }
        else
        {
@@ -3384,7 +3691,7 @@ Inventory* Server::getInventory(InventoryContext *c, std::string id)
                p.X = stoi(fn.next(","));
                p.Y = stoi(fn.next(","));
                p.Z = stoi(fn.next(","));
-               NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
+               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
                if(meta)
                        return meta->getInventory();
                infostream<<"nodemeta at ("<<p.X<<","<<p.Y<<","<<p.Z<<"): "
@@ -3400,9 +3707,9 @@ void Server::inventoryModified(InventoryContext *c, std::string id)
        if(id == "current_player")
        {
                assert(c->current_player);
-               // Send inventory
-               UpdateCrafting(c->current_player->peer_id);
-               SendInventory(c->current_player->peer_id);
+               ServerRemotePlayer *srp =
+                               static_cast<ServerRemotePlayer*>(c->current_player);
+               srp->m_inventory_not_sent = true;
                return;
        }
        
@@ -3417,17 +3724,15 @@ void Server::inventoryModified(InventoryContext *c, std::string id)
                p.Z = stoi(fn.next(","));
                v3s16 blockpos = getNodeBlockPos(p);
 
-               NodeMetadata *meta = m_env.getMap().getNodeMetadata(p);
+               NodeMetadata *meta = m_env->getMap().getNodeMetadata(p);
                if(meta)
                        meta->inventoryModified();
-
-               for(core::map<u16, RemoteClient*>::Iterator
-                       i = m_clients.getIterator();
-                       i.atEnd()==false; i++)
-               {
-                       RemoteClient *client = i.getNode()->getValue();
-                       client->SetBlockNotSent(blockpos);
-               }
+               
+               MapBlock *block = m_env->getMap().getBlockNoCreateNoEx(blockpos);
+               if(block)
+                       block->raiseModified(MOD_STATE_WRITE_NEEDED);
+               
+               setBlockNotSent(blockpos);
 
                return;
        }
@@ -3443,7 +3748,7 @@ core::list<PlayerInfo> Server::getPlayerInfo()
        
        core::list<PlayerInfo> list;
 
-       core::list<Player*> players = m_env.getPlayers();
+       core::list<Player*> players = m_env->getPlayers();
        
        core::list<Player*>::Iterator i;
        for(i = players.begin();
@@ -3454,11 +3759,10 @@ core::list<PlayerInfo> Server::getPlayerInfo()
                Player *player = *i;
 
                try{
-                       con::Peer *peer = m_con.GetPeer(player->peer_id);
-                       // Copy info from peer to info struct
-                       info.id = peer->id;
-                       info.address = peer->address;
-                       info.avg_rtt = peer->avg_rtt;
+                       // Copy info from connection to info struct
+                       info.id = player->peer_id;
+                       info.address = m_con.GetPeerAddress(player->peer_id);
+                       info.avg_rtt = m_con.GetPeerAvgRTT(player->peer_id);
                }
                catch(con::PeerNotFoundException &e)
                {
@@ -3556,6 +3860,81 @@ 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)
+{
+       DSTACK(__FUNCTION_NAME);
+       std::ostringstream os(std::ios_base::binary);
+
+       /*
+               u16 command
+               u32 length of the next item
+               serialized ToolDefManager
+       */
+       writeU16(os, TOCLIENT_TOOLDEF);
+       std::ostringstream tmp_os(std::ios::binary);
+       tooldef->serialize(tmp_os);
+       os<<serializeLongString(tmp_os.str());
+
+       // Make data buffer
+       std::string s = os.str();
+       infostream<<"Server::SendToolDef(): Sending tool 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);
+}
+
+void Server::SendNodeDef(con::Connection &con, u16 peer_id,
+               INodeDefManager *nodedef)
+{
+       DSTACK(__FUNCTION_NAME);
+       std::ostringstream os(std::ios_base::binary);
+
+       /*
+               u16 command
+               u32 length of the next item
+               serialized NodeDefManager
+       */
+       writeU16(os, TOCLIENT_NODEDEF);
+       std::ostringstream tmp_os(std::ios::binary);
+       nodedef->serialize(tmp_os);
+       os<<serializeLongString(tmp_os.str());
+
+       // Make data buffer
+       std::string s = os.str();
+       infostream<<"Server::SendNodeDef(): Sending node 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);
+}
+
+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
 */
@@ -3588,7 +3967,7 @@ void Server::SendPlayerInfos()
        //JMutexAutoLock envlock(m_env_mutex);
        
        // Get connected players
-       core::list<Player*> players = m_env.getPlayers(true);
+       core::list<Player*> players = m_env->getPlayers(true);
        
        u32 player_count = players.getSize();
        u32 datasize = 2+(2+PLAYERNAME_SIZE)*player_count;
@@ -3622,9 +4001,12 @@ 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
        */
@@ -3679,7 +4061,7 @@ void Server::SendPlayerItems()
        DSTACK(__FUNCTION_NAME);
 
        std::ostringstream os(std::ios_base::binary);
-       core::list<Player *> players = m_env.getPlayers(true);
+       core::list<Player *> players = m_env->getPlayers(true);
 
        writeU16(os, TOCLIENT_PLAYERITEM);
        writeU16(os, players.size());
@@ -3808,7 +4190,7 @@ void Server::sendRemoveNode(v3s16 p, u16 ignore_id,
                if(far_players)
                {
                        // Get player
-                       Player *player = m_env.getPlayer(client->peer_id);
+                       Player *player = m_env->getPlayer(client->peer_id);
                        if(player)
                        {
                                // If player is far away, only set modified blocks not sent
@@ -3849,7 +4231,7 @@ void Server::sendAddNode(v3s16 p, MapNode n, u16 ignore_id,
                if(far_players)
                {
                        // Get player
-                       Player *player = m_env.getPlayer(client->peer_id);
+                       Player *player = m_env->getPlayer(client->peer_id);
                        if(player)
                        {
                                // If player is far away, only set modified blocks not sent
@@ -3989,7 +4371,7 @@ void Server::SendBlocks(float dtime)
                MapBlock *block = NULL;
                try
                {
-                       block = m_env.getMap().getBlockNoCreate(q.pos);
+                       block = m_env->getMap().getBlockNoCreate(q.pos);
                }
                catch(InvalidPositionException &e)
                {
@@ -4006,6 +4388,129 @@ void Server::SendBlocks(float dtime)
        }
 }
 
+struct SendableTexture
+{
+       std::string name;
+       std::string path;
+       std::string data;
+
+       SendableTexture(const std::string &name_="", const std::string path_="",
+                       const std::string &data_=""):
+               name(name_),
+               path(path_),
+               data(data_)
+       {}
+};
+
+void Server::SendTextures(u16 peer_id)
+{
+       DSTACK(__FUNCTION_NAME);
+
+       infostream<<"Server::SendTextures(): 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;
+                       }
+               }
+       }
+
+       /* 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
+                       }
+               */
+               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::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
 */
@@ -4048,9 +4553,15 @@ void Server::HandlePlayerHP(Player *player, s16 damage)
 
 void Server::RespawnPlayer(Player *player)
 {
-       v3f pos = findSpawnPos(m_env.getServerMap());
-       player->setPosition(pos);
        player->hp = 20;
+       ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
+       bool repositioned = scriptapi_on_respawnplayer(m_lua, srp);
+       if(!repositioned){
+               v3f pos = findSpawnPos(m_env->getServerMap());
+               player->setPosition(pos);
+               srp->m_last_good_position = pos;
+               srp->m_last_good_position_age = 0;
+       }
        SendMovePlayer(player);
        SendPlayerHP(player);
 }
@@ -4059,39 +4570,65 @@ void Server::UpdateCrafting(u16 peer_id)
 {
        DSTACK(__FUNCTION_NAME);
        
-       Player* player = m_env.getPlayer(peer_id);
+       Player* player = m_env->getPlayer(peer_id);
        assert(player);
+       ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
 
-       /*
-               Calculate crafting stuff
-       */
-       if(g_settings->getBool("creative_mode") == false)
+       // No crafting in creative mode
+       if(g_settings->getBool("creative_mode"))
+               return;
+       
+       // Get the InventoryLists of the player in which we will operate
+       InventoryList *clist = player->inventory.getList("craft");
+       assert(clist);
+       InventoryList *rlist = player->inventory.getList("craftresult");
+       assert(rlist);
+       InventoryList *mlist = player->inventory.getList("main");
+       assert(mlist);
+
+       // If the result list is not a preview and is not empty, try to
+       // throw the item into main list
+       if(!player->craftresult_is_preview && rlist->getUsedSlots() != 0)
        {
-               InventoryList *clist = player->inventory.getList("craft");
-               InventoryList *rlist = player->inventory.getList("craftresult");
-
-               if(rlist && rlist->getUsedSlots() == 0)
-                       player->craftresult_is_preview = true;
+               // Grab item out of craftresult
+               InventoryItem *item = rlist->changeItem(0, NULL);
+               // Try to put in main
+               InventoryItem *leftover = mlist->addItem(item);
+               // If there are leftovers, put them back to craftresult and
+               // delete leftovers
+               delete rlist->addItem(leftover);
+               // Inventory was modified
+               srp->m_inventory_not_sent = true;
+       }
+       
+       // If result list is empty, we will make it preview what would be
+       // crafted
+       if(rlist->getUsedSlots() == 0)
+               player->craftresult_is_preview = true;
+       
+       // If it is a preview, clear the possible old preview in it
+       if(player->craftresult_is_preview)
+               rlist->clearItems();
 
-               if(rlist && player->craftresult_is_preview)
-               {
-                       rlist->clearItems();
-               }
-               if(clist && rlist && player->craftresult_is_preview)
-               {
-                       InventoryItem *items[9];
-                       for(u16 i=0; i<9; i++)
-                       {
-                               items[i] = clist->getItem(i);
-                       }
-                       
-                       // Get result of crafting grid
-                       InventoryItem *result = craft_get_result(items);
-                       if(result)
-                               rlist->addItem(result);
+       // If it is a preview, find out what is the crafting result
+       // and put it in
+       if(player->craftresult_is_preview)
+       {
+               // Mangle crafting grid to an another format
+               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());
                }
-       
-       } // if creative_mode == false
+               CraftPointerInput cpi(3, items);
+
+               // Find out what is crafted and add it to result item slot
+               InventoryItem *result = m_craftdef->getCraftResult(cpi, this);
+               if(result)
+                       rlist->addItem(result);
+       }
 }
 
 RemoteClient* Server::getClient(u16 peer_id)
@@ -4125,7 +4662,7 @@ std::wstring Server::getStatusString()
                if(client->serialization_version == SER_FMT_VER_INVALID)
                        continue;
                // Get player
-               Player *player = m_env.getPlayer(client->peer_id);
+               Player *player = m_env->getPlayer(client->peer_id);
                // Get name of player
                std::wstring name = L"unknown";
                if(player != NULL)
@@ -4134,7 +4671,7 @@ std::wstring Server::getStatusString()
                os<<name<<L",";
        }
        os<<L"}";
-       if(((ServerMap*)(&m_env.getMap()))->isSavingEnabled() == false)
+       if(((ServerMap*)(&m_env->getMap()))->isSavingEnabled() == false)
                os<<std::endl<<L"# Server: "<<" WARNING: Map saving is disabled.";
        if(g_settings->get("motd") != "")
                os<<std::endl<<L"# Server: "<<narrow_to_wide(g_settings->get("motd"));
@@ -4148,12 +4685,76 @@ void Server::saveConfig()
                g_settings->updateConfigFile(m_configpath.c_str());
 }
 
+void Server::notifyPlayer(const char *name, const std::wstring msg)
+{
+       Player *player = m_env->getPlayer(name);
+       if(!player)
+               return;
+       SendChatMessage(player->peer_id, std::wstring(L"Server: -!- ")+msg);
+}
+
+void Server::notifyPlayers(const std::wstring msg)
+{
+       BroadcastChatMessage(msg);
+}
+
+void Server::queueBlockEmerge(v3s16 blockpos, bool allow_generate)
+{
+       u8 flags = 0;
+       if(!allow_generate)
+               flags |= BLOCK_EMERGE_FLAG_FROMDISK;
+       m_emerge_queue.addBlock(PEER_ID_INEXISTENT, blockpos, flags);
+}
+
+// IGameDef interface
+// Under envlock
+IToolDefManager* Server::getToolDefManager()
+{
+       return m_toolmgr;
+}
+INodeDefManager* Server::getNodeDefManager()
+{
+       return m_nodedef;
+}
+ICraftDefManager* Server::getCraftDefManager()
+{
+       return m_craftdef;
+}
+ICraftItemDefManager* Server::getCraftItemDefManager()
+{
+       return m_craftitemdef;
+}
+ITextureSource* Server::getTextureSource()
+{
+       return NULL;
+}
+u16 Server::allocateUnknownNodeId(const std::string &name)
+{
+       return m_nodedef->allocateDummy(name);
+}
+
+IWritableToolDefManager* Server::getWritableToolDefManager()
+{
+       return m_toolmgr;
+}
+IWritableNodeDefManager* Server::getWritableNodeDefManager()
+{
+       return m_nodedef;
+}
+IWritableCraftDefManager* Server::getWritableCraftDefManager()
+{
+       return m_craftdef;
+}
+IWritableCraftItemDefManager* Server::getWritableCraftItemDefManager()
+{
+       return m_craftitemdef;
+}
+
 v3f findSpawnPos(ServerMap &map)
 {
        //return v3f(50,50,50)*BS;
 
-       v2s16 nodepos;
-       s16 groundheight = 0;
+       v3s16 nodepos;
        
 #if 0
        nodepos = v2s16(0,0);
@@ -4166,13 +4767,11 @@ v3f findSpawnPos(ServerMap &map)
        {
                s32 range = 1 + i;
                // We're going to try to throw the player to this position
-               nodepos = v2s16(-range + (myrand()%(range*2)),
+               v2s16 nodepos2d = v2s16(-range + (myrand()%(range*2)),
                                -range + (myrand()%(range*2)));
-               v2s16 sectorpos = getNodeSectorPos(nodepos);
-               // Get sector (NOTE: Don't get because it's slow)
-               //m_env.getMap().emergeSector(sectorpos);
+               //v2s16 sectorpos = getNodeSectorPos(nodepos2d);
                // Get ground height at point (fallbacks to heightmap function)
-               groundheight = map.findGroundLevel(nodepos);
+               s16 groundheight = map.findGroundLevel(nodepos2d);
                // Don't go underwater
                if(groundheight < WATER_LEVEL)
                {
@@ -4185,22 +4784,33 @@ v3f findSpawnPos(ServerMap &map)
                        //infostream<<"-> Underwater"<<std::endl;
                        continue;
                }
-
-               // Found a good place
-               //infostream<<"Searched through "<<i<<" places."<<std::endl;
-               break;
+               
+               nodepos = v3s16(nodepos2d.X, groundheight-2, nodepos2d.Y);
+               bool is_good = false;
+               s32 air_count = 0;
+               for(s32 i=0; i<10; i++){
+                       v3s16 blockpos = getNodeBlockPos(nodepos);
+                       map.emergeBlock(blockpos, true);
+                       MapNode n = map.getNodeNoEx(nodepos);
+                       if(n.getContent() == CONTENT_AIR){
+                               air_count++;
+                               if(air_count >= 2){
+                                       is_good = true;
+                                       nodepos.Y -= 1;
+                                       break;
+                               }
+                       }
+                       nodepos.Y++;
+               }
+               if(is_good){
+                       // Found a good place
+                       //infostream<<"Searched through "<<i<<" places."<<std::endl;
+                       break;
+               }
        }
 #endif
        
-       // If no suitable place was not found, go above water at least.
-       if(groundheight < WATER_LEVEL)
-               groundheight = WATER_LEVEL;
-
-       return intToFloat(v3s16(
-                       nodepos.X,
-                       groundheight + 3,
-                       nodepos.Y
-                       ), BS);
+       return intToFloat(nodepos, BS);
 }
 
 Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id)
@@ -4208,7 +4818,7 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
        /*
                Try to get an existing player
        */
-       Player *player = m_env.getPlayer(name);
+       Player *player = m_env->getPlayer(name);
        if(player != NULL)
        {
                // If player is already connected, cancel
@@ -4229,7 +4839,7 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
                        player->inventory_backup = new Inventory();
                        *(player->inventory_backup) = player->inventory;
                        // Set creative inventory
-                       craft_set_creative_inventory(player);
+                       craft_set_creative_inventory(player, this);
                }
 
                return player;
@@ -4238,7 +4848,7 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
        /*
                If player with the wanted peer_id already exists, cancel.
        */
-       if(m_env.getPlayer(peer_id) != NULL)
+       if(m_env->getPlayer(peer_id) != NULL)
        {
                infostream<<"emergePlayer(): Player with wrong name but same"
                                " peer_id already exists"<<std::endl;
@@ -4249,37 +4859,29 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
                Create a new player
        */
        {
-               player = new ServerRemotePlayer();
-               //player->peer_id = c.peer_id;
-               //player->peer_id = PEER_ID_INEXISTENT;
-               player->peer_id = peer_id;
-               player->updateName(name);
+               // 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
-               */
+               /* Set player position */
                
                infostream<<"Server: Finding spawn place for player \""
-                               <<player->getName()<<"\""<<std::endl;
+                               <<name<<"\""<<std::endl;
 
-               v3f pos = findSpawnPos(m_env.getServerMap());
+               v3f pos = findSpawnPos(m_env->getServerMap());
 
-               player->setPosition(pos);
+               player = new ServerRemotePlayer(m_env, pos, peer_id, name);
 
-               /*
-                       Add player to environment
-               */
+               /* Add player to environment */
+               m_env->addPlayer(player);
 
-               m_env.addPlayer(player);
+               /* Run scripts */
+               ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(player);
+               scriptapi_on_newplayer(m_lua, srp);
 
-               /*
-                       Add stuff to inventory
-               */
-               
+               /* Add stuff to inventory */
                if(g_settings->getBool("creative_mode"))
                {
                        // Warning: double code above
@@ -4287,11 +4889,7 @@ Player *Server::emergePlayer(const char *name, const char *password, u16 peer_id
                        player->inventory_backup = new Inventory();
                        *(player->inventory_backup) = player->inventory;
                        // Set creative inventory
-                       craft_set_creative_inventory(player);
-               }
-               else if(g_settings->getBool("give_initial_stuff"))
-               {
-                       craft_give_initial_stuff(player);
+                       craft_set_creative_inventory(player, this);
                }
 
                return player;
@@ -4345,7 +4943,7 @@ void Server::handlePeerChange(PeerChange &c)
                {
                        // Get object
                        u16 id = i.getNode()->getKey();
-                       ServerActiveObject* obj = m_env.getActiveObject(id);
+                       ServerActiveObject* obj = m_env->getActiveObject(id);
                        
                        if(obj && obj->m_known_by_count > 0)
                                obj->m_known_by_count--;
@@ -4354,7 +4952,7 @@ void Server::handlePeerChange(PeerChange &c)
                // Collect information about leaving in chat
                std::wstring message;
                {
-                       Player *player = m_env.getPlayer(c.peer_id);
+                       Player *player = m_env->getPlayer(c.peer_id);
                        if(player != NULL)
                        {
                                std::wstring name = narrow_to_wide(player->getName());
@@ -4368,12 +4966,12 @@ void Server::handlePeerChange(PeerChange &c)
 
                /*// Delete player
                {
-                       m_env.removePlayer(c.peer_id);
+                       m_env->removePlayer(c.peer_id);
                }*/
 
                // Set player client disconnected
                {
-                       Player *player = m_env.getPlayer(c.peer_id);
+                       Player *player = m_env->getPlayer(c.peer_id);
                        if(player != NULL)
                                player->peer_id = 0;
                        
@@ -4392,7 +4990,7 @@ void Server::handlePeerChange(PeerChange &c)
                                        if(client->serialization_version == SER_FMT_VER_INVALID)
                                                continue;
                                        // Get player
-                                       Player *player = m_env.getPlayer(client->peer_id);
+                                       Player *player = m_env->getPlayer(client->peer_id);
                                        if(!player)
                                                continue;
                                        // Get name of player