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");
88 Handler().PacketSent(seq);
95 void Connection::Received(const UDPpacket &udp_pack) {
96 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
99 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
104 ctrl_out.hist <<= diff;
105 ctrl_out.hist |= 1 << (diff - 1);
107 } else if (diff < 0 && diff >= -32) {
108 ctrl_out.hist |= 1 << (-diff - 1);
110 ctrl_out.ack = pack.header.ctrl.seq;
117 Packet::TControl ctrl_new = pack.header.ctrl;
118 Handler().Handle(udp_pack);
121 // if the packet holds more recent information
122 // check if remote failed to ack one of our packets
123 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
124 // should always be true, but you never know…
126 for (int i = 0; i < diff; ++i) {
127 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
128 Handler().PacketLost(ctrl_in.ack - 32 + i);
132 // check for newly ack'd packets
133 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
134 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
135 Handler().PacketReceived(s);
142 bool Packet::TControl::Acks(uint16_t s) const noexcept {
143 int16_t diff = int16_t(ack) - int16_t(s);
144 if (diff == 0) return true;
145 if (diff < 0 || diff > 32) return false;
146 return (hist & (1 << (diff - 1))) != 0;
149 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
150 Packet::Make<Packet::Ping>(udp_pack);
151 return Send(udp_pack, sock);
155 ConnectionHandler::ConnectionHandler()
157 , packets_received(0)
162 Uint32 now = SDL_GetTicks();
163 for (Uint32 &s : stamps) {
168 void ConnectionHandler::PacketSent(uint16_t seq) {
169 if (!SamplePacket(seq)) {
172 stamp_cursor = (stamp_cursor + 1) % 16;
173 stamps[stamp_cursor] = SDL_GetTicks();
177 void ConnectionHandler::PacketLost(uint16_t seq) {
184 void ConnectionHandler::PacketReceived(uint16_t seq) {
185 OnPacketReceived(seq);
191 void ConnectionHandler::UpdatePacketLoss() noexcept {
192 unsigned int packets_total = packets_lost + packets_received;
193 if (packets_total >= 256) {
194 packet_loss = float(packets_lost) / float(packets_total);
196 packets_received = 0;
200 void ConnectionHandler::UpdateRTT(std::uint16_t seq) noexcept {
201 if (!SamplePacket(seq)) return;
202 int diff = HeadDiff(seq);
203 if (diff > 0 || diff < -15) {
204 // packet outside observed time frame
207 int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16];
208 rtt += (cur_rtt - rtt) * 0.1f;
211 bool ConnectionHandler::SamplePacket(std::uint16_t seq) const noexcept {
212 // only sample every eighth packet
216 int ConnectionHandler::HeadDiff(std::uint16_t seq) const noexcept {
217 int16_t diff = int16_t(seq) - int16_t(stamp_last);
222 ostream &operator <<(ostream &out, const IPaddress &addr) {
223 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
225 << '.' << int(host[1])
226 << '.' << int(host[2])
227 << '.' << int(host[3]);
229 out << ':' << SDLNet_Read16(&addr.port);
235 const char *Packet::Type2String(uint8_t t) noexcept {
245 case PlayerUpdate::TYPE:
246 return "PlayerUpdate";
247 case SpawnEntity::TYPE:
248 return "SpawnEntity";
249 case DespawnEntity::TYPE:
250 return "DespawnEntity";
251 case EntityUpdate::TYPE:
252 return "EntityUpdate";
253 case PlayerCorrection::TYPE:
254 return "PlayerCorrection";
255 case ChunkBegin::TYPE:
257 case ChunkData::TYPE:
259 case BlockUpdate::TYPE:
260 return "BlockUpdate";
269 void Packet::Payload::Write(const T &src, size_t off) noexcept {
270 if ((length - off) < sizeof(T)) {
271 // dismiss out of bounds write
274 *reinterpret_cast<T *>(&data[off]) = src;
278 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
279 if ((length - off) < sizeof(T)) {
280 // dismiss out of bounds read
283 dst = *reinterpret_cast<T *>(&data[off]);
286 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
287 uint8_t *dst = &data[off];
288 size_t len = min(maxlen, length - off);
289 if (src.size() < len) {
290 memset(dst, '\0', len);
291 memcpy(dst, src.c_str(), src.size());
293 memcpy(dst, src.c_str(), len);
297 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
298 size_t len = min(maxlen, length - off);
301 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
302 dst.push_back(data[off + i]);
306 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
307 WritePackN(val.w, off);
308 WritePackN(val.x, off + 2);
309 WritePackN(val.y, off + 4);
310 WritePackN(val.z, off + 6);
313 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
314 ReadPackN(val.w, off);
315 ReadPackN(val.x, off + 2);
316 ReadPackN(val.y, off + 4);
317 ReadPackN(val.z, off + 6);
318 val = normalize(val);
321 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
322 Write(state.chunk_pos, off);
323 WritePackU(state.block_pos * (1.0f / 16.0f), off + 12);
324 Write(state.velocity, off + 18);
325 Write(state.orient, off + 30);
326 WritePackN(state.pitch * PI_0p5_inv, off + 38);
327 WritePackN(state.yaw * PI_inv, off + 40);
330 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
331 Read(state.chunk_pos, off);
332 ReadPackU(state.block_pos, off + 12);
333 Read(state.velocity, off + 18);
334 Read(state.orient, off + 30);
335 ReadPackN(state.pitch, off + 38);
336 ReadPackN(state.yaw, off + 40);
337 state.block_pos *= 16.0f;
338 state.pitch *= PI_0p5;
342 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
343 WritePackB(state.chunk_pos - base, off);
344 WritePackU(state.block_pos * (1.0f / 16.0f), off + 3);
345 Write(state.velocity, off + 9);
346 Write(state.orient, off + 21);
347 WritePackN(state.pitch * PI_0p5_inv, off + 29);
348 WritePackN(state.yaw * PI_inv, off + 31);
351 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
352 ReadPackB(state.chunk_pos, off);
353 ReadPackU(state.block_pos, off + 3);
354 Read(state.velocity, off + 9);
355 Read(state.orient, off + 21);
356 ReadPackN(state.pitch, off + 29);
357 ReadPackN(state.yaw, off + 31);
358 state.chunk_pos += base;
359 state.block_pos *= 16.0f;
360 state.pitch *= PI_0p5;
364 void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept {
365 Write(int8_t(val.x), off);
366 Write(int8_t(val.y), off + 1);
367 Write(int8_t(val.z), off + 2);
370 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
380 void Packet::Payload::WritePackN(float val, size_t off) noexcept {
381 int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f);
385 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
388 val = raw * (1.0f/32767.0f);
391 void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept {
392 WritePackN(val.x, off);
393 WritePackN(val.y, off + 2);
394 WritePackN(val.z, off + 4);
397 void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept {
398 ReadPackN(val.x, off);
399 ReadPackN(val.y, off + 2);
400 ReadPackN(val.z, off + 4);
403 void Packet::Payload::WritePackU(float val, size_t off) noexcept {
404 uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f);
408 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
411 val = raw * (1.0f/65535.0f);
414 void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept {
415 WritePackU(val.x, off);
416 WritePackU(val.y, off + 2);
417 WritePackU(val.z, off + 4);
420 void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept {
421 ReadPackU(val.x, off);
422 ReadPackU(val.y, off + 2);
423 ReadPackU(val.z, off + 4);
427 void Packet::Login::WritePlayerName(const string &name) noexcept {
428 WriteString(name, 0, 32);
431 void Packet::Login::ReadPlayerName(string &name) const noexcept {
432 ReadString(name, 0, 32);
435 void Packet::Join::WritePlayer(const Entity &player) noexcept {
436 Write(player.ID(), 0);
437 Write(player.GetState(), 4);
440 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
444 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
448 void Packet::Join::WriteWorldName(const string &name) noexcept {
449 WriteString(name, 46, 32);
452 void Packet::Join::ReadWorldName(string &name) const noexcept {
453 ReadString(name, 46, 32);
456 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
460 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
464 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
468 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
472 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
476 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
480 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
484 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
488 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
491 Write(e.GetModel().GetModel().ID(), 4);
493 Write(uint32_t(0), 4);
495 Write(e.GetState(), 8);
496 Write(e.Bounds(), 50);
498 if (e.WorldCollidable()) {
502 WriteString(e.Name(), 78, 32);
505 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
509 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
513 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
522 ReadString(name, 78, 32);
526 e.WorldCollidable(flags & 1);
530 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
534 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
538 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
542 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
546 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
550 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
554 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
555 uint32_t off = GetSize(num);
557 Write(entity.ID(), off);
558 Write(entity.GetState(), base, off + 4);
561 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
562 uint32_t off = GetSize(num);
566 void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept {
567 uint32_t off = GetSize(num);
568 Read(state, base, off + 4);
571 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
575 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
579 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
580 Write(player.GetState(), 2);
583 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
587 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
591 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
595 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
599 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
603 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
607 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
611 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
615 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
619 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
623 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
627 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
631 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
635 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
639 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
643 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
644 size_t len = min(length - 12, l);
645 memcpy(&data[12], d, len);
648 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
649 size_t len = min(length - 12, l);
650 memcpy(d, &data[12], len);
653 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
657 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
661 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
665 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
669 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
670 uint32_t off = GetSize(num);
674 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
675 uint32_t off = GetSize(num);
679 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
680 uint32_t off = GetSize(num) + 2;
684 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
685 uint32_t off = GetSize(num) + 2;
689 void Packet::Message::WriteType(uint8_t type) noexcept {
693 void Packet::Message::ReadType(uint8_t &type) const noexcept {
697 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
701 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
705 void Packet::Message::WriteMessage(const string &msg) noexcept {
706 WriteString(msg, 5, MAX_MESSAGE_LEN);
709 void Packet::Message::ReadMessage(string &msg) const noexcept {
710 ReadString(msg, 5, MAX_MESSAGE_LEN);
714 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
715 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
716 switch (pack.Type()) {
717 case Packet::Ping::TYPE:
718 On(Packet::As<Packet::Ping>(udp_pack));
720 case Packet::Login::TYPE:
721 On(Packet::As<Packet::Login>(udp_pack));
723 case Packet::Join::TYPE:
724 On(Packet::As<Packet::Join>(udp_pack));
726 case Packet::Part::TYPE:
727 On(Packet::As<Packet::Part>(udp_pack));
729 case Packet::PlayerUpdate::TYPE:
730 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
732 case Packet::SpawnEntity::TYPE:
733 On(Packet::As<Packet::SpawnEntity>(udp_pack));
735 case Packet::DespawnEntity::TYPE:
736 On(Packet::As<Packet::DespawnEntity>(udp_pack));
738 case Packet::EntityUpdate::TYPE:
739 On(Packet::As<Packet::EntityUpdate>(udp_pack));
741 case Packet::PlayerCorrection::TYPE:
742 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
744 case Packet::ChunkBegin::TYPE:
745 On(Packet::As<Packet::ChunkBegin>(udp_pack));
747 case Packet::ChunkData::TYPE:
748 On(Packet::As<Packet::ChunkData>(udp_pack));
750 case Packet::BlockUpdate::TYPE:
751 On(Packet::As<Packet::BlockUpdate>(udp_pack));
753 case Packet::Message::TYPE:
754 On(Packet::As<Packet::Message>(udp_pack));
757 // drop unknown or unhandled packets