1 #include "Connection.hpp"
2 #include "ConnectionHandler.hpp"
6 #include "../app/init.hpp"
7 #include "../model/CompositeModel.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;
31 Connection::Connection(const IPaddress &addr)
36 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
37 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
43 bool Connection::Matches(const IPaddress &remote) const noexcept {
44 return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
47 void Connection::FlagSend() noexcept {
51 void Connection::FlagRecv() noexcept {
55 bool Connection::ShouldPing() const noexcept {
56 return !closed && send_timer.HitOnce();
59 bool Connection::TimedOut() const noexcept {
60 return recv_timer.HitOnce();
63 void Connection::Update(int dt) {
64 send_timer.Update(dt);
65 recv_timer.Update(dt);
69 Handler().OnTimeout();
75 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
76 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
77 pack.header.ctrl = ctrl_out;
78 uint16_t seq = ctrl_out.seq++;
80 udp_pack.address = addr;
81 if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
82 throw NetError("SDLNet_UDP_Send");
89 void Connection::Received(const UDPpacket &udp_pack) {
90 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
93 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
98 ctrl_out.hist <<= diff;
99 ctrl_out.hist |= 1 << (diff - 1);
101 } else if (diff < 0 && diff >= -32) {
102 ctrl_out.hist |= 1 << (-diff - 1);
104 ctrl_out.ack = pack.header.ctrl.seq;
111 Packet::TControl ctrl_new = pack.header.ctrl;
112 Handler().Handle(udp_pack);
115 // if the packet holds more recent information
116 // check if remote failed to ack one of our packets
117 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
118 // should always be true, but you never know…
120 for (int i = 0; i < diff; ++i) {
121 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
122 Handler().PacketLost(ctrl_in.ack - 32 + i);
126 // check for newly ack'd packets
127 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
128 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
129 Handler().PacketReceived(s);
136 bool Packet::TControl::Acks(uint16_t s) const noexcept {
137 int16_t diff = int16_t(ack) - int16_t(s);
138 if (diff == 0) return true;
139 if (diff < 0 || diff > 32) return false;
140 return (hist & (1 << (diff - 1))) != 0;
143 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
144 Packet::Make<Packet::Ping>(udp_pack);
145 return Send(udp_pack, sock);
149 ConnectionHandler::ConnectionHandler()
151 , packets_received(0)
152 , packet_loss(0.0f) {
156 void ConnectionHandler::PacketLost(uint16_t seq) {
162 void ConnectionHandler::PacketReceived(uint16_t seq) {
163 OnPacketReceived(seq);
168 void ConnectionHandler::UpdatePacketLoss() noexcept {
169 unsigned int packets_total = packets_lost + packets_received;
170 if (packets_total >= 256) {
171 packet_loss = float(packets_lost) / float(packets_total);
173 packets_received = 0;
178 ostream &operator <<(ostream &out, const IPaddress &addr) {
179 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
181 << '.' << int(host[1])
182 << '.' << int(host[2])
183 << '.' << int(host[3]);
185 out << ':' << SDLNet_Read16(&addr.port);
191 const char *Packet::Type2String(uint8_t t) noexcept {
201 case PlayerUpdate::TYPE:
202 return "PlayerUpdate";
203 case SpawnEntity::TYPE:
204 return "SpawnEntity";
205 case DespawnEntity::TYPE:
206 return "DespawnEntity";
207 case EntityUpdate::TYPE:
208 return "EntityUpdate";
209 case PlayerCorrection::TYPE:
210 return "PlayerCorrection";
211 case ChunkBegin::TYPE:
213 case ChunkData::TYPE:
215 case BlockUpdate::TYPE:
216 return "BlockUpdate";
223 void Packet::Payload::Write(const T &src, size_t off) noexcept {
224 if ((length - off) < sizeof(T)) {
225 // dismiss out of bounds write
228 *reinterpret_cast<T *>(&data[off]) = src;
232 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
233 if ((length - off) < sizeof(T)) {
234 // dismiss out of bounds read
237 dst = *reinterpret_cast<T *>(&data[off]);
240 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
241 uint8_t *dst = &data[off];
242 size_t len = min(maxlen, length - off);
243 if (src.size() < len) {
244 memset(dst, '\0', len);
245 memcpy(dst, src.c_str(), src.size());
247 memcpy(dst, src.c_str(), len);
251 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
252 size_t len = min(maxlen, length - off);
255 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
256 dst.push_back(data[off + i]);
261 void Packet::Login::WritePlayerName(const string &name) noexcept {
262 WriteString(name, 0, 32);
265 void Packet::Login::ReadPlayerName(string &name) const noexcept {
266 ReadString(name, 0, 32);
269 void Packet::Join::WritePlayer(const Entity &player) noexcept {
270 Write(player.ID(), 0);
271 Write(player.GetState(), 4);
274 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
278 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
282 void Packet::Join::WriteWorldName(const string &name) noexcept {
283 WriteString(name, 68, 32);
286 void Packet::Join::ReadWorldName(string &name) const noexcept {
287 ReadString(name, 68, 32);
290 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
294 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
298 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
299 glm::ivec3 conv = clamp(glm::ivec3(mov * 32767.0f), -32767, 32767);
300 Write(int16_t(conv.x), 64);
301 Write(int16_t(conv.y), 66);
302 Write(int16_t(conv.z), 68);
305 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
310 mov = glm::vec3(x, y, z) * .00003051850947599719f;
313 void Packet::PlayerUpdate::WritePitch(float pitch) noexcept {
314 int16_t conv = pitch * 20860.12008116853786870640f;
318 void Packet::PlayerUpdate::ReadPitch(float &pitch) const noexcept {
321 pitch = conv * .00004793836258415163f;
324 void Packet::PlayerUpdate::WriteYaw(float yaw) noexcept {
325 int16_t conv = yaw * 10430.06004058426893435320f;
329 void Packet::PlayerUpdate::ReadYaw(float &yaw) const noexcept {
332 yaw = conv * .00009587672516830326f;
335 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
339 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
343 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
347 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
351 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
354 Write(e.GetModel().GetModel().ID(), 4);
356 Write(uint32_t(0), 4);
358 Write(e.GetState(), 8);
359 Write(e.Bounds(), 72);
361 if (e.WorldCollidable()) {
365 WriteString(e.Name(), 100, 32);
368 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
372 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
376 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
385 ReadString(name, 100, 32);
389 e.WorldCollidable(flags & 1);
393 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
397 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
401 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
405 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
409 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
410 uint32_t off = GetSize(num);
412 Write(entity.ID(), off);
413 Write(entity.GetState(), off + 4);
416 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
417 uint32_t off = GetSize(num);
421 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
422 uint32_t off = GetSize(num);
423 Read(state, off + 4);
426 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
430 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
434 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
435 Write(player.GetState(), 2);
438 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
442 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
446 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
450 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
454 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
458 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
462 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
466 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
470 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
474 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
478 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
482 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
486 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
490 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
494 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
498 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
499 size_t len = min(length - 12, l);
500 memcpy(&data[12], d, len);
503 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
504 size_t len = min(length - 12, l);
505 memcpy(d, &data[12], len);
508 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
512 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
516 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
520 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
524 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
525 uint32_t off = GetSize(num);
529 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
530 uint32_t off = GetSize(num);
534 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
535 uint32_t off = GetSize(num) + 2;
539 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
540 uint32_t off = GetSize(num) + 2;
545 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
546 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
547 switch (pack.Type()) {
548 case Packet::Ping::TYPE:
549 On(Packet::As<Packet::Ping>(udp_pack));
551 case Packet::Login::TYPE:
552 On(Packet::As<Packet::Login>(udp_pack));
554 case Packet::Join::TYPE:
555 On(Packet::As<Packet::Join>(udp_pack));
557 case Packet::Part::TYPE:
558 On(Packet::As<Packet::Part>(udp_pack));
560 case Packet::PlayerUpdate::TYPE:
561 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
563 case Packet::SpawnEntity::TYPE:
564 On(Packet::As<Packet::SpawnEntity>(udp_pack));
566 case Packet::DespawnEntity::TYPE:
567 On(Packet::As<Packet::DespawnEntity>(udp_pack));
569 case Packet::EntityUpdate::TYPE:
570 On(Packet::As<Packet::EntityUpdate>(udp_pack));
572 case Packet::PlayerCorrection::TYPE:
573 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
575 case Packet::ChunkBegin::TYPE:
576 On(Packet::As<Packet::ChunkBegin>(udp_pack));
578 case Packet::ChunkData::TYPE:
579 On(Packet::As<Packet::ChunkData>(udp_pack));
581 case Packet::BlockUpdate::TYPE:
582 On(Packet::As<Packet::BlockUpdate>(udp_pack));
585 // drop unknown or unhandled packets