2 #include "ClientConnection.hpp"
3 #include "Connection.hpp"
4 #include "ConnectionHandler.hpp"
9 #include "../app/init.hpp"
10 #include "../model/CompositeModel.hpp"
11 #include "../world/Entity.hpp"
12 #include "../world/EntityState.hpp"
13 #include "../world/World.hpp"
17 #include <glm/gtx/io.hpp>
24 constexpr size_t Packet::Ping::MAX_LEN;
25 constexpr size_t Packet::Login::MAX_LEN;
26 constexpr size_t Packet::Join::MAX_LEN;
27 constexpr size_t Packet::Part::MAX_LEN;
28 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
29 constexpr size_t Packet::SpawnEntity::MAX_LEN;
30 constexpr size_t Packet::DespawnEntity::MAX_LEN;
31 constexpr size_t Packet::EntityUpdate::MAX_LEN;
32 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
36 UDPsocket client_bind(Uint16 port) {
37 UDPsocket sock = SDLNet_UDP_Open(port);
39 throw NetError("SDLNet_UDP_Open");
44 IPaddress client_resolve(const char *host, Uint16 port) {
46 if (SDLNet_ResolveHost(&addr, host, port) != 0) {
47 throw NetError("SDLNet_ResolveHost");
54 Client::Client(const Config &conf)
55 : conn(client_resolve(conf.host.c_str(), conf.port))
56 , client_sock(client_bind(0))
57 , client_pack{ -1, nullptr, 0 } {
58 client_pack.data = new Uint8[sizeof(Packet)];
59 client_pack.maxlen = sizeof(Packet);
60 // establish connection
65 delete[] client_pack.data;
66 SDLNet_UDP_Close(client_sock);
70 void Client::Handle() {
71 int result = SDLNet_UDP_Recv(client_sock, &client_pack);
73 HandlePacket(client_pack);
74 result = SDLNet_UDP_Recv(client_sock, &client_pack);
78 throw NetError("SDLNet_UDP_Recv");
82 void Client::HandlePacket(const UDPpacket &udp_pack) {
83 if (!conn.Matches(udp_pack.address)) {
84 // packet came from somewhere else, drop
87 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
88 if (pack.header.tag != Packet::TAG) {
89 // mistagged packet, drop
93 conn.Received(udp_pack);
96 void Client::Update(int dt) {
98 if (conn.ShouldPing()) {
103 uint16_t Client::SendPing() {
104 return conn.SendPing(client_pack, client_sock);
107 uint16_t Client::SendLogin(const string &name) {
108 auto pack = Packet::Make<Packet::Login>(client_pack);
109 pack.WritePlayerName(name);
110 return conn.Send(client_pack, client_sock);
113 uint16_t Client::SendPlayerUpdate(const Entity &player) {
114 auto pack = Packet::Make<Packet::PlayerUpdate>(client_pack);
115 pack.WritePlayer(player);
116 return conn.Send(client_pack, client_sock);
119 uint16_t Client::SendPart() {
120 Packet::Make<Packet::Part>(client_pack);
121 return conn.Send(client_pack, client_sock);
125 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
131 , player_update_pack(0)
132 , player_update_timer(1500) {
133 conn.SetHandler(this);
136 ClientConnection::~ClientConnection() {
140 void ClientConnection::Update(int dt) {
142 if (Disconnected()) {
147 auto global_iter = server.GetWorld().Entities().begin();
148 auto global_end = server.GetWorld().Entities().end();
149 auto local_iter = spawns.begin();
150 auto local_end = spawns.end();
152 while (global_iter != global_end && local_iter != local_end) {
153 if (global_iter->ID() == local_iter->entity->ID()) {
155 if (CanDespawn(*global_iter)) {
156 SendDespawn(*local_iter);
159 SendUpdate(*local_iter);
163 } else if (global_iter->ID() < local_iter->entity->ID()) {
164 // global entity was inserted
165 if (CanSpawn(*global_iter)) {
166 auto spawned = spawns.emplace(local_iter, *global_iter);
171 // global entity was removed
172 SendDespawn(*local_iter);
178 while (global_iter != global_end) {
179 if (CanSpawn(*global_iter)) {
180 spawns.emplace_back(*global_iter);
181 SendSpawn(spawns.back());
187 while (local_iter != local_end) {
188 SendDespawn(*local_iter);
194 if (conn.ShouldPing()) {
195 conn.SendPing(server.GetPacket(), server.GetSocket());
199 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
206 ClientConnection::SpawnStatus::~SpawnStatus() {
210 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
214 manhattan_radius(e.ChunkCoords() - Player().ChunkCoords()) < 7;
217 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
220 manhattan_radius(e.ChunkCoords() - Player().ChunkCoords()) > 7;
223 void ClientConnection::SendSpawn(SpawnStatus &status) {
224 // don't double spawn
225 if (status.spawn_pack != -1) return;
227 auto pack = Packet::Make<Packet::SpawnEntity>(server.GetPacket());
228 pack.WriteEntity(*status.entity);
229 status.spawn_pack = conn.Send(server.GetPacket(), server.GetSocket());
233 void ClientConnection::SendDespawn(SpawnStatus &status) {
234 // don't double despawn
235 if (status.despawn_pack != -1) return;
237 auto pack = Packet::Make<Packet::DespawnEntity>(server.GetPacket());
238 pack.WriteEntityID(status.entity->ID());
239 status.despawn_pack = conn.Send(server.GetPacket(), server.GetSocket());
243 void ClientConnection::SendUpdate(SpawnStatus &status) {
244 // don't send updates while spawn not ack'd or despawn sent
245 if (status.spawn_pack != -1 || status.despawn_pack != -1) return;
247 // TODO: pack entity updates
248 auto pack = Packet::Make<Packet::EntityUpdate>(server.GetPacket());
249 pack.WriteEntityCount(1);
250 pack.WriteEntity(*status.entity, 0);
251 server.GetPacket().len = Packet::EntityUpdate::GetSize(1);
252 conn.Send(server.GetPacket(), server.GetSocket());
255 void ClientConnection::CheckPlayerFix() {
256 // check always succeeds for now ;)
257 auto pack = Packet::Make<Packet::PlayerCorrection>(server.GetPacket());
258 pack.WritePacketSeq(player_update_pack);
259 pack.WritePlayer(Player());
260 conn.Send(server.GetPacket(), server.GetSocket());
263 void ClientConnection::AttachPlayer(Entity &new_player) {
265 player = &new_player;
267 cout << "player \"" << player->Name() << "\" joined" << endl;
270 void ClientConnection::DetachPlayer() {
274 cout << "player \"" << player->Name() << "\" left" << endl;
278 void ClientConnection::OnPacketReceived(uint16_t seq) {
279 if (!confirm_wait) return;
280 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
281 if (seq == iter->spawn_pack) {
282 iter->spawn_pack = -1;
286 if (seq == iter->despawn_pack) {
294 void ClientConnection::OnPacketLost(uint16_t seq) {
295 if (!confirm_wait) return;
296 for (SpawnStatus &status : spawns) {
297 if (seq == status.spawn_pack) {
298 status.spawn_pack = -1;
303 if (seq == status.despawn_pack) {
304 status.despawn_pack = -1;
312 void ClientConnection::On(const Packet::Login &pack) {
314 pack.ReadPlayerName(name);
316 Entity *new_player = server.GetWorld().AddPlayer(name).entity;
320 AttachPlayer(*new_player);
321 cout << "accepted login from player \"" << name << '"' << endl;
322 auto response = Packet::Make<Packet::Join>(server.GetPacket());
323 response.WritePlayer(*new_player);
324 response.WriteWorldName(server.GetWorld().Name());
325 conn.Send(server.GetPacket(), server.GetSocket());
326 // set up update tracking
327 player_update_pack = pack.Seq();
328 player_update_timer.Reset();
329 player_update_timer.Start();
332 cout << "rejected login from player \"" << name << '"' << endl;
333 Packet::Make<Packet::Part>(server.GetPacket());
334 conn.Send(server.GetPacket(), server.GetSocket());
339 void ClientConnection::On(const Packet::Part &) {
343 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
344 if (!HasPlayer()) return;
345 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
346 bool overdue = player_update_timer.HitOnce();
347 player_update_timer.Reset();
348 if (pack_diff > 0 || overdue) {
349 player_update_pack = pack.Seq();
350 // TODO: do client input validation here
351 pack.ReadPlayerState(Player().GetState());
356 Connection::Connection(const IPaddress &addr)
361 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
362 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
368 bool Connection::Matches(const IPaddress &remote) const noexcept {
369 return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
372 void Connection::FlagSend() noexcept {
376 void Connection::FlagRecv() noexcept {
380 bool Connection::ShouldPing() const noexcept {
381 return !closed && send_timer.HitOnce();
384 bool Connection::TimedOut() const noexcept {
385 return recv_timer.HitOnce();
388 void Connection::Update(int dt) {
389 send_timer.Update(dt);
390 recv_timer.Update(dt);
394 Handler().OnTimeout();
400 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
401 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
402 pack.header.ctrl = ctrl_out;
403 uint16_t seq = ctrl_out.seq++;
405 udp_pack.address = addr;
406 if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
407 throw NetError("SDLNet_UDP_Send");
414 void Connection::Received(const UDPpacket &udp_pack) {
415 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
418 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
423 ctrl_out.hist <<= diff;
424 ctrl_out.hist |= 1 << (diff - 1);
426 } else if (diff < 0 && diff >= -32) {
427 ctrl_out.hist |= 1 << (-diff - 1);
429 ctrl_out.ack = pack.header.ctrl.seq;
436 Packet::TControl ctrl_new = pack.header.ctrl;
437 Handler().Handle(udp_pack);
440 // if the packet holds more recent information
441 // check if remote failed to ack one of our packets
442 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
443 // should always be true, but you never know…
445 for (int i = 0; i < diff; ++i) {
446 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
447 Handler().OnPacketLost(ctrl_in.ack - 32 + i);
451 // check for newly ack'd packets
452 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); ++s) {
453 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
454 Handler().OnPacketReceived(s);
461 bool Packet::TControl::Acks(uint16_t s) const noexcept {
462 int16_t diff = int16_t(ack) - int16_t(s);
463 if (diff == 0) return true;
464 if (diff < 0 || diff > 32) return false;
465 return (hist & (1 << (diff - 1))) != 0;
468 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
469 Packet::Make<Packet::Ping>(udp_pack);
470 return Send(udp_pack, sock);
474 ostream &operator <<(ostream &out, const IPaddress &addr) {
475 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
477 << '.' << int(host[1])
478 << '.' << int(host[2])
479 << '.' << int(host[3]);
481 out << ':' << SDLNet_Read16(&addr.port);
487 const char *Packet::Type2String(uint8_t t) noexcept {
497 case PlayerUpdate::TYPE:
498 return "PlayerUpdate";
499 case SpawnEntity::TYPE:
500 return "SpawnEntity";
501 case DespawnEntity::TYPE:
502 return "DespawnEntity";
503 case EntityUpdate::TYPE:
504 return "EntityUpdate";
505 case PlayerCorrection::TYPE:
506 return "PlayerCorrection";
513 void Packet::Payload::Write(const T &src, size_t off) noexcept {
514 if ((length - off) < sizeof(T)) {
515 // dismiss out of bounds write
518 *reinterpret_cast<T *>(&data[off]) = src;
522 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
523 if ((length - off) < sizeof(T)) {
524 // dismiss out of bounds read
527 dst = *reinterpret_cast<T *>(&data[off]);
530 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
531 uint8_t *dst = &data[off];
532 size_t len = min(maxlen, length - off);
533 if (src.size() < len) {
534 memset(dst, '\0', len);
535 memcpy(dst, src.c_str(), src.size());
537 memcpy(dst, src.c_str(), len);
541 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
542 size_t len = min(maxlen, length - off);
545 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
546 dst.push_back(data[off + i]);
551 void Packet::Login::WritePlayerName(const string &name) noexcept {
552 WriteString(name, 0, 32);
555 void Packet::Login::ReadPlayerName(string &name) const noexcept {
556 ReadString(name, 0, 32);
559 void Packet::Join::WritePlayer(const Entity &player) noexcept {
560 Write(player.ID(), 0);
561 Write(player.GetState(), 4);
564 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
568 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
572 void Packet::Join::WriteWorldName(const string &name) noexcept {
573 WriteString(name, 68, 32);
576 void Packet::Join::ReadWorldName(string &name) const noexcept {
577 ReadString(name, 68, 32);
580 void Packet::PlayerUpdate::WritePlayer(const Entity &player) noexcept {
581 Write(player.GetState(), 0);
584 void Packet::PlayerUpdate::ReadPlayerState(EntityState &state) const noexcept {
588 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
591 Write(e.GetModel().GetModel().ID(), 4);
593 Write(uint32_t(0), 4);
595 Write(e.GetState(), 8);
596 Write(e.Bounds(), 72);
598 if (e.WorldCollidable()) {
602 WriteString(e.Name(), 100, 32);
605 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
609 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
613 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
622 ReadString(name, 100, 32);
626 e.WorldCollidable(flags & 1);
630 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
634 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
638 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
642 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
646 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
647 uint32_t off = 4 + (num * 64);
649 Write(entity.ID(), off);
650 Write(entity.GetState(), off + 4);
653 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
654 Read(id, 4 + (num * 64));
657 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
658 uint32_t off = 4 + (num * 64);
659 Read(state, off + 4);
662 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
666 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
670 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
671 Write(player.GetState(), 2);
674 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
679 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
680 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
681 switch (pack.Type()) {
682 case Packet::Ping::TYPE:
683 On(Packet::As<Packet::Ping>(udp_pack));
685 case Packet::Login::TYPE:
686 On(Packet::As<Packet::Login>(udp_pack));
688 case Packet::Join::TYPE:
689 On(Packet::As<Packet::Join>(udp_pack));
691 case Packet::Part::TYPE:
692 On(Packet::As<Packet::Part>(udp_pack));
694 case Packet::PlayerUpdate::TYPE:
695 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
697 case Packet::SpawnEntity::TYPE:
698 On(Packet::As<Packet::SpawnEntity>(udp_pack));
700 case Packet::DespawnEntity::TYPE:
701 On(Packet::As<Packet::DespawnEntity>(udp_pack));
703 case Packet::EntityUpdate::TYPE:
704 On(Packet::As<Packet::EntityUpdate>(udp_pack));
706 case Packet::PlayerCorrection::TYPE:
707 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
710 // drop unknown or unhandled packets
716 Server::Server(const Config &conf, World &world)
718 , serv_pack{ -1, nullptr, 0 }
721 serv_sock = SDLNet_UDP_Open(conf.port);
723 throw NetError("SDLNet_UDP_Open");
726 serv_pack.data = new Uint8[sizeof(Packet)];
727 serv_pack.maxlen = sizeof(Packet);
731 delete[] serv_pack.data;
732 SDLNet_UDP_Close(serv_sock);
736 void Server::Handle() {
737 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
739 HandlePacket(serv_pack);
740 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
743 // a boo boo happened
744 throw NetError("SDLNet_UDP_Recv");
748 void Server::HandlePacket(const UDPpacket &udp_pack) {
749 if (udp_pack.len < int(sizeof(Packet::Header))) {
750 // packet too small, drop
753 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
754 if (pack.header.tag != Packet::TAG) {
755 // mistagged packet, drop
759 ClientConnection &client = GetClient(udp_pack.address);
760 client.GetConnection().Received(udp_pack);
763 ClientConnection &Server::GetClient(const IPaddress &addr) {
764 for (ClientConnection &client : clients) {
765 if (client.Matches(addr)) {
769 clients.emplace_back(*this, addr);
770 return clients.back();
773 void Server::Update(int dt) {
774 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
776 if (client->Disconnected()) {
777 client = clients.erase(client);