Fix warnings reported by clang
[oweals/minetest.git] / src / server.cpp
index 4f42cfabe3c2244ccbf2c2ba0b203ec127520490..1e644ce6ce3a672a5f4d414f63409a66940e0fad 100644 (file)
@@ -294,9 +294,6 @@ Server::Server(
                errorstream << std::endl;
        }
 
-       // Path to builtin.lua
-       std::string builtinpath = getBuiltinLuaPath() + DIR_DELIM + "builtin.lua";
-
        // Lock environment
        JMutexAutoLock envlock(m_env_mutex);
 
@@ -305,16 +302,13 @@ Server::Server(
 
        m_script = new GameScripting(this);
 
+       std::string scriptpath = getBuiltinLuaPath() + DIR_DELIM "init.lua";
 
-       // Load and run builtin.lua
-       infostream<<"Server: Loading builtin.lua [\""
-                       <<builtinpath<<"\"]"<<std::endl;
-       bool success = m_script->loadMod(builtinpath, "__builtin");
-       if(!success){
-               errorstream<<"Server: Failed to load and run "
-                               <<builtinpath<<std::endl;
-               throw ModError("Failed to load and run "+builtinpath);
+       if (!m_script->loadScript(scriptpath)) {
+               throw ModError("Failed to load and run " + scriptpath);
        }
+
+
        // Print 'em
        infostream<<"Server: Loading mods: ";
        for(std::vector<ModSpec>::iterator i = m_mods.begin();
@@ -350,7 +344,7 @@ Server::Server(
 
        // Initialize Environment
        ServerMap *servermap = new ServerMap(path_world, this, m_emerge);
-       m_env = new ServerEnvironment(servermap, m_script, this);
+       m_env = new ServerEnvironment(servermap, m_script, this, m_path_world);
 
        m_clients.setEnv(m_env);
 
@@ -367,19 +361,13 @@ Server::Server(
        servermap->addEventReceiver(this);
 
        // If file exists, load environment metadata
-       if(fs::PathExists(m_path_world+DIR_DELIM+"env_meta.txt"))
+       if(fs::PathExists(m_path_world + DIR_DELIM "env_meta.txt"))
        {
                infostream<<"Server: Loading environment metadata"<<std::endl;
-               m_env->loadMeta(m_path_world);
+               m_env->loadMeta();
        }
 
-       // Load players
-       infostream<<"Server: Loading players"<<std::endl;
-       m_env->deSerializePlayers(m_path_world);
-
-       /*
-               Add some test ActiveBlockModifiers to environment
-       */
+       // Add some test ActiveBlockModifiers to environment
        add_legacy_abms(m_env, m_nodedef);
 
        m_liquid_transform_every = g_settings->getFloat("liquid_update");
@@ -389,42 +377,23 @@ Server::~Server()
 {
        infostream<<"Server destructing"<<std::endl;
 
-       /*
-               Send shutdown message
-       */
-       {
-               std::wstring line = L"*** Server shutting down";
-               SendChatMessage(PEER_ID_INEXISTENT, line);
-       }
+       // Send shutdown message
+       SendChatMessage(PEER_ID_INEXISTENT, L"*** Server shutting down");
 
        {
                JMutexAutoLock envlock(m_env_mutex);
 
-               /*
-                       Execute script shutdown hooks
-               */
+               // Execute script shutdown hooks
                m_script->on_shutdown();
-       }
-
-       {
-               JMutexAutoLock envlock(m_env_mutex);
 
-               /*
-                       Save players
-               */
                infostream<<"Server: Saving players"<<std::endl;
-               m_env->serializePlayers(m_path_world);
+               m_env->saveLoadedPlayers();
 
-               /*
-                       Save environment metadata
-               */
                infostream<<"Server: Saving environment metadata"<<std::endl;
-               m_env->saveMeta(m_path_world);
+               m_env->saveMeta();
        }
 
-       /*
-               Stop threads
-       */
+       // Stop threads
        stop();
        delete m_thread;
 
@@ -450,12 +419,10 @@ Server::~Server()
        delete m_script;
 
        // Delete detached inventories
-       {
-               for(std::map<std::string, Inventory*>::iterator
-                               i = m_detached_inventories.begin();
-                               i != m_detached_inventories.end(); i++){
-                       delete i->second;
-               }
+       for (std::map<std::string, Inventory*>::iterator
+                       i = m_detached_inventories.begin();
+                       i != m_detached_inventories.end(); i++) {
+               delete i->second;
        }
 }
 
@@ -646,7 +613,7 @@ void Server::AsyncRunStep(bool initial_step)
                        /*
                                Send player breath if changed
                        */
-                       if(playersao->m_breath_not_sent){
+                       if(playersao->m_breath_not_sent) {
                                SendPlayerBreath(*i);
                        }
 
@@ -709,15 +676,15 @@ void Server::AsyncRunStep(bool initial_step)
        {
                float &counter = m_masterserver_timer;
                if(!isSingleplayer() && (!counter || counter >= 300.0) &&
-                               g_settings->getBool("server_announce") == true)
+                               g_settings->getBool("server_announce"))
                {
-                       ServerList::sendAnnounce(!counter ? "start" : "update",
-                                                                               m_clients.getPlayerNames(),
-                                                                               m_uptime.get(),
-                                                                               m_env->getGameTime(),
-                                                                               m_lag,
-                                                                               m_gamespec.id,
-                                                                               m_mods);
+                       ServerList::sendAnnounce(counter ? "update" : "start",
+                                       m_clients.getPlayerNames(),
+                                       m_uptime.get(),
+                                       m_env->getGameTime(),
+                                       m_lag,
+                                       m_gamespec.id,
+                                       m_mods);
                        counter = 0.01;
                }
                counter += dtime;
@@ -747,7 +714,7 @@ void Server::AsyncRunStep(bool initial_step)
 
                        // If definitions and textures have not been sent, don't
                        // send objects either
-                       if (client->getState() < DefinitionsSent)
+                       if (client->getState() < CS_DefinitionsSent)
                                continue;
 
                        Player *player = m_env->getPlayer(client->peer_id);
@@ -1147,18 +1114,19 @@ void Server::AsyncRunStep(bool initial_step)
 
                        ScopeProfiler sp(g_profiler, "Server: saving stuff");
 
-                       //Ban stuff
-                       if(m_banmanager->isModified())
+                       // Save ban file
+                       if (m_banmanager->isModified()) {
                                m_banmanager->save();
+                       }
 
                        // Save changed parts of map
                        m_env->getMap().save(MOD_STATE_WRITE_NEEDED);
 
                        // Save players
-                       m_env->serializePlayers(m_path_world);
+                       m_env->saveLoadedPlayers();
 
                        // Save environment metadata
-                       m_env->saveMeta(m_path_world);
+                       m_env->saveMeta();
                }
        }
 }
@@ -1179,20 +1147,10 @@ void Server::Receive()
                                "InvalidIncomingDataException: what()="
                                <<e.what()<<std::endl;
        }
-       catch(con::PeerNotFoundException &e)
-       {
-               //NOTE: This is not needed anymore
-
-               // The peer has been disconnected.
-               // Find the associated player and remove it.
-
-               /*JMutexAutoLock envlock(m_env_mutex);
-
-               infostream<<"ServerThread: peer_id="<<peer_id
-                               <<" has apparently closed connection. "
-                               <<"Removing player."<<std::endl;
-
-               m_env->removePlayer(peer_id);*/
+       catch(SerializationError &e) {
+               infostream<<"Server::Receive(): "
+                               "SerializationError: what()="
+                               <<e.what()<<std::endl;
        }
        catch(ClientStateError &e)
        {
@@ -1200,6 +1158,10 @@ void Server::Receive()
                DenyAccess(peer_id, L"Your client sent something server didn't expect."
                                L"Try reconnecting or updating your client");
        }
+       catch(con::PeerNotFoundException &e)
+       {
+               // Do nothing
+       }
 }
 
 PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
@@ -1207,7 +1169,7 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
        std::string playername = "";
        PlayerSAO *playersao = NULL;
        m_clients.Lock();
-       RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id,InitDone);
+       RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_InitDone);
        if (client != NULL) {
                playername = client->getName();
                playersao = emergePlayer(playername.c_str(), peer_id);
@@ -1280,8 +1242,9 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
                        SendChatMessage(PEER_ID_INEXISTENT,message);
                }
        }
