1 #include "CongestionControl.hpp"
2 #include "Connection.hpp"
3 #include "ConnectionHandler.hpp"
7 #include "../app/init.hpp"
8 #include "../model/Model.hpp"
9 #include "../world/Entity.hpp"
10 #include "../world/EntityState.hpp"
19 constexpr size_t Packet::Ping::MAX_LEN;
20 constexpr size_t Packet::Login::MAX_LEN;
21 constexpr size_t Packet::Join::MAX_LEN;
22 constexpr size_t Packet::Part::MAX_LEN;
23 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
24 constexpr size_t Packet::SpawnEntity::MAX_LEN;
25 constexpr size_t Packet::DespawnEntity::MAX_LEN;
26 constexpr size_t Packet::EntityUpdate::MAX_LEN;
27 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
28 constexpr size_t Packet::ChunkBegin::MAX_LEN;
29 constexpr size_t Packet::ChunkData::MAX_LEN;
30 constexpr size_t Packet::BlockUpdate::MAX_LEN;
31 constexpr size_t Packet::Message::MAX_LEN;
32 constexpr size_t Packet::Message::MAX_MESSAGE_LEN;
35 CongestionControl::CongestionControl()
36 // I know, I know, it's an estimate (about 20 for IPv4, 48 for IPv6)
38 // only sample every eighth packet for measuring RTT
51 Uint32 now = SDL_GetTicks();
52 for (Uint32 &s : stamps) {
58 void CongestionControl::PacketSent(uint16_t seq) noexcept {
59 if (!SamplePacket(seq)) {
62 stamp_cursor = (stamp_cursor + 1) % 16;
63 stamps[stamp_cursor] = SDL_GetTicks();
67 void CongestionControl::PacketLost(uint16_t seq) noexcept {
73 void CongestionControl::PacketReceived(uint16_t seq) noexcept {
79 void CongestionControl::UpdatePacketLoss() noexcept {
80 unsigned int packets_total = packets_lost + packets_received;
81 if (packets_total >= 256) {
82 packet_loss = float(packets_lost) / float(packets_total);
88 void CongestionControl::UpdateRTT(std::uint16_t seq) noexcept {
89 if (!SamplePacket(seq)) return;
90 int diff = HeadDiff(seq);
91 if (diff > 0 || diff < -15) {
92 // packet outside observed time frame
95 int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16];
96 rtt += (cur_rtt - rtt) * 0.1f;
99 bool CongestionControl::SamplePacket(std::uint16_t seq) const noexcept {
100 return seq % sample_skip == 0;
103 int CongestionControl::HeadDiff(std::uint16_t seq) const noexcept {
104 int16_t diff = int16_t(seq) - int16_t(stamp_last);
105 return diff / sample_skip;
108 void CongestionControl::PacketIn(const UDPpacket &pack) noexcept {
109 rx_bytes += pack.len + packet_overhead;
113 void CongestionControl::PacketOut(const UDPpacket &pack) noexcept {
114 tx_bytes += pack.len + packet_overhead;
118 void CongestionControl::UpdateStats() noexcept {
119 Uint32 now = SDL_GetTicks();
120 if (now >= next_sample) {
121 tx_kbps = float(tx_bytes) * (1.0f / 1024.0f);
122 rx_kbps = float(rx_bytes) * (1.0f / 1024.0f);
130 Connection::Connection(const IPaddress &addr)
135 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
136 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
142 bool Connection::Matches(const IPaddress &remote) const noexcept {
143 return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
146 void Connection::FlagSend() noexcept {
150 void Connection::FlagRecv() noexcept {
154 bool Connection::ShouldPing() const noexcept {
155 return !closed && send_timer.HitOnce();
158 bool Connection::TimedOut() const noexcept {
159 return recv_timer.HitOnce();
162 void Connection::Update(int dt) {
163 send_timer.Update(dt);
164 recv_timer.Update(dt);
168 Handler().OnTimeout();
174 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
175 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
176 pack.header.ctrl = ctrl_out;
177 uint16_t seq = ctrl_out.seq++;
179 udp_pack.address = addr;
180 if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
181 throw NetError("SDLNet_UDP_Send");
185 Handler().PacketOut(udp_pack);
186 Handler().PacketSent(seq);
193 void Connection::Received(const UDPpacket &udp_pack) {
194 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
197 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
202 ctrl_out.hist <<= diff;
203 ctrl_out.hist |= 1 << (diff - 1);
205 } else if (diff < 0 && diff >= -32) {
206 ctrl_out.hist |= 1 << (-diff - 1);
208 ctrl_out.ack = pack.header.ctrl.seq;
215 Packet::TControl ctrl_new = pack.header.ctrl;
216 Handler().PacketIn(udp_pack);
217 Handler().Handle(udp_pack);
220 // if the packet holds more recent information
221 // check if remote failed to ack one of our packets
222 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
223 // should always be true, but you never know…
225 for (int i = 0; i < diff; ++i) {
226 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
227 Handler().PacketLost(ctrl_in.ack - 32 + i);
231 // check for newly ack'd packets
232 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
233 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
234 Handler().PacketReceived(s);
241 bool Packet::TControl::Acks(uint16_t s) const noexcept {
242 int16_t diff = int16_t(ack) - int16_t(s);
243 if (diff == 0) return true;
244 if (diff < 0 || diff > 32) return false;
245 return (hist & (1 << (diff - 1))) != 0;
248 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
249 Packet::Make<Packet::Ping>(udp_pack);
250 return Send(udp_pack, sock);
254 ConnectionHandler::ConnectionHandler()
259 void ConnectionHandler::PacketSent(uint16_t seq) noexcept {
263 void ConnectionHandler::PacketLost(uint16_t seq) {
268 void ConnectionHandler::PacketReceived(uint16_t seq) {
269 OnPacketReceived(seq);
270 cc.PacketReceived(seq);
273 void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept {
277 void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept {
282 ostream &operator <<(ostream &out, const IPaddress &addr) {
283 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
285 << '.' << int(host[1])
286 << '.' << int(host[2])
287 << '.' << int(host[3]);
289 out << ':' << SDLNet_Read16(&addr.port);
295 const char *Packet::Type2String(uint8_t t) noexcept {
305 case PlayerUpdate::TYPE:
306 return "PlayerUpdate";
307 case SpawnEntity::TYPE:
308 return "SpawnEntity";
309 case DespawnEntity::TYPE:
310 return "DespawnEntity";
311 case EntityUpdate::TYPE:
312 return "EntityUpdate";
313 case PlayerCorrection::TYPE:
314 return "PlayerCorrection";
315 case ChunkBegin::TYPE:
317 case ChunkData::TYPE:
319 case BlockUpdate::TYPE:
320 return "BlockUpdate";
329 void Packet::Payload::Write(const T &src, size_t off) noexcept {
330 if ((length - off) < sizeof(T)) {
331 // dismiss out of bounds write
334 *reinterpret_cast<T *>(&data[off]) = src;
338 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
339 if ((length - off) < sizeof(T)) {
340 // dismiss out of bounds read
343 dst = *reinterpret_cast<T *>(&data[off]);
346 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
347 uint8_t *dst = &data[off];
348 size_t len = min(maxlen, length - off);
349 if (src.size() < len) {
350 memset(dst, '\0', len);
351 memcpy(dst, src.c_str(), src.size());
353 memcpy(dst, src.c_str(), len);
357 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
358 size_t len = min(maxlen, length - off);
361 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
362 dst.push_back(data[off + i]);
366 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
367 WritePackN(val.w, off);
368 WritePackN(val.x, off + 2);
369 WritePackN(val.y, off + 4);
370 WritePackN(val.z, off + 6);
373 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
374 ReadPackN(val.w, off);
375 ReadPackN(val.x, off + 2);
376 ReadPackN(val.y, off + 4);
377 ReadPackN(val.z, off + 6);
378 val = normalize(val);
381 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
382 Write(state.chunk_pos, off);
383 WritePackU(state.block_pos * (1.0f / 16.0f), off + 12);
384 Write(state.velocity, off + 18);
385 Write(state.orient, off + 30);
386 WritePackN(state.pitch * PI_0p5_inv, off + 38);
387 WritePackN(state.yaw * PI_inv, off + 40);
390 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
391 Read(state.chunk_pos, off);
392 ReadPackU(state.block_pos, off + 12);
393 Read(state.velocity, off + 18);
394 Read(state.orient, off + 30);
395 ReadPackN(state.pitch, off + 38);
396 ReadPackN(state.yaw, off + 40);
397 state.block_pos *= 16.0f;
398 state.pitch *= PI_0p5;
402 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
403 WritePackB(state.chunk_pos - base, off);
404 WritePackU(state.block_pos * (1.0f / 16.0f), off + 3);
405 Write(state.velocity, off + 9);
406 Write(state.orient, off + 21);
407 WritePackN(state.pitch * PI_0p5_inv, off + 29);
408 WritePackN(state.yaw * PI_inv, off + 31);
411 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
412 ReadPackB(state.chunk_pos, off);
413 ReadPackU(state.block_pos, off + 3);
414 Read(state.velocity, off + 9);
415 Read(state.orient, off + 21);
416 ReadPackN(state.pitch, off + 29);
417 ReadPackN(state.yaw, off + 31);
418 state.chunk_pos += base;
419 state.block_pos *= 16.0f;
420 state.pitch *= PI_0p5;
424 void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept {
425 Write(int8_t(val.x), off);
426 Write(int8_t(val.y), off + 1);
427 Write(int8_t(val.z), off + 2);
430 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
440 void Packet::Payload::WritePackN(float val, size_t off) noexcept {
441 int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f);
445 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
448 val = raw * (1.0f/32767.0f);
451 void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept {
452 WritePackN(val.x, off);
453 WritePackN(val.y, off + 2);
454 WritePackN(val.z, off + 4);
457 void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept {
458 ReadPackN(val.x, off);
459 ReadPackN(val.y, off + 2);
460 ReadPackN(val.z, off + 4);
463 void Packet::Payload::WritePackU(float val, size_t off) noexcept {
464 uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f);
468 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
471 val = raw * (1.0f/65535.0f);
474 void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept {
475 WritePackU(val.x, off);
476 WritePackU(val.y, off + 2);
477 WritePackU(val.z, off + 4);
480 void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept {
481 ReadPackU(val.x, off);
482 ReadPackU(val.y, off + 2);
483 ReadPackU(val.z, off + 4);
487 void Packet::Login::WritePlayerName(const string &name) noexcept {
488 WriteString(name, 0, 32);
491 void Packet::Login::ReadPlayerName(string &name) const noexcept {
492 ReadString(name, 0, 32);
495 void Packet::Join::WritePlayer(const Entity &player) noexcept {
496 Write(player.ID(), 0);
497 Write(player.GetState(), 4);
500 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
504 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
508 void Packet::Join::WriteWorldName(const string &name) noexcept {
509 WriteString(name, 46, 32);
512 void Packet::Join::ReadWorldName(string &name) const noexcept {
513 ReadString(name, 46, 32);
516 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
520 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
524 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
528 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
532 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
536 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
540 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
544 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
548 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
551 Write(e.GetModel().GetModel().ID(), 4);
553 Write(uint32_t(0), 4);
555 Write(e.GetState(), 8);
556 Write(e.Bounds(), 50);
558 if (e.WorldCollidable()) {
562 WriteString(e.Name(), 78, 32);
565 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
569 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
573 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
582 ReadString(name, 78, 32);
586 e.WorldCollidable(flags & 1);
590 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
594 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
598 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
602 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
606 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
610 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
614 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
615 uint32_t off = GetSize(num);
617 Write(entity.ID(), off);
618 Write(entity.GetState(), base, off + 4);
621 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
622 uint32_t off = GetSize(num);
626 void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept {
627 uint32_t off = GetSize(num);
628 Read(state, base, off + 4);
631 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
635 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
639 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
640 Write(player.GetState(), 2);
643 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
647 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
651 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
655 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
659 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
663 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
667 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
671 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
675 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
679 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
683 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
687 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
691 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
695 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
699 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
703 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
704 size_t len = min(length - 12, l);
705 memcpy(&data[12], d, len);
708 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
709 size_t len = min(length - 12, l);
710 memcpy(d, &data[12], len);
713 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
717 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
721 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
725 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
729 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
730 uint32_t off = GetSize(num);
734 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
735 uint32_t off = GetSize(num);
739 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
740 uint32_t off = GetSize(num) + 2;
744 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
745 uint32_t off = GetSize(num) + 2;
749 void Packet::Message::WriteType(uint8_t type) noexcept {
753 void Packet::Message::ReadType(uint8_t &type) const noexcept {
757 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
761 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
765 void Packet::Message::WriteMessage(const string &msg) noexcept {
766 WriteString(msg, 5, MAX_MESSAGE_LEN);
769 void Packet::Message::ReadMessage(string &msg) const noexcept {
770 ReadString(msg, 5, MAX_MESSAGE_LEN);
774 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
775 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
776 switch (pack.Type()) {
777 case Packet::Ping::TYPE:
778 On(Packet::As<Packet::Ping>(udp_pack));
780 case Packet::Login::TYPE:
781 On(Packet::As<Packet::Login>(udp_pack));
783 case Packet::Join::TYPE:
784 On(Packet::As<Packet::Join>(udp_pack));
786 case Packet::Part::TYPE:
787 On(Packet::As<Packet::Part>(udp_pack));
789 case Packet::PlayerUpdate::TYPE:
790 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
792 case Packet::SpawnEntity::TYPE:
793 On(Packet::As<Packet::SpawnEntity>(udp_pack));
795 case Packet::DespawnEntity::TYPE:
796 On(Packet::As<Packet::DespawnEntity>(udp_pack));
798 case Packet::EntityUpdate::TYPE:
799 On(Packet::As<Packet::EntityUpdate>(udp_pack));
801 case Packet::PlayerCorrection::TYPE:
802 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
804 case Packet::ChunkBegin::TYPE:
805 On(Packet::As<Packet::ChunkBegin>(udp_pack));
807 case Packet::ChunkData::TYPE:
808 On(Packet::As<Packet::ChunkData>(udp_pack));
810 case Packet::BlockUpdate::TYPE:
811 On(Packet::As<Packet::BlockUpdate>(udp_pack));
813 case Packet::Message::TYPE:
814 On(Packet::As<Packet::Message>(udp_pack));
817 // drop unknown or unhandled packets