X-Git-Url: http://git.localhorst.tv/?a=blobdiff_plain;f=src%2Fnet%2Fnet.cpp;h=0686d54eb0b9d87077b2838daac3091c54c79b37;hb=015bb899f8e3fb014bfa69fdcbb30db1c1163384;hp=18761572bd13364cb10cddd6a2ac410c5d6b4b2d;hpb=b5a83cd3df5083ed0cccfe4876143e788b3836f9;p=blank.git diff --git a/src/net/net.cpp b/src/net/net.cpp index 1876157..0686d54 100644 --- a/src/net/net.cpp +++ b/src/net/net.cpp @@ -1,17 +1,14 @@ -#include "Client.hpp" -#include "ClientConnection.hpp" #include "Connection.hpp" #include "ConnectionHandler.hpp" #include "io.hpp" #include "Packet.hpp" -#include "Server.hpp" #include "../app/init.hpp" -#include "../world/World.hpp" +#include "../model/Model.hpp" +#include "../world/Entity.hpp" +#include "../world/EntityState.hpp" #include -#include -#include using namespace std; @@ -23,158 +20,15 @@ constexpr size_t Packet::Login::MAX_LEN; constexpr size_t Packet::Join::MAX_LEN; constexpr size_t Packet::Part::MAX_LEN; constexpr size_t Packet::PlayerUpdate::MAX_LEN; - -namespace { - -UDPsocket client_bind(Uint16 port) { - UDPsocket sock = SDLNet_UDP_Open(port); - if (!sock) { - throw NetError("SDLNet_UDP_Open"); - } - return sock; -} - -IPaddress client_resolve(const char *host, Uint16 port) { - IPaddress addr; - if (SDLNet_ResolveHost(&addr, host, port) != 0) { - throw NetError("SDLNet_ResolveHost"); - } - return addr; -} - -} - -Client::Client(const Config &conf) -: conn(client_resolve(conf.host.c_str(), conf.port)) -, client_sock(client_bind(0)) -, client_pack{ -1, nullptr, 0 } { - client_pack.data = new Uint8[sizeof(Packet)]; - client_pack.maxlen = sizeof(Packet); - // establish connection - SendPing(); -} - -Client::~Client() { - delete[] client_pack.data; - SDLNet_UDP_Close(client_sock); -} - - -void Client::Handle() { - int result = SDLNet_UDP_Recv(client_sock, &client_pack); - while (result > 0) { - HandlePacket(client_pack); - result = SDLNet_UDP_Recv(client_sock, &client_pack); - } - if (result == -1) { - // a boo boo happened - throw NetError("SDLNet_UDP_Recv"); - } -} - -void Client::HandlePacket(const UDPpacket &udp_pack) { - if (!conn.Matches(udp_pack.address)) { - // packet came from somewhere else, drop - return; - } - const Packet &pack = *reinterpret_cast(udp_pack.data); - if (pack.header.tag != Packet::TAG) { - // mistagged packet, drop - return; - } - - conn.Received(udp_pack); -} - -void Client::Update(int dt) { - conn.Update(dt); - if (conn.ShouldPing()) { - SendPing(); - } -} - -uint16_t Client::SendPing() { - return conn.SendPing(client_pack, client_sock); -} - -uint16_t Client::SendLogin(const string &name) { - auto pack = Packet::Make(client_pack); - pack.WritePlayerName(name); - return conn.Send(client_pack, client_sock); -} - -uint16_t Client::SendPlayerUpdate(const Entity &player) { - auto pack = Packet::Make(client_pack); - pack.WritePlayer(player); - return conn.Send(client_pack, client_sock); -} - - -ClientConnection::ClientConnection(Server &server, const IPaddress &addr) -: server(server) -, conn(addr) -, player(nullptr) { - conn.SetHandler(this); -} - -ClientConnection::~ClientConnection() { - DetachPlayer(); -} - -void ClientConnection::Update(int dt) { - conn.Update(dt); - if (Disconnected()) { - cout << "disconnect from " << conn.Address() << endl; - } else if (conn.ShouldPing()) { - conn.SendPing(server.GetPacket(), server.GetSocket()); - } -} - -void ClientConnection::AttachPlayer(Entity &new_player) { - DetachPlayer(); - player = &new_player; - player->Ref(); -} - -void ClientConnection::DetachPlayer() { - if (!player) return; - player->Kill(); - player->UnRef(); - player = nullptr; -} - -void ClientConnection::On(const Packet::Login &pack) { - string name; - pack.ReadPlayerName(name); - - Entity *new_player = server.GetWorld().AddPlayer(name); - - if (new_player) { - // success! - AttachPlayer(*new_player); - cout << "accepted login from player \"" << name << '"' << endl; - auto response = Packet::Make(server.GetPacket()); - response.WritePlayer(*new_player); - response.WriteWorldName(server.GetWorld().Name()); - conn.Send(server.GetPacket(), server.GetSocket()); - } else { - // aw no :( - cout << "rejected login from player \"" << name << '"' << endl; - Packet::Make(server.GetPacket()); - conn.Send(server.GetPacket(), server.GetSocket()); - conn.Close(); - } -} - -void ClientConnection::On(const Packet::Part &) { - conn.Close(); -} - -void ClientConnection::On(const Packet::PlayerUpdate &pack) { - if (!HasPlayer()) return; - pack.ReadPlayer(Player()); -} - +constexpr size_t Packet::SpawnEntity::MAX_LEN; +constexpr size_t Packet::DespawnEntity::MAX_LEN; +constexpr size_t Packet::EntityUpdate::MAX_LEN; +constexpr size_t Packet::PlayerCorrection::MAX_LEN; +constexpr size_t Packet::ChunkBegin::MAX_LEN; +constexpr size_t Packet::ChunkData::MAX_LEN; +constexpr size_t Packet::BlockUpdate::MAX_LEN; +constexpr size_t Packet::Message::MAX_LEN; +constexpr size_t Packet::Message::MAX_MESSAGE_LEN; Connection::Connection(const IPaddress &addr) : handler(nullptr) @@ -230,6 +84,11 @@ uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) { throw NetError("SDLNet_UDP_Send"); } + if (HasHandler()) { + Handler().PacketOut(udp_pack); + Handler().PacketSent(seq); + } + FlagSend(); return seq; } @@ -257,6 +116,7 @@ void Connection::Received(const UDPpacket &udp_pack) { } Packet::TControl ctrl_new = pack.header.ctrl; + Handler().PacketIn(udp_pack); Handler().Handle(udp_pack); if (diff > 0) { @@ -267,14 +127,14 @@ void Connection::Received(const UDPpacket &udp_pack) { if (diff > 0) { for (int i = 0; i < diff; ++i) { if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) { - Handler().OnPacketLost(ctrl_in.ack - 32 + i); + Handler().PacketLost(ctrl_in.ack - 32 + i); } } } // check for newly ack'd packets - for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); ++s) { + for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) { if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) { - Handler().OnPacketReceived(s); + Handler().PacketReceived(s); } } ctrl_in = ctrl_new; @@ -294,6 +154,100 @@ uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) { } +ConnectionHandler::ConnectionHandler() +: packets_lost(0) +, packets_received(0) +, packet_loss(0.0f) +, stamp_cursor(15) +, stamp_last(0) +, rtt(64.0f) +, next_sample(1000) +, tx_bytes(0) +, rx_bytes(0) +, tx_kbps(0.0f) +, rx_kbps(0.0f) { + Uint32 now = SDL_GetTicks(); + for (Uint32 &s : stamps) { + s = now; + } + next_sample += now; +} + +void ConnectionHandler::PacketSent(uint16_t seq) noexcept { + if (!SamplePacket(seq)) { + return; + } + stamp_cursor = (stamp_cursor + 1) % 16; + stamps[stamp_cursor] = SDL_GetTicks(); + stamp_last = seq; +} + +void ConnectionHandler::PacketLost(uint16_t seq) { + OnPacketLost(seq); + ++packets_lost; + UpdatePacketLoss(); + UpdateRTT(seq); +} + +void ConnectionHandler::PacketReceived(uint16_t seq) { + OnPacketReceived(seq); + ++packets_received; + UpdatePacketLoss(); + UpdateRTT(seq); +} + +void ConnectionHandler::UpdatePacketLoss() noexcept { + unsigned int packets_total = packets_lost + packets_received; + if (packets_total >= 256) { + packet_loss = float(packets_lost) / float(packets_total); + packets_lost = 0; + packets_received = 0; + } +} + +void ConnectionHandler::UpdateRTT(std::uint16_t seq) noexcept { + if (!SamplePacket(seq)) return; + int diff = HeadDiff(seq); + if (diff > 0 || diff < -15) { + // packet outside observed time frame + return; + } + int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16]; + rtt += (cur_rtt - rtt) * 0.1f; +} + +bool ConnectionHandler::SamplePacket(std::uint16_t seq) const noexcept { + // only sample every eighth packet + return seq % 8 == 0; +} + +int ConnectionHandler::HeadDiff(std::uint16_t seq) const noexcept { + int16_t diff = int16_t(seq) - int16_t(stamp_last); + return diff / 8; +} + +void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept { + rx_bytes += pack.len + 20; // I know, I know, it's an estimate (about 48 for IPv6) + UpdateStats(); +} + +void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept { + tx_bytes += pack.len + 20; + UpdateStats(); +} + +void ConnectionHandler::UpdateStats() noexcept { + Uint32 now = SDL_GetTicks(); + if (now >= next_sample) { + tx_kbps = float(tx_bytes) * (1.0f / 1024.0f); + rx_kbps = float(rx_bytes) * (1.0f / 1024.0f); + tx_bytes = 0; + rx_bytes = 0; + next_sample += 1000; + } +} + + ostream &operator <<(ostream &out, const IPaddress &addr) { const unsigned char *host = reinterpret_cast(&addr.host); out << int(host[0]) @@ -319,6 +273,22 @@ const char *Packet::Type2String(uint8_t t) noexcept { return "Part"; case PlayerUpdate::TYPE: return "PlayerUpdate"; + case SpawnEntity::TYPE: + return "SpawnEntity"; + case DespawnEntity::TYPE: + return "DespawnEntity"; + case EntityUpdate::TYPE: + return "EntityUpdate"; + case PlayerCorrection::TYPE: + return "PlayerCorrection"; + case ChunkBegin::TYPE: + return "ChunkBegin"; + case ChunkData::TYPE: + return "ChunkData"; + case BlockUpdate::TYPE: + return "BlockUpdate"; + case Message::TYPE: + return "Message"; default: return "Unknown"; } @@ -362,6 +332,126 @@ void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const n } } +void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept { + WritePackN(val.w, off); + WritePackN(val.x, off + 2); + WritePackN(val.y, off + 4); + WritePackN(val.z, off + 6); +} + +void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept { + ReadPackN(val.w, off); + ReadPackN(val.x, off + 2); + ReadPackN(val.y, off + 4); + ReadPackN(val.z, off + 6); + val = normalize(val); +} + +void Packet::Payload::Write(const EntityState &state, size_t off) noexcept { + Write(state.chunk_pos, off); + WritePackU(state.block_pos * (1.0f / 16.0f), off + 12); + Write(state.velocity, off + 18); + Write(state.orient, off + 30); + WritePackN(state.pitch * PI_0p5_inv, off + 38); + WritePackN(state.yaw * PI_inv, off + 40); +} + +void Packet::Payload::Read(EntityState &state, size_t off) const noexcept { + Read(state.chunk_pos, off); + ReadPackU(state.block_pos, off + 12); + Read(state.velocity, off + 18); + Read(state.orient, off + 30); + ReadPackN(state.pitch, off + 38); + ReadPackN(state.yaw, off + 40); + state.block_pos *= 16.0f; + state.pitch *= PI_0p5; + state.yaw *= PI; +} + +void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept { + WritePackB(state.chunk_pos - base, off); + WritePackU(state.block_pos * (1.0f / 16.0f), off + 3); + Write(state.velocity, off + 9); + Write(state.orient, off + 21); + WritePackN(state.pitch * PI_0p5_inv, off + 29); + WritePackN(state.yaw * PI_inv, off + 31); +} + +void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept { + ReadPackB(state.chunk_pos, off); + ReadPackU(state.block_pos, off + 3); + Read(state.velocity, off + 9); + Read(state.orient, off + 21); + ReadPackN(state.pitch, off + 29); + ReadPackN(state.yaw, off + 31); + state.chunk_pos += base; + state.block_pos *= 16.0f; + state.pitch *= PI_0p5; + state.yaw *= PI; +} + +void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept { + Write(int8_t(val.x), off); + Write(int8_t(val.y), off + 1); + Write(int8_t(val.z), off + 2); +} + +void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept { + int8_t conv = 0; + Read(conv, off); + val.x = conv; + Read(conv, off + 1); + val.y = conv; + Read(conv, off + 2); + val.z = conv; +} + +void Packet::Payload::WritePackN(float val, size_t off) noexcept { + int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f); + Write(raw, off); +} + +void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept { + int16_t raw = 0; + Read(raw, off); + val = raw * (1.0f/32767.0f); +} + +void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept { + WritePackN(val.x, off); + WritePackN(val.y, off + 2); + WritePackN(val.z, off + 4); +} + +void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept { + ReadPackN(val.x, off); + ReadPackN(val.y, off + 2); + ReadPackN(val.z, off + 4); +} + +void Packet::Payload::WritePackU(float val, size_t off) noexcept { + uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f); + Write(raw, off); +} + +void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept { + uint16_t raw = 0; + Read(raw, off); + val = raw * (1.0f/65535.0f); +} + +void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept { + WritePackU(val.x, off); + WritePackU(val.y, off + 2); + WritePackU(val.z, off + 4); +} + +void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept { + ReadPackU(val.x, off); + ReadPackU(val.y, off + 2); + ReadPackU(val.z, off + 4); +} + void Packet::Login::WritePlayerName(const string &name) noexcept { WriteString(name, 0, 32); @@ -373,69 +463,280 @@ void Packet::Login::ReadPlayerName(string &name) const noexcept { void Packet::Join::WritePlayer(const Entity &player) noexcept { Write(player.ID(), 0); - Write(player.ChunkCoords(), 4); - Write(player.Position(), 16); - Write(player.Velocity(), 28); - Write(player.Orientation(), 40); - Write(player.AngularVelocity(), 56); + Write(player.GetState(), 4); } void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept { Read(id, 0); } -void Packet::Join::ReadPlayer(Entity &player) const noexcept { - glm::ivec3 chunk_coords(0); - glm::vec3 pos; - glm::vec3 vel; - glm::quat rot; - glm::vec3 ang; - - Read(chunk_coords, 4); - Read(pos, 16); - Read(vel, 28); - Read(rot, 40); - Read(ang, 56); - - player.Position(chunk_coords, pos); - player.Velocity(vel); - player.Orientation(rot); - player.AngularVelocity(ang); +void Packet::Join::ReadPlayerState(EntityState &state) const noexcept { + Read(state, 4); } void Packet::Join::WriteWorldName(const string &name) noexcept { - WriteString(name, 68, 32); + WriteString(name, 46, 32); } void Packet::Join::ReadWorldName(string &name) const noexcept { - ReadString(name, 68, 32); + ReadString(name, 46, 32); } -void Packet::PlayerUpdate::WritePlayer(const Entity &player) noexcept { - Write(player.ChunkCoords(), 0); - Write(player.Position(), 12); - Write(player.Velocity(), 24); - Write(player.Orientation(), 36); - Write(player.AngularVelocity(), 52); +void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept { + Write(state, 0); } -void Packet::PlayerUpdate::ReadPlayer(Entity &player) const noexcept { - glm::ivec3 chunk_coords(0); - glm::vec3 pos; - glm::vec3 vel; - glm::quat rot; - glm::vec3 ang; +void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept { + Read(state, 0); +} - Read(chunk_coords, 0); - Read(pos, 12); - Read(vel, 24); - Read(rot, 36); - Read(ang, 52); +void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept { + WritePackN(mov, 42); +} - player.Position(chunk_coords, pos); - player.Velocity(vel); - player.Orientation(rot); - player.AngularVelocity(ang); +void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept { + ReadPackN(mov, 42); +} + +void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept { + Write(actions, 48); +} + +void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept { + Read(actions, 48); +} + +void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept { + Write(slot, 49); +} + +void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept { + Read(slot, 49); +} + +void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept { + Write(e.ID(), 0); + if (e.GetModel()) { + Write(e.GetModel().GetModel().ID(), 4); + } else { + Write(uint32_t(0), 4); + } + Write(e.GetState(), 8); + Write(e.Bounds(), 50); + uint32_t flags = 0; + if (e.WorldCollidable()) { + flags |= 1; + } + Write(flags, 74); + WriteString(e.Name(), 78, 32); +} + +void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept { + Read(id, 0); +} + +void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept { + Read(id, 4); +} + +void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept { + EntityState state; + AABB bounds; + uint32_t flags = 0; + string name; + + Read(state, 8); + Read(bounds, 50); + Read(flags, 74); + ReadString(name, 78, 32); + + e.SetState(state); + e.Bounds(bounds); + e.WorldCollidable(flags & 1); + e.Name(name); +} + +void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept { + Write(id, 0); +} + +void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept { + Read(id, 0); +} + +void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept { + Write(count, 0); +} + +void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept { + Read(count, 0); +} + +void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept { + Write(base, 4); +} + +void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept { + Read(base, 4); +} + +void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept { + uint32_t off = GetSize(num); + + Write(entity.ID(), off); + Write(entity.GetState(), base, off + 4); +} + +void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept { + uint32_t off = GetSize(num); + Read(id, off); +} + +void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept { + uint32_t off = GetSize(num); + Read(state, base, off + 4); +} + +void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept { + Write(s, 0); +} + +void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept { + Read(s, 0); +} + +void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept { + Write(player.GetState(), 2); +} + +void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept { + Read(state, 2); +} + +void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept { + Write(id, 0); +} + +void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept { + Read(id, 0); +} + +void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept { + Write(f, 4); +} + +void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept { + Read(f, 4); +} + +void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept { + Write(pos, 8); +} + +void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept { + Read(pos, 8); +} + +void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept { + Write(s, 20); +} + +void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept { + Read(s, 20); +} + +void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept { + Write(id, 0); +} + +void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept { + Read(id, 0); +} + +void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept { + Write(o, 4); +} + +void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept { + Read(o, 4); +} + +void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept { + Write(s, 8); +} + +void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept { + Read(s, 8); +} + +void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept { + size_t len = min(length - 12, l); + memcpy(&data[12], d, len); +} + +void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept { + size_t len = min(length - 12, l); + memcpy(d, &data[12], len); +} + +void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept { + Write(coords, 0); +} + +void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept { + Read(coords, 0); +} + +void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept { + Write(count, 12); +} + +void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept { + Read(count, 12); +} + +void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept { + uint32_t off = GetSize(num); + Write(index, off); +} + +void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept { + uint32_t off = GetSize(num); + Read(index, off); +} + +void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept { + uint32_t off = GetSize(num) + 2; + Write(block, off); +} + +void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept { + uint32_t off = GetSize(num) + 2; + Read(block, off); +} + +void Packet::Message::WriteType(uint8_t type) noexcept { + Write(type, 0); +} + +void Packet::Message::ReadType(uint8_t &type) const noexcept { + Read(type, 0); +} + +void Packet::Message::WriteReferral(uint32_t ref) noexcept { + Write(ref, 1); +} + +void Packet::Message::ReadReferral(uint32_t &ref) const noexcept { + Read(ref, 1); +} + +void Packet::Message::WriteMessage(const string &msg) noexcept { + WriteString(msg, 5, MAX_MESSAGE_LEN); +} + +void Packet::Message::ReadMessage(string &msg) const noexcept { + ReadString(msg, 5, MAX_MESSAGE_LEN); } @@ -457,79 +758,34 @@ void ConnectionHandler::Handle(const UDPpacket &udp_pack) { case Packet::PlayerUpdate::TYPE: On(Packet::As(udp_pack)); break; + case Packet::SpawnEntity::TYPE: + On(Packet::As(udp_pack)); + break; + case Packet::DespawnEntity::TYPE: + On(Packet::As(udp_pack)); + break; + case Packet::EntityUpdate::TYPE: + On(Packet::As(udp_pack)); + break; + case Packet::PlayerCorrection::TYPE: + On(Packet::As(udp_pack)); + break; + case Packet::ChunkBegin::TYPE: + On(Packet::As(udp_pack)); + break; + case Packet::ChunkData::TYPE: + On(Packet::As(udp_pack)); + break; + case Packet::BlockUpdate::TYPE: + On(Packet::As(udp_pack)); + break; + case Packet::Message::TYPE: + On(Packet::As(udp_pack)); + break; default: // drop unknown or unhandled packets break; } } - -Server::Server(const Config &conf, World &world) -: serv_sock(nullptr) -, serv_pack{ -1, nullptr, 0 } -, clients() -, world(world) { - serv_sock = SDLNet_UDP_Open(conf.port); - if (!serv_sock) { - throw NetError("SDLNet_UDP_Open"); - } - - serv_pack.data = new Uint8[sizeof(Packet)]; - serv_pack.maxlen = sizeof(Packet); -} - -Server::~Server() { - delete[] serv_pack.data; - SDLNet_UDP_Close(serv_sock); -} - - -void Server::Handle() { - int result = SDLNet_UDP_Recv(serv_sock, &serv_pack); - while (result > 0) { - HandlePacket(serv_pack); - result = SDLNet_UDP_Recv(serv_sock, &serv_pack); - } - if (result == -1) { - // a boo boo happened - throw NetError("SDLNet_UDP_Recv"); - } -} - -void Server::HandlePacket(const UDPpacket &udp_pack) { - if (udp_pack.len < int(sizeof(Packet::Header))) { - // packet too small, drop - return; - } - const Packet &pack = *reinterpret_cast(udp_pack.data); - if (pack.header.tag != Packet::TAG) { - // mistagged packet, drop - return; - } - - ClientConnection &client = GetClient(udp_pack.address); - client.GetConnection().Received(udp_pack); -} - -ClientConnection &Server::GetClient(const IPaddress &addr) { - for (ClientConnection &client : clients) { - if (client.Matches(addr)) { - return client; - } - } - clients.emplace_back(*this, addr); - return clients.back(); -} - -void Server::Update(int dt) { - for (list::iterator client(clients.begin()), end(clients.end()); client != end;) { - client->Update(dt); - if (client->Disconnected()) { - client = clients.erase(client); - } else { - ++client; - } - } -} - }