1 #include "Connection.hpp"
2 #include "ConnectionHandler.hpp"
6 #include "../app/init.hpp"
7 #include "../model/Model.hpp"
8 #include "../world/Entity.hpp"
9 #include "../world/EntityState.hpp"
18 constexpr size_t Packet::Ping::MAX_LEN;
19 constexpr size_t Packet::Login::MAX_LEN;
20 constexpr size_t Packet::Join::MAX_LEN;
21 constexpr size_t Packet::Part::MAX_LEN;
22 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
23 constexpr size_t Packet::SpawnEntity::MAX_LEN;
24 constexpr size_t Packet::DespawnEntity::MAX_LEN;
25 constexpr size_t Packet::EntityUpdate::MAX_LEN;
26 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
27 constexpr size_t Packet::ChunkBegin::MAX_LEN;
28 constexpr size_t Packet::ChunkData::MAX_LEN;
29 constexpr size_t Packet::BlockUpdate::MAX_LEN;
30 constexpr size_t Packet::Message::MAX_LEN;
31 constexpr size_t Packet::Message::MAX_MESSAGE_LEN;
33 Connection::Connection(const IPaddress &addr)
38 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
39 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
45 bool Connection::Matches(const IPaddress &remote) const noexcept {
46 return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
49 void Connection::FlagSend() noexcept {
53 void Connection::FlagRecv() noexcept {
57 bool Connection::ShouldPing() const noexcept {
58 return !closed && send_timer.HitOnce();
61 bool Connection::TimedOut() const noexcept {
62 return recv_timer.HitOnce();
65 void Connection::Update(int dt) {
66 send_timer.Update(dt);
67 recv_timer.Update(dt);
71 Handler().OnTimeout();
77 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
78 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
79 pack.header.ctrl = ctrl_out;
80 uint16_t seq = ctrl_out.seq++;
82 udp_pack.address = addr;
83 if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
84 throw NetError("SDLNet_UDP_Send");
91 void Connection::Received(const UDPpacket &udp_pack) {
92 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
95 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
100 ctrl_out.hist <<= diff;
101 ctrl_out.hist |= 1 << (diff - 1);
103 } else if (diff < 0 && diff >= -32) {
104 ctrl_out.hist |= 1 << (-diff - 1);
106 ctrl_out.ack = pack.header.ctrl.seq;
113 Packet::TControl ctrl_new = pack.header.ctrl;
114 Handler().Handle(udp_pack);
117 // if the packet holds more recent information
118 // check if remote failed to ack one of our packets
119 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
120 // should always be true, but you never know…
122 for (int i = 0; i < diff; ++i) {
123 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
124 Handler().PacketLost(ctrl_in.ack - 32 + i);
128 // check for newly ack'd packets
129 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
130 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
131 Handler().PacketReceived(s);
138 bool Packet::TControl::Acks(uint16_t s) const noexcept {
139 int16_t diff = int16_t(ack) - int16_t(s);
140 if (diff == 0) return true;
141 if (diff < 0 || diff > 32) return false;
142 return (hist & (1 << (diff - 1))) != 0;
145 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
146 Packet::Make<Packet::Ping>(udp_pack);
147 return Send(udp_pack, sock);
151 ConnectionHandler::ConnectionHandler()
153 , packets_received(0)
154 , packet_loss(0.0f) {
158 void ConnectionHandler::PacketLost(uint16_t seq) {
164 void ConnectionHandler::PacketReceived(uint16_t seq) {
165 OnPacketReceived(seq);
170 void ConnectionHandler::UpdatePacketLoss() noexcept {
171 unsigned int packets_total = packets_lost + packets_received;
172 if (packets_total >= 256) {
173 packet_loss = float(packets_lost) / float(packets_total);
175 packets_received = 0;
180 ostream &operator <<(ostream &out, const IPaddress &addr) {
181 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
183 << '.' << int(host[1])
184 << '.' << int(host[2])
185 << '.' << int(host[3]);
187 out << ':' << SDLNet_Read16(&addr.port);
193 const char *Packet::Type2String(uint8_t t) noexcept {
203 case PlayerUpdate::TYPE:
204 return "PlayerUpdate";
205 case SpawnEntity::TYPE:
206 return "SpawnEntity";
207 case DespawnEntity::TYPE:
208 return "DespawnEntity";
209 case EntityUpdate::TYPE:
210 return "EntityUpdate";
211 case PlayerCorrection::TYPE:
212 return "PlayerCorrection";
213 case ChunkBegin::TYPE:
215 case ChunkData::TYPE:
217 case BlockUpdate::TYPE:
218 return "BlockUpdate";
227 void Packet::Payload::Write(const T &src, size_t off) noexcept {
228 if ((length - off) < sizeof(T)) {
229 // dismiss out of bounds write
232 *reinterpret_cast<T *>(&data[off]) = src;
236 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
237 if ((length - off) < sizeof(T)) {
238 // dismiss out of bounds read
241 dst = *reinterpret_cast<T *>(&data[off]);
244 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
245 uint8_t *dst = &data[off];
246 size_t len = min(maxlen, length - off);
247 if (src.size() < len) {
248 memset(dst, '\0', len);
249 memcpy(dst, src.c_str(), src.size());
251 memcpy(dst, src.c_str(), len);
255 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
256 size_t len = min(maxlen, length - off);
259 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
260 dst.push_back(data[off + i]);
264 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
265 WritePackN(val.w, off);
266 WritePackN(val.x, off + 2);
267 WritePackN(val.y, off + 4);
268 WritePackN(val.z, off + 6);
271 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
272 ReadPackN(val.w, off);
273 ReadPackN(val.x, off + 2);
274 ReadPackN(val.y, off + 4);
275 ReadPackN(val.z, off + 6);
276 val = normalize(val);
279 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
280 Write(state.chunk_pos, off);
281 WritePackU(state.block_pos * (1.0f / 16.0f), off + 12);
282 Write(state.velocity, off + 18);
283 Write(state.orient, off + 30);
284 Write(state.ang_vel, off + 38);
287 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
288 Read(state.chunk_pos, off);
289 ReadPackU(state.block_pos, off + 12);
290 Read(state.velocity, off + 18);
291 Read(state.orient, off + 30);
292 Read(state.ang_vel, off + 38);
293 state.block_pos *= 16.0f;
296 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
297 WritePackB(state.chunk_pos - base, off);
298 WritePackU(state.block_pos * (1.0f / 16.0f), off + 3);
299 Write(state.velocity, off + 9);
300 Write(state.orient, off + 21);
301 Write(state.ang_vel, off + 29);
304 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
305 ReadPackB(state.chunk_pos, off);
306 ReadPackU(state.block_pos, off + 3);
307 Read(state.velocity, off + 9);
308 Read(state.orient, off + 21);
309 Read(state.ang_vel, off + 29);
310 state.chunk_pos += base;
311 state.block_pos *= 16.0f;
314 void Packet::Payload::WritePackN(float val, size_t off) noexcept {
315 int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f);
319 void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept {
320 Write(int8_t(val.x), off);
321 Write(int8_t(val.y), off + 1);
322 Write(int8_t(val.z), off + 2);
325 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
335 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
338 val = raw * (1.0f/32767.0f);
341 void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept {
342 WritePackN(val.x, off);
343 WritePackN(val.y, off + 2);
344 WritePackN(val.z, off + 4);
347 void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept {
348 ReadPackN(val.x, off);
349 ReadPackN(val.y, off + 2);
350 ReadPackN(val.z, off + 4);
353 void Packet::Payload::WritePackU(float val, size_t off) noexcept {
354 uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f);
358 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
361 val = raw * (1.0f/65535.0f);
364 void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept {
365 WritePackU(val.x, off);
366 WritePackU(val.y, off + 2);
367 WritePackU(val.z, off + 4);
370 void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept {
371 ReadPackU(val.x, off);
372 ReadPackU(val.y, off + 2);
373 ReadPackU(val.z, off + 4);
377 void Packet::Login::WritePlayerName(const string &name) noexcept {
378 WriteString(name, 0, 32);
381 void Packet::Login::ReadPlayerName(string &name) const noexcept {
382 ReadString(name, 0, 32);
385 void Packet::Join::WritePlayer(const Entity &player) noexcept {
386 Write(player.ID(), 0);
387 Write(player.GetState(), 4);
390 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
394 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
398 void Packet::Join::WriteWorldName(const string &name) noexcept {
399 WriteString(name, 54, 32);
402 void Packet::Join::ReadWorldName(string &name) const noexcept {
403 ReadString(name, 54, 32);
406 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
410 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
414 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
418 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
422 void Packet::PlayerUpdate::WritePitch(float pitch) noexcept {
423 float conv = pitch * PI_0p5_inv;
424 WritePackN(conv, 56);
427 void Packet::PlayerUpdate::ReadPitch(float &pitch) const noexcept {
428 ReadPackN(pitch, 56);
432 void Packet::PlayerUpdate::WriteYaw(float yaw) noexcept {
433 float conv = yaw * PI_inv;
434 WritePackN(conv, 58);
437 void Packet::PlayerUpdate::ReadYaw(float &yaw) const noexcept {
442 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
446 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
450 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
454 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
458 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
461 Write(e.GetModel().GetModel().ID(), 4);
463 Write(uint32_t(0), 4);
465 Write(e.GetState(), 8);
466 Write(e.Bounds(), 58);
468 if (e.WorldCollidable()) {
472 WriteString(e.Name(), 86, 32);
475 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
479 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
483 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
492 ReadString(name, 86, 32);
496 e.WorldCollidable(flags & 1);
500 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
504 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
508 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
512 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
516 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
520 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
524 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
525 uint32_t off = GetSize(num);
527 Write(entity.ID(), off);
528 Write(entity.GetState(), base, off + 4);
531 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
532 uint32_t off = GetSize(num);
536 void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept {
537 uint32_t off = GetSize(num);
538 Read(state, base, off + 4);
541 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
545 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
549 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
550 Write(player.GetState(), 2);
553 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
557 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
561 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
565 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
569 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
573 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
577 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
581 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
585 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
589 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
593 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
597 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
601 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
605 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
609 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
613 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
614 size_t len = min(length - 12, l);
615 memcpy(&data[12], d, len);
618 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
619 size_t len = min(length - 12, l);
620 memcpy(d, &data[12], len);
623 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
627 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
631 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
635 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
639 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
640 uint32_t off = GetSize(num);
644 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
645 uint32_t off = GetSize(num);
649 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
650 uint32_t off = GetSize(num) + 2;
654 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
655 uint32_t off = GetSize(num) + 2;
659 void Packet::Message::WriteType(uint8_t type) noexcept {
663 void Packet::Message::ReadType(uint8_t &type) const noexcept {
667 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
671 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
675 void Packet::Message::WriteMessage(const string &msg) noexcept {
676 WriteString(msg, 5, MAX_MESSAGE_LEN);
679 void Packet::Message::ReadMessage(string &msg) const noexcept {
680 ReadString(msg, 5, MAX_MESSAGE_LEN);
684 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
685 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
686 switch (pack.Type()) {
687 case Packet::Ping::TYPE:
688 On(Packet::As<Packet::Ping>(udp_pack));
690 case Packet::Login::TYPE:
691 On(Packet::As<Packet::Login>(udp_pack));
693 case Packet::Join::TYPE:
694 On(Packet::As<Packet::Join>(udp_pack));
696 case Packet::Part::TYPE:
697 On(Packet::As<Packet::Part>(udp_pack));
699 case Packet::PlayerUpdate::TYPE:
700 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
702 case Packet::SpawnEntity::TYPE:
703 On(Packet::As<Packet::SpawnEntity>(udp_pack));
705 case Packet::DespawnEntity::TYPE:
706 On(Packet::As<Packet::DespawnEntity>(udp_pack));
708 case Packet::EntityUpdate::TYPE:
709 On(Packet::As<Packet::EntityUpdate>(udp_pack));
711 case Packet::PlayerCorrection::TYPE:
712 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
714 case Packet::ChunkBegin::TYPE:
715 On(Packet::As<Packet::ChunkBegin>(udp_pack));
717 case Packet::ChunkData::TYPE:
718 On(Packet::As<Packet::ChunkData>(udp_pack));
720 case Packet::BlockUpdate::TYPE:
721 On(Packet::As<Packet::BlockUpdate>(udp_pack));
723 case Packet::Message::TYPE:
724 On(Packet::As<Packet::Message>(udp_pack));
727 // drop unknown or unhandled packets