-
-       actionstream<<player->getName() <<" joins game. " << std::endl;
+       Address addr = getPeerAddress(player->peer_id);
+       std::string ip_str = addr.serializeString();
+       actionstream<<player->getName() <<" [" << ip_str << "] joins game. " << std::endl;
        /*
                Print out action
        */
@@ -1296,7 +1259,7 @@ PlayerSAO* Server::StageTwoClientInit(u16 peer_id)
                        actionstream << *i << " ";
                }
 
-               actionstream<<std::endl;
+               actionstream << player->getName() <<std::endl;
        }
        return playersao;
 }
@@ -1328,7 +1291,13 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        }
        catch(con::PeerNotFoundException &e)
        {
-               errorstream<<"Server::ProcessData(): Cancelling: peer "
+               /*
+                * no peer for this packet found
+                * most common reason is peer timeout, e.g. peer didn't
+                * respond for some time, your server was overloaded or
+                * things like that.
+                */
+               infostream<<"Server::ProcessData(): Cancelling: peer "
                                <<peer_id<<" not found"<<std::endl;
                return;
        }
@@ -1351,10 +1320,10 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                if(datasize < 2+1+PLAYERNAME_SIZE)
                        return;
 
-               RemoteClient* client = getClient(peer_id,Created);
+               RemoteClient* client = getClient(peer_id, CS_Created);
 
                // If net_proto_version is set, this client has already been handled
