1 #include "CongestionControl.hpp"
2 #include "Connection.hpp"
3 #include "ConnectionHandler.hpp"
7 #include "../app/init.hpp"
8 #include "../geometry/const.hpp"
9 #include "../model/Model.hpp"
10 #include "../world/Entity.hpp"
11 #include "../world/EntityState.hpp"
20 constexpr size_t Packet::Ping::MAX_LEN;
21 constexpr size_t Packet::Login::MAX_LEN;
22 constexpr size_t Packet::Join::MAX_LEN;
23 constexpr size_t Packet::Part::MAX_LEN;
24 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
25 constexpr size_t Packet::SpawnEntity::MAX_LEN;
26 constexpr size_t Packet::DespawnEntity::MAX_LEN;
27 constexpr size_t Packet::EntityUpdate::MAX_LEN;
28 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
29 constexpr size_t Packet::ChunkBegin::MAX_LEN;
30 constexpr size_t Packet::ChunkData::MAX_LEN;
31 constexpr size_t Packet::BlockUpdate::MAX_LEN;
32 constexpr size_t Packet::Message::MAX_LEN;
33 constexpr size_t Packet::Message::MAX_MESSAGE_LEN;
36 CongestionControl::CongestionControl()
37 // I know, I know, it's an estimate (about 20 for IPv4, 48 for IPv6)
39 // only sample every eighth packet for measuring RTT
53 // rtt > 100ms or packet loss > 5% is BAD
56 // rtt > 250ms or packet loss > 15% is UGLY
59 , mode_keep_time(1000) {
60 Uint32 now = SDL_GetTicks();
61 for (Uint32 &s : stamps) {
70 void CongestionControl::PacketSent(uint16_t seq) noexcept {
71 if (!SamplePacket(seq)) {
74 stamp_cursor = (stamp_cursor + 1) % 16;
75 stamps[stamp_cursor] = SDL_GetTicks();
79 void CongestionControl::PacketLost(uint16_t seq) noexcept {
85 void CongestionControl::PacketReceived(uint16_t seq) noexcept {
91 void CongestionControl::UpdatePacketLoss() noexcept {
92 unsigned int packets_total = packets_lost + packets_received;
93 if (packets_total >= 256) {
94 packet_loss = float(packets_lost) / float(packets_total);
100 void CongestionControl::UpdateRTT(std::uint16_t seq) noexcept {
101 if (!SamplePacket(seq)) return;
102 int16_t diff = int16_t(seq) - int16_t(stamp_last);
104 if (diff > 0 || diff < -15) {
105 // packet outside observed time frame
108 int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16];
109 rtt += (cur_rtt - rtt) * 0.1f;
112 bool CongestionControl::SamplePacket(std::uint16_t seq) const noexcept {
113 return seq % sample_skip == 0;
116 void CongestionControl::PacketIn(const UDPpacket &pack) noexcept {
117 rx_bytes += pack.len + packet_overhead;
121 void CongestionControl::PacketOut(const UDPpacket &pack) noexcept {
122 tx_bytes += pack.len + packet_overhead;
126 void CongestionControl::UpdateStats() noexcept {
127 Uint32 now = SDL_GetTicks();
128 if (now < next_sample) {
132 tx_kbps = float(tx_bytes) * (1.0f / 1024.0f);
133 rx_kbps = float(rx_bytes) * (1.0f / 1024.0f);
140 void CongestionControl::UpdateMode() noexcept {
141 Mode now_mode = Conditions();
142 if (now_mode > mode) {
143 ChangeMode(now_mode);
144 } else if (now_mode < mode) {
145 CheckUpgrade(now_mode);
151 void CongestionControl::CheckUpgrade(Mode m) noexcept {
152 Uint32 now = SDL_GetTicks();
153 Uint32 time_in_mode = now - mode_entered;
154 if (time_in_mode < mode_keep_time) {
160 void CongestionControl::ChangeMode(Mode m) noexcept {
161 Uint32 now = SDL_GetTicks();
163 // changed to worse mode
164 // if we spent less than 10 seconds in better mode
165 // double keep time till up to 64 seconds
166 if (now - mode_entered < 10000) {
167 if (mode_keep_time < 64000) {
174 mode_reset = mode_entered;
177 void CongestionControl::KeepMode() noexcept {
178 mode_reset = SDL_GetTicks();
179 // if in good mode for 10 seconds, halve keep time till down to one second
180 if (mode == GOOD && mode_keep_time > 1000 && mode_step - mode_reset > 10000) {
182 mode_step = mode_reset;
186 CongestionControl::Mode CongestionControl::Conditions() const noexcept {
187 if (rtt > ugly_rtt || packet_loss > ugly_loss) {
189 } else if (rtt > bad_rtt || packet_loss > bad_loss) {
197 Connection::Connection(const IPaddress &addr)
202 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
203 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
209 bool Connection::Matches(const IPaddress &remote) const noexcept {
210 return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
213 void Connection::FlagSend() noexcept {
217 void Connection::FlagRecv() noexcept {
221 bool Connection::ShouldPing() const noexcept {
222 return !closed && send_timer.HitOnce();
225 bool Connection::TimedOut() const noexcept {
226 return recv_timer.HitOnce();
229 void Connection::Update(int dt) {
230 send_timer.Update(dt);
231 recv_timer.Update(dt);
235 Handler().OnTimeout();
241 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
242 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
243 pack.header.ctrl = ctrl_out;
244 uint16_t seq = ctrl_out.seq++;
246 udp_pack.address = addr;
247 if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
248 throw NetError("SDLNet_UDP_Send");
252 Handler().PacketOut(udp_pack);
253 Handler().PacketSent(seq);
260 void Connection::Received(const UDPpacket &udp_pack) {
261 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
264 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
269 ctrl_out.hist <<= diff;
270 ctrl_out.hist |= 1 << (diff - 1);
272 } else if (diff < 0 && diff >= -32) {
273 ctrl_out.hist |= 1 << (-diff - 1);
275 ctrl_out.ack = pack.header.ctrl.seq;
282 Packet::TControl ctrl_new = pack.header.ctrl;
283 Handler().PacketIn(udp_pack);
284 Handler().Handle(udp_pack);
287 // if the packet holds more recent information
288 // check if remote failed to ack one of our packets
289 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
290 // should always be true, but you never know…
292 for (int i = 0; i < diff; ++i) {
293 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
294 Handler().PacketLost(ctrl_in.ack - 32 + i);
298 // check for newly ack'd packets
299 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
300 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
301 Handler().PacketReceived(s);
308 bool Packet::TControl::Acks(uint16_t s) const noexcept {
309 int16_t diff = int16_t(ack) - int16_t(s);
310 if (diff == 0) return true;
311 if (diff < 0 || diff > 32) return false;
312 return (hist & (1 << (diff - 1))) != 0;
315 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
316 Packet::Make<Packet::Ping>(udp_pack);
317 return Send(udp_pack, sock);
321 ConnectionHandler::ConnectionHandler()
326 void ConnectionHandler::PacketSent(uint16_t seq) noexcept {
330 void ConnectionHandler::PacketLost(uint16_t seq) {
335 void ConnectionHandler::PacketReceived(uint16_t seq) {
336 OnPacketReceived(seq);
337 cc.PacketReceived(seq);
340 void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept {
344 void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept {
349 ostream &operator <<(ostream &out, const IPaddress &addr) {
350 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
352 << '.' << int(host[1])
353 << '.' << int(host[2])
354 << '.' << int(host[3]);
356 out << ':' << SDLNet_Read16(&addr.port);
362 const char *Packet::Type2String(uint8_t t) noexcept {
372 case PlayerUpdate::TYPE:
373 return "PlayerUpdate";
374 case SpawnEntity::TYPE:
375 return "SpawnEntity";
376 case DespawnEntity::TYPE:
377 return "DespawnEntity";
378 case EntityUpdate::TYPE:
379 return "EntityUpdate";
380 case PlayerCorrection::TYPE:
381 return "PlayerCorrection";
382 case ChunkBegin::TYPE:
384 case ChunkData::TYPE:
386 case BlockUpdate::TYPE:
387 return "BlockUpdate";
396 void Packet::Payload::Write(const T &src, size_t off) noexcept {
397 if ((length - off) < sizeof(T)) {
398 // dismiss out of bounds write
401 *reinterpret_cast<T *>(&data[off]) = src;
405 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
406 if ((length - off) < sizeof(T)) {
407 // dismiss out of bounds read
410 dst = *reinterpret_cast<T *>(&data[off]);
413 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
414 uint8_t *dst = &data[off];
415 size_t len = min(maxlen, length - off);
416 if (src.size() < len) {
417 memset(dst, '\0', len);
418 memcpy(dst, src.c_str(), src.size());
420 memcpy(dst, src.c_str(), len);
424 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
425 size_t len = min(maxlen, length - off);
428 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
429 dst.push_back(data[off + i]);
433 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
434 WritePackN(val.w, off);
435 WritePackN(val.x, off + 2);
436 WritePackN(val.y, off + 4);
437 WritePackN(val.z, off + 6);
440 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
441 ReadPackN(val.w, off);
442 ReadPackN(val.x, off + 2);
443 ReadPackN(val.y, off + 4);
444 ReadPackN(val.z, off + 6);
445 val = normalize(val);
448 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
449 Write(state.pos.chunk, off);
450 WritePackU(state.pos.block * (1.0f / ExactLocation::fscale), off + 12);
451 Write(state.velocity, off + 18);
452 Write(state.orient, off + 30);
453 WritePackN(state.pitch * PI_0p5_inv, off + 38);
454 WritePackN(state.yaw * PI_inv, off + 40);
457 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
458 Read(state.pos.chunk, off);
459 ReadPackU(state.pos.block, off + 12);
460 Read(state.velocity, off + 18);
461 Read(state.orient, off + 30);
462 ReadPackN(state.pitch, off + 38);
463 ReadPackN(state.yaw, off + 40);
464 state.pos.block *= ExactLocation::fscale;
465 state.pitch *= PI_0p5;
469 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
470 WritePackB(state.pos.chunk - base, off);
471 WritePackU(state.pos.block * (1.0f / ExactLocation::fscale), off + 3);
472 Write(state.velocity, off + 9);
473 Write(state.orient, off + 21);
474 WritePackN(state.pitch * PI_0p5_inv, off + 29);
475 WritePackN(state.yaw * PI_inv, off + 31);
478 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
479 ReadPackB(state.pos.chunk, off);
480 ReadPackU(state.pos.block, off + 3);
481 Read(state.velocity, off + 9);
482 Read(state.orient, off + 21);
483 ReadPackN(state.pitch, off + 29);
484 ReadPackN(state.yaw, off + 31);
485 state.pos.chunk += base;
486 state.pos.block *= ExactLocation::fscale;
487 state.pitch *= PI_0p5;
491 void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept {
492 Write(int8_t(val.x), off);
493 Write(int8_t(val.y), off + 1);
494 Write(int8_t(val.z), off + 2);
497 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
507 void Packet::Payload::WritePackN(float val, size_t off) noexcept {
508 int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f);
512 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
515 val = raw * (1.0f/32767.0f);
518 void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept {
519 WritePackN(val.x, off);
520 WritePackN(val.y, off + 2);
521 WritePackN(val.z, off + 4);
524 void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept {
525 ReadPackN(val.x, off);
526 ReadPackN(val.y, off + 2);
527 ReadPackN(val.z, off + 4);
530 void Packet::Payload::WritePackU(float val, size_t off) noexcept {
531 uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f);
535 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
538 val = raw * (1.0f/65535.0f);
541 void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept {
542 WritePackU(val.x, off);
543 WritePackU(val.y, off + 2);
544 WritePackU(val.z, off + 4);
547 void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept {
548 ReadPackU(val.x, off);
549 ReadPackU(val.y, off + 2);
550 ReadPackU(val.z, off + 4);
554 void Packet::Login::WritePlayerName(const string &name) noexcept {
555 WriteString(name, 0, 32);
558 void Packet::Login::ReadPlayerName(string &name) const noexcept {
559 ReadString(name, 0, 32);
562 void Packet::Join::WritePlayer(const Entity &player) noexcept {
563 Write(player.ID(), 0);
564 Write(player.GetState(), 4);
567 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
571 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
575 void Packet::Join::WriteWorldName(const string &name) noexcept {
576 WriteString(name, 46, 32);
579 void Packet::Join::ReadWorldName(string &name) const noexcept {
580 ReadString(name, 46, 32);
583 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
587 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
591 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
595 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
599 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
603 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
607 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
611 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
615 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
618 Write(e.GetModel().GetModel().ID(), 4);
620 Write(uint32_t(0), 4);
622 Write(e.GetState(), 8);
623 Write(e.Bounds(), 50);
625 if (e.WorldCollidable()) {
629 WriteString(e.Name(), 78, 32);
632 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
636 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
640 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
649 ReadString(name, 78, 32);
653 e.WorldCollidable(flags & 1);
657 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
661 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
665 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
669 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
673 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
677 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
681 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
682 uint32_t off = GetSize(num);
684 Write(entity.ID(), off);
685 Write(entity.GetState(), base, off + 4);
688 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
689 uint32_t off = GetSize(num);
693 void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept {
694 uint32_t off = GetSize(num);
695 Read(state, base, off + 4);
698 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
702 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
706 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
707 Write(player.GetState(), 2);
710 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
714 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
718 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
722 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
726 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
730 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
734 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
738 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
742 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
746 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
750 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
754 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
758 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
762 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
766 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
770 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
771 size_t len = min(length - 12, l);
772 memcpy(&data[12], d, len);
775 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
776 size_t len = min(length - 12, l);
777 memcpy(d, &data[12], len);
780 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
784 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
788 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
792 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
796 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
797 uint32_t off = GetSize(num);
801 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
802 uint32_t off = GetSize(num);
806 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
807 uint32_t off = GetSize(num) + 2;
811 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
812 uint32_t off = GetSize(num) + 2;
816 void Packet::Message::WriteType(uint8_t type) noexcept {
820 void Packet::Message::ReadType(uint8_t &type) const noexcept {
824 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
828 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
832 void Packet::Message::WriteMessage(const string &msg) noexcept {
833 WriteString(msg, 5, MAX_MESSAGE_LEN);
836 void Packet::Message::ReadMessage(string &msg) const noexcept {
837 ReadString(msg, 5, MAX_MESSAGE_LEN);
841 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
842 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
843 switch (pack.Type()) {
844 case Packet::Ping::TYPE:
845 On(Packet::As<Packet::Ping>(udp_pack));
847 case Packet::Login::TYPE:
848 On(Packet::As<Packet::Login>(udp_pack));
850 case Packet::Join::TYPE:
851 On(Packet::As<Packet::Join>(udp_pack));
853 case Packet::Part::TYPE:
854 On(Packet::As<Packet::Part>(udp_pack));
856 case Packet::PlayerUpdate::TYPE:
857 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
859 case Packet::SpawnEntity::TYPE:
860 On(Packet::As<Packet::SpawnEntity>(udp_pack));
862 case Packet::DespawnEntity::TYPE:
863 On(Packet::As<Packet::DespawnEntity>(udp_pack));
865 case Packet::EntityUpdate::TYPE:
866 On(Packet::As<Packet::EntityUpdate>(udp_pack));
868 case Packet::PlayerCorrection::TYPE:
869 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
871 case Packet::ChunkBegin::TYPE:
872 On(Packet::As<Packet::ChunkBegin>(udp_pack));
874 case Packet::ChunkData::TYPE:
875 On(Packet::As<Packet::ChunkData>(udp_pack));
877 case Packet::BlockUpdate::TYPE:
878 On(Packet::As<Packet::BlockUpdate>(udp_pack));
880 case Packet::Message::TYPE:
881 On(Packet::As<Packet::Message>(udp_pack));
884 // drop unknown or unhandled packets