]> git.localhorst.tv Git - blank.git/blobdiff - src/server/net.cpp
unified location handling
[blank.git] / src / server / net.cpp
index 73595344a30271f08b713ebbfeebc0ac860c5589..9eac33ece573ed35edb24b78893b855f75c0feb3 100644 (file)
@@ -3,13 +3,17 @@
 #include "Server.hpp"
 
 #include "../app/init.hpp"
-#include "../model/CompositeModel.hpp"
+#include "../geometry/distance.hpp"
+#include "../io/WorldSave.hpp"
+#include "../model/Model.hpp"
 #include "../world/ChunkIndex.hpp"
 #include "../world/Entity.hpp"
 #include "../world/World.hpp"
 
+#include <algorithm>
 #include <iostream>
 #include <zlib.h>
+#include <glm/gtx/io.hpp>
 
 using namespace std;
 
@@ -172,14 +176,16 @@ void ChunkTransmitter::Release() {
 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
 : server(server)
 , conn(addr)
-, player(nullptr, nullptr)
+, input()
 , player_model(nullptr)
 , spawns()
 , confirm_wait(0)
 , entity_updates()
+, entity_updates_skipped(0)
 , player_update_state()
 , player_update_pack(0)
 , player_update_timer(1500)
+, old_actions(0)
 , transmitter(*this)
 , chunk_queue()
 , old_base() {
@@ -207,7 +213,7 @@ void ClientConnection::Update(int dt) {
                                // they're the same
                                if (CanDespawn(*global_iter)) {
                                        SendDespawn(*local_iter);
-                               } else {
+                               } else if (SendingUpdates()) {
                                        // update
                                        QueueUpdate(*local_iter);
                                }
@@ -264,7 +270,7 @@ ClientConnection::SpawnStatus::~SpawnStatus() {
 
 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
        return
-               &e != player.entity &&
+               &e != &PlayerEntity() &&
                !e.Dead() &&
                manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
 }
@@ -280,7 +286,7 @@ uint16_t ClientConnection::Send() {
 }
 
 uint16_t ClientConnection::Send(size_t len) {
-       server.GetPacket().len = len;
+       server.GetPacket().len = sizeof(Packet::Header) + len;
        return Send();
 }
 
@@ -304,6 +310,10 @@ void ClientConnection::SendDespawn(SpawnStatus &status) {
        ++confirm_wait;
 }
 
+bool ClientConnection::SendingUpdates() const noexcept {
+       return entity_updates_skipped >= NetStat().SuggestedPacketSkip();
+}
+
 void ClientConnection::QueueUpdate(SpawnStatus &status) {
        // don't send updates while spawn not ack'd or despawn sent
        if (status.spawn_pack == -1 && status.despawn_pack == -1) {
@@ -312,10 +322,17 @@ void ClientConnection::QueueUpdate(SpawnStatus &status) {
 }
 
 void ClientConnection::SendUpdates() {
+       if (!SendingUpdates()) {
+               entity_updates.clear();
+               ++entity_updates_skipped;
+               return;
+       }
+       auto base = PlayerChunks().Base();
        auto pack = Prepare<Packet::EntityUpdate>();
+       pack.WriteChunkBase(base);
        int entity_pos = 0;
        for (SpawnStatus *status : entity_updates) {
-               pack.WriteEntity(*status->entity, entity_pos);
+               pack.WriteEntity(*status->entity, base, entity_pos);
                ++entity_pos;
                if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
                        pack.WriteEntityCount(entity_pos);
@@ -329,6 +346,7 @@ void ClientConnection::SendUpdates() {
                Send(Packet::EntityUpdate::GetSize(entity_pos));
        }
        entity_updates.clear();
+       entity_updates_skipped = 0;
 }
 
 void ClientConnection::CheckPlayerFix() {
@@ -348,11 +366,28 @@ void ClientConnection::CheckPlayerFix() {
        }
 }
 
+namespace {
+
+struct QueueCompare {
+       explicit QueueCompare(const glm::ivec3 &base)
+       : base(base) { }
+       bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
+               const glm::ivec3 ld(left - base);
+               const glm::ivec3 rd(right - base);
+               return
+                       ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
+                       rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
+       }
+       const glm::ivec3 &base;
+};
+
+}
+
 void ClientConnection::CheckChunkQueue() {
        if (PlayerChunks().Base() != old_base) {
-               Chunk::Pos begin = PlayerChunks().CoordsBegin();
-               Chunk::Pos end = PlayerChunks().CoordsEnd();
-               for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
+               ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
+               ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
+               for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
                        for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
                                for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
                                        if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
@@ -362,6 +397,12 @@ void ClientConnection::CheckChunkQueue() {
                        }
                }
                old_base = PlayerChunks().Base();
+               sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
+       }
+       // if we have packet skip enabled and just pushed an entity
+       // update, don't also send chunk data
+       if (NetStat().SuggestedPacketSkip() > 0 && entity_updates_skipped == 0) {
+               return;
        }
        if (transmitter.Transmitting()) {
                transmitter.Transmit();
@@ -371,7 +412,7 @@ void ClientConnection::CheckChunkQueue() {
                int count = 0;
                constexpr int max = 64;
                while (count < max && !chunk_queue.empty()) {
-                       Chunk::Pos pos = chunk_queue.front();
+                       ExactLocation::Coarse pos = chunk_queue.front();
                        chunk_queue.pop_front();
                        if (PlayerChunks().InRange(pos)) {
                                Chunk *chunk = PlayerChunks().Get(pos);
@@ -387,40 +428,48 @@ void ClientConnection::CheckChunkQueue() {
        }
 }
 
-void ClientConnection::AttachPlayer(const Player &new_player) {
+void ClientConnection::AttachPlayer(Player &player) {
        DetachPlayer();
-       player = new_player;
-       player.entity->Ref();
+       input.reset(new DirectInput(server.GetWorld(), player, server));
+       PlayerEntity().Ref();
 
-       old_base = player.chunks->Base();
-       Chunk::Pos begin = player.chunks->CoordsBegin();
-       Chunk::Pos end = player.chunks->CoordsEnd();
-       for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
+       old_base = PlayerChunks().Base();
+       ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
+       ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
+       for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
                for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
                        for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
                                chunk_queue.push_back(pos);
                        }
                }
        }
+       sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
+       // TODO: should the server do this?
        if (HasPlayerModel()) {
-               GetPlayerModel().Instantiate(player.entity->GetModel());
+               GetPlayerModel().Instantiate(PlayerEntity().GetModel());
        }
 
-       cout << "player \"" << player.entity->Name() << "\" joined" << endl;
+       string msg = "player \"" + player.Name() + "\" joined";
+       cout << msg << endl;
+       server.DistributeMessage(0, 0, msg);
 }
 
 void ClientConnection::DetachPlayer() {
        if (!HasPlayer()) return;
-       cout << "player \"" << player.entity->Name() << "\" left" << endl;
-       player.entity->Kill();
-       player.entity->UnRef();
-       player.entity = nullptr;
-       player.chunks = nullptr;
+       string msg = "player \"" + input->GetPlayer().Name() + "\" left";
+       cout << msg << endl;
+       server.DistributeMessage(0, 0, msg);
+
+       server.GetWorldSave().Write(input->GetPlayer());
+       PlayerEntity().Kill();
+       PlayerEntity().UnRef();
+       input.reset();
        transmitter.Abort();
        chunk_queue.clear();
+       old_actions = 0;
 }
 
-void ClientConnection::SetPlayerModel(const CompositeModel &m) noexcept {
+void ClientConnection::SetPlayerModel(const Model &m) noexcept {
        player_model = &m;
        if (HasPlayer()) {
                m.Instantiate(PlayerEntity().GetModel());
@@ -431,7 +480,7 @@ bool ClientConnection::HasPlayerModel() const noexcept {
        return player_model;
 }
 
-const CompositeModel &ClientConnection::GetPlayerModel() const noexcept {
+const Model &ClientConnection::GetPlayerModel() const noexcept {
        return *player_model;
 }
 
@@ -479,18 +528,18 @@ void ClientConnection::On(const Packet::Login &pack) {
        string name;
        pack.ReadPlayerName(name);
 
-       Player new_player = server.GetWorld().AddPlayer(name);
+       Player *new_player = server.JoinPlayer(name);
 
-       if (new_player.entity) {
+       if (new_player) {
                // success!
-               AttachPlayer(new_player);
+               AttachPlayer(*new_player);
                cout << "accepted login from player \"" << name << '"' << endl;
                auto response = Prepare<Packet::Join>();
-               response.WritePlayer(*new_player.entity);
+               response.WritePlayer(new_player->GetEntity());
                response.WriteWorldName(server.GetWorld().Name());
                Send();
                // set up update tracking
-               player_update_state = new_player.entity->GetState();
+               player_update_state = new_player->GetEntity().GetState();
                player_update_pack = pack.Seq();
                player_update_timer.Reset();
                player_update_timer.Start();
@@ -512,22 +561,73 @@ void ClientConnection::On(const Packet::PlayerUpdate &pack) {
        int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
        bool overdue = player_update_timer.HitOnce();
        player_update_timer.Reset();
-       if (pack_diff > 0 || overdue) {
-               player_update_pack = pack.Seq();
-               pack.ReadPlayerState(player_update_state);
-               // accept velocity and orientation as "user input"
-               PlayerEntity().Velocity(player_update_state.velocity);
-               PlayerEntity().Orientation(player_update_state.orient);
+       if (pack_diff <= 0 && !overdue) {
+               // drop old packets if we have a fairly recent state
+               return;
+       }
+       glm::vec3 movement(0.0f);
+       uint8_t new_actions;
+       uint8_t slot;
+
+       player_update_pack = pack.Seq();
+       pack.ReadPredictedState(player_update_state);
+       pack.ReadMovement(movement);
+       pack.ReadActions(new_actions);
+       pack.ReadSlot(slot);
+
+       input->SetMovement(movement);
+       input->TurnHead(player_update_state.pitch - input->GetPitch(), player_update_state.yaw - input->GetYaw());
+       input->SelectInventory(slot);
+
+       if ((new_actions & 0x01) && !(old_actions & 0x01)) {
+               input->StartPrimaryAction();
+       } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
+               input->StopPrimaryAction();
+       }
+       if ((new_actions & 0x02) && !(old_actions & 0x02)) {
+               input->StartSecondaryAction();
+       } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
+               input->StopSecondaryAction();
+       }
+       if ((new_actions & 0x04) && !(old_actions & 0x04)) {
+               input->StartTertiaryAction();
+       } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
+               input->StopTertiaryAction();
+       }
+       old_actions = new_actions;
+}
+
+bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
+       return HasPlayer() && PlayerChunks().InRange(pos);
+}
+
+void ClientConnection::On(const Packet::Message &pack) {
+       uint8_t type;
+       uint32_t ref;
+       string msg;
+       pack.ReadType(type);
+       pack.ReadReferral(ref);
+       pack.ReadMessage(msg);
+
+       if (type == 1 && HasPlayer()) {
+               server.DispatchMessage(input->GetPlayer(), msg);
        }
 }
 
 
-Server::Server(const Config &conf, World &world)
+Server::Server(
+       const Config::Network &conf,
+       World &world,
+       const World::Config &wc,
+       const WorldSave &save)
 : serv_sock(nullptr)
 , serv_pack{ -1, nullptr, 0 }
 , clients()
 , world(world)
-, player_model(nullptr) {
+, spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
+, save(save)
+, player_model(nullptr)
+, cli(world) {
        serv_sock = SDLNet_UDP_Open(conf.port);
        if (!serv_sock) {
                throw NetError("SDLNet_UDP_Open");
@@ -538,6 +638,7 @@ Server::Server(const Config &conf, World &world)
 }
 
 Server::~Server() {
+       world.Chunks().UnregisterIndex(spawn_index);
        delete[] serv_pack.data;
        SDLNet_UDP_Close(serv_sock);
 }
@@ -594,7 +695,7 @@ void Server::Update(int dt) {
        }
 }
 
-void Server::SetPlayerModel(const CompositeModel &m) noexcept {
+void Server::SetPlayerModel(const Model &m) noexcept {
        player_model = &m;
        for (ClientConnection &client : clients) {
                client.SetPlayerModel(m);
@@ -605,9 +706,67 @@ bool Server::HasPlayerModel() const noexcept {
        return player_model;
 }
 
-const CompositeModel &Server::GetPlayerModel() const noexcept {
+const Model &Server::GetPlayerModel() const noexcept {
        return *player_model;
 }
 
+Player *Server::JoinPlayer(const string &name) {
+       if (spawn_index.MissingChunks() > 0) {
+               return nullptr;
+       }
+       Player *player = world.AddPlayer(name);
+       if (!player) {
+               return nullptr;
+       }
+       if (save.Exists(*player)) {
+               save.Read(*player);
+       } else {
+               // TODO: spawn
+       }
+       return player;
+}
+
+void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
+       chunk.SetBlock(index, block);
+       // TODO: batch chunk changes
+       auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
+       pack.WriteChunkCoords(chunk.Position());
+       pack.WriteBlockCount(uint32_t(1));
+       pack.WriteIndex(index, 0);
+       pack.WriteBlock(chunk.BlockAt(index), 0);
+       GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
+       for (ClientConnection &client : clients) {
+               if (client.ChunkInRange(chunk.Position())) {
+                       client.Send();
+               }
+       }
+}
+
+void Server::DispatchMessage(Player &player, const string &msg) {
+       if (msg.empty()) {
+               return;
+       }
+       if (msg[0] == '/' && msg.size() > 1 && msg[1] != '/') {
+               cli.Execute(player, msg.substr(1));
+       } else {
+               DistributeMessage(1, player.GetEntity().ID(), msg);
+       }
+}
+
+void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
+       auto pack = Packet::Make<Packet::Message>(serv_pack);
+       pack.WriteType(type);
+       pack.WriteReferral(ref);
+       pack.WriteMessage(msg);
+       serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
+       SendAll();
+}
+
+void Server::SendAll() {
+       for (ClientConnection &client : clients) {
+               client.GetConnection().Send(serv_pack, serv_sock);
+       }
+}
+
 }
 }