-               if(client->getState() > Created)
+               if(client->getState() > CS_Created)
                {
                        verbosestream<<"Server: Ignoring multiple TOSERVER_INITs from "
                                        <<addr_s<<" (peer_id="<<peer_id<<")"<<std::endl;
@@ -1553,7 +1522,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
 
                // Enforce user limit.
                // Don't enforce for users that have some admin right
-               if(m_clients.getClientIDs(Created).size() >= g_settings->getU16("max_users") &&
+               if(m_clients.getClientIDs(CS_Created).size() >= g_settings->getU16("max_users") &&
                                !checkPriv(playername, "server") &&
                                !checkPriv(playername, "ban") &&
                                !checkPriv(playername, "privs") &&
@@ -1636,7 +1605,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
 
                        // Send as reliable
                        m_clients.send(peer_id, 0, reply, true);
-                       m_clients.event(peer_id, Init);
+                       m_clients.event(peer_id, CSE_Init);
                }
 
                return;
@@ -1648,7 +1617,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                verbosestream<<"Server: Got TOSERVER_INIT2 from "
                                <<peer_id<<std::endl;
 
-               m_clients.event(peer_id, GotInit2);
+               m_clients.event(peer_id, CSE_GotInit2);
                u16 protocol_version = m_clients.getProtocolVersion(peer_id);
 
 
@@ -1682,7 +1651,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                // Send node definitions
                SendNodeDef(peer_id, m_nodedef, protocol_version);
 
-               m_clients.event(peer_id, SetDefinitionsSent);
+               m_clients.event(peer_id, CSE_SetDefinitionsSent);
 
                // Send media announcement
                sendMediaAnnouncement(peer_id);
@@ -1697,7 +1666,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
 
                ///// begin compatibility code
                if (protocol_version <= 22) {
-                       m_clients.event(peer_id, SetClientReady);
+                       m_clients.event(peer_id, CSE_SetClientReady);
                        m_script->on_joinplayer(playersao);
                }
                ///// end compatibility code
@@ -1712,8 +1681,8 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                return;
        }
 
-       u8 peer_ser_ver = getClient(peer_id,InitDone)->serialization_version;
-       u16 peer_proto_ver = getClient(peer_id,InitDone)->net_proto_version;
+       u8 peer_ser_ver = getClient(peer_id, CS_InitDone)->serialization_version;
+       u16 peer_proto_ver = getClient(peer_id, CS_InitDone)->net_proto_version;
 
        if(peer_ser_ver == SER_FMT_VER_INVALID)
        {
@@ -1751,7 +1720,13 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        else if(command == TOSERVER_CLIENT_READY) {
                // clients <= protocol version 22 did not send ready message,
                // they're already initialized
-               assert(peer_proto_ver > 22);
+               if (peer_proto_ver <= 22) {
+                       infostream << "Client sent message not expected by a "
+                               << "client using protocol version <= 22,"
+                               << "disconnecing peer_id: " << peer_id << std::endl;
+                       m_con.DisconnectPeer(peer_id);
+                       return;
+               }
 
                PlayerSAO* playersao = StageTwoClientInit(peer_id);
 
@@ -1771,7 +1746,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                                data[2], data[3], data[4],
                                std::string((char*) &data[8],(u16) data[6]));
 
-               m_clients.event(peer_id, SetClientReady);
+               m_clients.event(peer_id, CSE_SetClientReady);
                m_script->on_joinplayer(playersao);
 
        }
@@ -1803,7 +1778,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                return;
        }
 
-       if (m_clients.getClientState(peer_id) < Active)
+       if (m_clients.getClientState(peer_id) < CS_Active)
        {
                if (command == TOSERVER_PLAYERPOS) return;
 
@@ -1814,18 +1789,20 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
        }
 
        Player *player = m_env->getPlayer(peer_id);
-       if(player == NULL){
+       if(player == NULL) {
                errorstream<<"Server::ProcessData(): Cancelling: "
                                "No player for peer_id="<<peer_id
-                               <<std::endl;
+                               << " disconnecting peer!" <<std::endl;
+               m_con.DisconnectPeer(peer_id);
                return;
        }
 
        PlayerSAO *playersao = player->getPlayerSAO();
-       if(playersao == NULL){
+       if(playersao == NULL) {
                errorstream<<"Server::ProcessData(): Cancelling: "
                                "No player object for peer_id="<<peer_id
-                               <<std::endl;
+                               << " disconnecting peer!" <<std::endl;
+               m_con.DisconnectPeer(peer_id);
                return;
        }
 
@@ -2195,6 +2172,7 @@ void Server::ProcessData(u8 *data, u32 datasize, u16 peer_id)
                std::istringstream is(datastring, std::ios_base::binary);
                u16 breath = readU16(is);
                playersao->setBreath(breath);
+               m_script->player_event(playersao,"breath_changed");
        }
        else if(command == TOSERVER_PASSWORD)
        {
@@ -2861,7 +2839,7 @@ void Server::deletingPeer(con::Peer *peer, bool timeout)
        verbosestream<<"Server::deletingPeer(): peer->id="
                        <<peer->id<<", timeout="<<timeout<<std::endl;
 
-       m_clients.event(peer->id,Disconnect);
+       m_clients.event(peer->id, CSE_Disconnect);
        con::PeerChange c;
        c.type = con::PEER_REMOVED;
        c.peer_id = peer->id;
@@ -2890,10 +2868,12 @@ bool Server::getClientInfo(
 {
        *state = m_clients.getClientState(peer_id);
        m_clients.Lock();
-       RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id,Invalid);
+       RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_Invalid);
 
-       if (client == NULL)
+       if (client == NULL) {
+               m_clients.Unlock();
                return false;
+       }
 
        *uptime = client->uptime();
        *ser_vers = client->serialization_version;
@@ -3154,10 +3134,11 @@ void Server::SendShowFormspecMessage(u16 peer_id, const std::string &formspec,
        std::ostringstream os(std::ios_base::binary);
        u8 buf[12];
 
+
        // Write command
        writeU16(buf, TOCLIENT_SHOW_FORMSPEC);
        os.write((char*)buf, 2);
-       os<<serializeLongString(formspec);
+       os<<serializeLongString(FORMSPEC_VERSION_STRING + formspec);
        os<<serializeString(formname);
 
        // Make data buffer
@@ -3282,6 +3263,7 @@ void Server::SendHUDAdd(u16 peer_id, u32 id, HudElement *form)
        writeV2F1000(os, form->align);
        writeV2F1000(os, form->offset);
        writeV3F1000(os, form->world_pos);
+       writeV2S32(os,form->size);
 
        // Make data buffer
        std::string s = os.str();
@@ -3328,6 +3310,9 @@ void Server::SendHUDChange(u16 peer_id, u32 id, HudElementStat stat, void *value
                case HUD_STAT_WORLD_POS:
                        writeV3F1000(os, *(v3f *)value);
                        break;
+               case HUD_STAT_SIZE:
+                       writeV2S32(os,*(v2s32 *)value);
+                       break;
                case HUD_STAT_NUMBER:
                case HUD_STAT_ITEM:
                case HUD_STAT_DIR:
@@ -3349,6 +3334,10 @@ void Server::SendHUDSetFlags(u16 peer_id, u32 flags, u32 mask)
 
        // Write command
        writeU16(os, TOCLIENT_HUD_SET_FLAGS);
+
+       //////////////////////////// compatibility code to be removed //////////////
+       flags &= ~(HUD_FLAG_HEALTHBAR_VISIBLE | HUD_FLAG_BREATHBAR_VISIBLE);
+       ////////////////////////////////////////////////////////////////////////////
        writeU32(os, flags);
        writeU32(os, mask);
 
@@ -3438,6 +3427,7 @@ void Server::SendPlayerHP(u16 peer_id)
        assert(playersao);
        playersao->m_hp_not_sent = false;
        SendHP(peer_id, playersao->getHP());
+       m_script->player_event(playersao,"health_changed");
 
        // Send to other clients
        std::string str = gob_cmd_punched(playersao->readDamage(), playersao->getHP());
@@ -3451,6 +3441,7 @@ void Server::SendPlayerBreath(u16 peer_id)
        PlayerSAO *playersao = getPlayerSAO(peer_id);
        assert(playersao);
        playersao->m_breath_not_sent = false;
+       m_script->player_event(playersao,"breath_changed");
        SendBreath(peer_id, playersao->getBreath());
 }
 
@@ -3484,15 +3475,15 @@ void Server::SendMovePlayer(u16 peer_id)
        m_clients.send(peer_id, 0, data, true);
 }
 
-void Server::SendLocalPlayerAnimations(u16 peer_id, v2f animation_frames[4], f32 animation_speed)
+void Server::SendLocalPlayerAnimations(u16 peer_id, v2s32 animation_frames[4], f32 animation_speed)
 {
        std::ostringstream os(std::ios_base::binary);
 
        writeU16(os, TOCLIENT_LOCAL_PLAYER_ANIMATIONS);
-       writeV2F1000(os, animation_frames[0]);
-       writeV2F1000(os, animation_frames[1]);
-       writeV2F1000(os, animation_frames[2]);
-       writeV2F1000(os, animation_frames[3]);
+       writeV2S32(os, animation_frames[0]);
+       writeV2S32(os, animation_frames[1]);
+       writeV2S32(os, animation_frames[2]);
+       writeV2S32(os, animation_frames[3]);
        writeF1000(os, animation_speed);
 
        // Make data buffer
@@ -3502,6 +3493,20 @@ void Server::SendLocalPlayerAnimations(u16 peer_id, v2f animation_frames[4], f32
        m_clients.send(peer_id, 0, data, true);
 }
 
+void Server::SendEyeOffset(u16 peer_id, v3f first, v3f third)
+{
+       std::ostringstream os(std::ios_base::binary);
+
+       writeU16(os, TOCLIENT_EYE_OFFSET);
+       writeV3F1000(os, first);
+       writeV3F1000(os, third);
+
+       // Make data buffer
+       std::string s = os.str();
+       SharedBuffer<u8> data((u8 *)s.c_str(), s.size());
+       // Send as reliable
+       m_clients.send(peer_id, 0, data, true);
+}
 void Server::SendPlayerPrivileges(u16 peer_id)
 {
        Player *player = m_env->getPlayer(peer_id);
@@ -3536,7 +3541,7 @@ void Server::SendPlayerInventoryFormspec(u16 peer_id)
 
        std::ostringstream os(std::ios_base::binary);
        writeU16(os, TOCLIENT_INVENTORY_FORMSPEC);
-       os<<serializeLongString(player->inventory_formspec);
+       os<<serializeLongString(FORMSPEC_VERSION_STRING + player->inventory_formspec);
 
        // Make data buffer
        std::string s = os.str();
@@ -3839,7 +3844,7 @@ void Server::SendBlocks(float dtime)
                        i = clients.begin();
                        i != clients.end(); ++i)
                {
-                       RemoteClient *client = m_clients.lockedGetClientNoEx(*i,Active);
+                       RemoteClient *client = m_clients.lockedGetClientNoEx(*i, CS_Active);
 
                        if (client == NULL)
                                return;
@@ -3875,7 +3880,7 @@ void Server::SendBlocks(float dtime)
                        continue;
                }
 
-               RemoteClient *client = m_clients.lockedGetClientNoEx(q.peer_id,Active);
+               RemoteClient *client = m_clients.lockedGetClientNoEx(q.peer_id, CS_Active);
 
                if(!client)
                        continue;
@@ -4266,7 +4271,7 @@ void Server::DenyAccess(u16 peer_id, const std::wstring &reason)
        DSTACK(__FUNCTION_NAME);
 
        SendAccessDenied(peer_id, reason);
-       m_clients.event(peer_id,SetDenied);
+       m_clients.event(peer_id, CSE_SetDenied);
        m_con.DisconnectPeer(peer_id);
 }
 
@@ -4532,24 +4537,25 @@ bool Server::showFormspec(const char *playername, const std::string &formspec, c
 u32 Server::hudAdd(Player *player, HudElement *form) {
        if (!player)
                return -1;
-
-       u32 id = player->getFreeHudID();
-       if (id < player->hud.size())
-               player->hud[id] = form;
-       else
-               player->hud.push_back(form);
        
+       u32 id = player->addHud(form);
+
        SendHUDAdd(player->peer_id, id, form);
+
        return id;
 }
 
 bool Server::hudRemove(Player *player, u32 id) {
-       if (!player || id >= player->hud.size() || !player->hud[id])
+       if (!player)
                return false;
 
-       delete player->hud[id];
-       player->hud[id] = NULL;
+       HudElement* todel = player->removeHud(id);
+
+       if (!todel)
+               return false;
        
+       delete todel;
+
        SendHUDRemove(player->peer_id, id);
        return true;
 }
@@ -4567,6 +4573,9 @@ bool Server::hudSetFlags(Player *player, u32 flags, u32 mask) {
                return false;
 
        SendHUDSetFlags(player->peer_id, flags, mask);
+       player->hud_flags = flags;
+
+       m_script->player_event(player->getPlayerSAO(),"hud_changed");
        return true;
 }
 
@@ -4596,7 +4605,7 @@ void Server::hudSetHotbarSelectedImage(Player *player, std::string name) {
        SendHUDSetParam(player->peer_id, HUD_PARAM_HOTBAR_SELECTED_IMAGE, name);
 }
 
-bool Server::setLocalPlayerAnimations(Player *player, v2f animation_frames[4], f32 frame_speed)
+bool Server::setLocalPlayerAnimations(Player *player, v2s32 animation_frames[4], f32 frame_speed)
 {
        if (!player)
                return false;
@@ -4605,6 +4614,15 @@ bool Server::setLocalPlayerAnimations(Player *player, v2f animation_frames[4], f
        return true;
 }
 
+bool Server::setPlayerEyeOffset(Player *player, v3f first, v3f third)
+{
+       if (!player)
+               return false;
+
+       SendEyeOffset(player->peer_id, first, third);
+       return true;
+}
+
 bool Server::setSky(Player *player, const video::SColor &bgcolor,
                const std::string &type, const std::vector<std::string> &params)
 {
@@ -4980,15 +4998,16 @@ PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
                return NULL;
        }
 
-       /*
-               Create a new player if it doesn't exist yet
-       */
-       if(player == NULL)
-       {
+       // Load player if it isn't already loaded
+       if (!player) {
+               player = static_cast<RemotePlayer*>(m_env->loadPlayer(name));
+       }
+
+       // Create player if it doesn't exist
+       if (!player) {
                newplayer = true;
                player = new RemotePlayer(this);
                player->updateName(name);
-
                /* Set player position */
                infostream<<"Server: Finding spawn place for player \""
                                <<name<<"\""<<std::endl;
@@ -4999,22 +5018,21 @@ PlayerSAO* Server::emergePlayer(const char *name, u16 peer_id)
                m_env->addPlayer(player);
        }
 
-       /*
-               Create a new player active object
-       */
+       // Create a new player active object
        PlayerSAO *playersao = new PlayerSAO(m_env, player, peer_id,
                        getPlayerEffectivePrivs(player->getName()),
                        isSingleplayer());
 
        /* Clean up old HUD elements from previous sessions */
-       player->hud.clear();
+       player->clearHud();
 
        /* Add object to environment */
        m_env->addActiveObject(playersao);
 
        /* Run scripts */
-       if(newplayer)
+       if (newplayer) {
                m_script->on_newplayer(playersao);
+       }
 
        return playersao;
 }