]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
rate network conditions
[blank.git] / src / net / net.cpp
1 #include "CongestionControl.hpp"
2 #include "Connection.hpp"
3 #include "ConnectionHandler.hpp"
4 #include "io.hpp"
5 #include "Packet.hpp"
6
7 #include "../app/init.hpp"
8 #include "../model/Model.hpp"
9 #include "../world/Entity.hpp"
10 #include "../world/EntityState.hpp"
11
12 #include <cstring>
13
14 using namespace std;
15
16
17 namespace blank {
18
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;
33
34
35 CongestionControl::CongestionControl()
36 // I know, I know, it's an estimate (about 20 for IPv4, 48 for IPv6)
37 : packet_overhead(20)
38 // only sample every eighth packet for measuring RTT
39 , sample_skip(8)
40 , packets_lost(0)
41 , packets_received(0)
42 , packet_loss(0.0f)
43 , stamp_cursor(15)
44 , stamp_last(0)
45 , rtt(64.0f)
46 , next_sample(1000)
47 , tx_bytes(0)
48 , rx_bytes(0)
49 , tx_kbps(0.0f)
50 , rx_kbps(0.0f)
51 , mode(GOOD)
52 // rtt > 100ms or packet loss > 5% is BAD
53 , bad_rtt(100.0f)
54 , bad_loss(0.05f)
55 // rtt > 250ms or packet loss > 15% is UGLY
56 , ugly_rtt(250.0f)
57 , ugly_loss(0.15f)
58 , mode_keep_time(1000) {
59         Uint32 now = SDL_GetTicks();
60         for (Uint32 &s : stamps) {
61                 s = now;
62         }
63         next_sample += now;
64         mode_entered = now;
65         mode_reset = now;
66         mode_step = now;
67 }
68
69 void CongestionControl::PacketSent(uint16_t seq) noexcept {
70         if (!SamplePacket(seq)) {
71                 return;
72         }
73         stamp_cursor = (stamp_cursor + 1) % 16;
74         stamps[stamp_cursor] = SDL_GetTicks();
75         stamp_last = seq;
76 }
77
78 void CongestionControl::PacketLost(uint16_t seq) noexcept {
79         ++packets_lost;
80         UpdatePacketLoss();
81         UpdateRTT(seq);
82 }
83
84 void CongestionControl::PacketReceived(uint16_t seq) noexcept {
85         ++packets_received;
86         UpdatePacketLoss();
87         UpdateRTT(seq);
88 }
89
90 void CongestionControl::UpdatePacketLoss() noexcept {
91         unsigned int packets_total = packets_lost + packets_received;
92         if (packets_total >= 256) {
93                 packet_loss = float(packets_lost) / float(packets_total);
94                 packets_lost = 0;
95                 packets_received = 0;
96         }
97 }
98
99 void CongestionControl::UpdateRTT(std::uint16_t seq) noexcept {
100         if (!SamplePacket(seq)) return;
101         int16_t diff = int16_t(seq) - int16_t(stamp_last);
102         diff /= sample_skip;
103         if (diff > 0 || diff < -15) {
104                 // packet outside observed time frame
105                 return;
106         }
107         int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16];
108         rtt += (cur_rtt - rtt) * 0.1f;
109 }
110
111 bool CongestionControl::SamplePacket(std::uint16_t seq) const noexcept {
112         return seq % sample_skip == 0;
113 }
114
115 void CongestionControl::PacketIn(const UDPpacket &pack) noexcept {
116         rx_bytes += pack.len + packet_overhead;
117         UpdateStats();
118 }
119
120 void CongestionControl::PacketOut(const UDPpacket &pack) noexcept {
121         tx_bytes += pack.len + packet_overhead;
122         UpdateStats();
123 }
124
125 void CongestionControl::UpdateStats() noexcept {
126         Uint32 now = SDL_GetTicks();
127         if (now < next_sample) {
128                 // not yet
129                 return;
130         }
131         tx_kbps = float(tx_bytes) * (1.0f / 1024.0f);
132         rx_kbps = float(rx_bytes) * (1.0f / 1024.0f);
133         tx_bytes = 0;
134         rx_bytes = 0;
135         next_sample += 1000;
136         UpdateMode();
137 }
138
139 void CongestionControl::UpdateMode() noexcept {
140         Mode now_mode = Conditions();
141         if (now_mode > mode) {
142                 ChangeMode(now_mode);
143         } else if (now_mode < mode) {
144                 CheckUpgrade(now_mode);
145         } else {
146                 KeepMode();
147         }
148 }
149
150 void CongestionControl::CheckUpgrade(Mode m) noexcept {
151         Uint32 now = SDL_GetTicks();
152         Uint32 time_in_mode = now - mode_entered;
153         if (time_in_mode < mode_keep_time) {
154                 return;
155         }
156         ChangeMode(m);
157 }
158
159 void CongestionControl::ChangeMode(Mode m) noexcept {
160         Uint32 now = SDL_GetTicks();
161         if (m > mode) {
162                 // changed to worse mode
163                 // if we spent less than 10 seconds in better mode
164                 // double keep time till up to 64 seconds
165                 if (now - mode_entered < 10000) {
166                         if (mode_keep_time < 64000) {
167                                 mode_keep_time *= 2;
168                         }
169                 }
170         }
171         mode = m;
172         mode_entered = now;
173         mode_reset = mode_entered;
174 }
175
176 void CongestionControl::KeepMode() noexcept {
177         mode_reset = SDL_GetTicks();
178         // if in good mode for 10 seconds, halve keep time till down to one second
179         if (mode == GOOD && mode_keep_time > 1000 && mode_step - mode_reset > 10000) {
180                 mode_keep_time /= 2;
181                 mode_step = mode_reset;
182         }
183 }
184
185 CongestionControl::Mode CongestionControl::Conditions() const noexcept {
186         if (rtt > ugly_rtt || packet_loss > ugly_loss) {
187                 return UGLY;
188         } else if (rtt > bad_rtt || packet_loss > bad_loss) {
189                 return BAD;
190         } else {
191                 return GOOD;
192         }
193 }
194
195
196 Connection::Connection(const IPaddress &addr)
197 : handler(nullptr)
198 , addr(addr)
199 , send_timer(500)
200 , recv_timer(10000)
201 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
202 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
203 , closed(false) {
204         send_timer.Start();
205         recv_timer.Start();
206 }
207
208 bool Connection::Matches(const IPaddress &remote) const noexcept {
209         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
210 }
211
212 void Connection::FlagSend() noexcept {
213         send_timer.Reset();
214 }
215
216 void Connection::FlagRecv() noexcept {
217         recv_timer.Reset();
218 }
219
220 bool Connection::ShouldPing() const noexcept {
221         return !closed && send_timer.HitOnce();
222 }
223
224 bool Connection::TimedOut() const noexcept {
225         return recv_timer.HitOnce();
226 }
227
228 void Connection::Update(int dt) {
229         send_timer.Update(dt);
230         recv_timer.Update(dt);
231         if (TimedOut()) {
232                 Close();
233                 if (HasHandler()) {
234                         Handler().OnTimeout();
235                 }
236         }
237 }
238
239
240 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
241         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
242         pack.header.ctrl = ctrl_out;
243         uint16_t seq = ctrl_out.seq++;
244
245         udp_pack.address = addr;
246         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
247                 throw NetError("SDLNet_UDP_Send");
248         }
249
250         if (HasHandler()) {
251                 Handler().PacketOut(udp_pack);
252                 Handler().PacketSent(seq);
253         }
254
255         FlagSend();
256         return seq;
257 }
258
259 void Connection::Received(const UDPpacket &udp_pack) {
260         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
261
262         // ack to the remote
263         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
264         if (diff > 0) {
265                 if (diff >= 32) {
266                         ctrl_out.hist = 0;
267                 } else {
268                         ctrl_out.hist <<= diff;
269                         ctrl_out.hist |= 1 << (diff - 1);
270                 }
271         } else if (diff < 0 && diff >= -32) {
272                 ctrl_out.hist |= 1 << (-diff - 1);
273         }
274         ctrl_out.ack = pack.header.ctrl.seq;
275         FlagRecv();
276
277         if (!HasHandler()) {
278                 return;
279         }
280
281         Packet::TControl ctrl_new = pack.header.ctrl;
282         Handler().PacketIn(udp_pack);
283         Handler().Handle(udp_pack);
284
285         if (diff > 0) {
286                 // if the packet holds more recent information
287                 // check if remote failed to ack one of our packets
288                 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
289                 // should always be true, but you never know…
290                 if (diff > 0) {
291                         for (int i = 0; i < diff; ++i) {
292                                 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
293                                         Handler().PacketLost(ctrl_in.ack - 32 + i);
294                                 }
295                         }
296                 }
297                 // check for newly ack'd packets
298                 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
299                         if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
300                                 Handler().PacketReceived(s);
301                         }
302                 }
303                 ctrl_in = ctrl_new;
304         }
305 }
306
307 bool Packet::TControl::Acks(uint16_t s) const noexcept {
308         int16_t diff = int16_t(ack) - int16_t(s);
309         if (diff == 0) return true;
310         if (diff < 0 || diff > 32) return false;
311         return (hist & (1 << (diff - 1))) != 0;
312 }
313
314 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
315         Packet::Make<Packet::Ping>(udp_pack);
316         return Send(udp_pack, sock);
317 }
318
319
320 ConnectionHandler::ConnectionHandler()
321 : cc() {
322
323 }
324
325 void ConnectionHandler::PacketSent(uint16_t seq) noexcept {
326         cc.PacketSent(seq);
327 }
328
329 void ConnectionHandler::PacketLost(uint16_t seq) {
330         OnPacketLost(seq);
331         cc.PacketLost(seq);
332 }
333
334 void ConnectionHandler::PacketReceived(uint16_t seq) {
335         OnPacketReceived(seq);
336         cc.PacketReceived(seq);
337 }
338
339 void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept {
340         cc.PacketIn(pack);
341 }
342
343 void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept {
344         cc.PacketOut(pack);
345 }
346
347
348 ostream &operator <<(ostream &out, const IPaddress &addr) {
349         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
350         out << int(host[0])
351                 << '.' << int(host[1])
352                 << '.' << int(host[2])
353                 << '.' << int(host[3]);
354         if (addr.port) {
355                 out << ':' << SDLNet_Read16(&addr.port);
356         }
357         return out;
358 }
359
360
361 const char *Packet::Type2String(uint8_t t) noexcept {
362         switch (t) {
363                 case Ping::TYPE:
364                         return "Ping";
365                 case Login::TYPE:
366                         return "Login";
367                 case Join::TYPE:
368                         return "Join";
369                 case Part::TYPE:
370                         return "Part";
371                 case PlayerUpdate::TYPE:
372                         return "PlayerUpdate";
373                 case SpawnEntity::TYPE:
374                         return "SpawnEntity";
375                 case DespawnEntity::TYPE:
376                         return "DespawnEntity";
377                 case EntityUpdate::TYPE:
378                         return "EntityUpdate";
379                 case PlayerCorrection::TYPE:
380                         return "PlayerCorrection";
381                 case ChunkBegin::TYPE:
382                         return "ChunkBegin";
383                 case ChunkData::TYPE:
384                         return "ChunkData";
385                 case BlockUpdate::TYPE:
386                         return "BlockUpdate";
387                 case Message::TYPE:
388                         return "Message";
389                 default:
390                         return "Unknown";
391         }
392 }
393
394 template<class T>
395 void Packet::Payload::Write(const T &src, size_t off) noexcept {
396         if ((length - off) < sizeof(T)) {
397                 // dismiss out of bounds write
398                 return;
399         }
400         *reinterpret_cast<T *>(&data[off]) = src;
401 }
402
403 template<class T>
404 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
405         if ((length - off) < sizeof(T)) {
406                 // dismiss out of bounds read
407                 return;
408         }
409         dst = *reinterpret_cast<T *>(&data[off]);
410 }
411
412 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
413         uint8_t *dst = &data[off];
414         size_t len = min(maxlen, length - off);
415         if (src.size() < len) {
416                 memset(dst, '\0', len);
417                 memcpy(dst, src.c_str(), src.size());
418         } else {
419                 memcpy(dst, src.c_str(), len);
420         }
421 }
422
423 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
424         size_t len = min(maxlen, length - off);
425         dst.clear();
426         dst.reserve(len);
427         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
428                 dst.push_back(data[off + i]);
429         }
430 }
431
432 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
433         WritePackN(val.w, off);
434         WritePackN(val.x, off + 2);
435         WritePackN(val.y, off + 4);
436         WritePackN(val.z, off + 6);
437 }
438
439 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
440         ReadPackN(val.w, off);
441         ReadPackN(val.x, off + 2);
442         ReadPackN(val.y, off + 4);
443         ReadPackN(val.z, off + 6);
444         val = normalize(val);
445 }
446
447 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
448         Write(state.chunk_pos, off);
449         WritePackU(state.block_pos * (1.0f / 16.0f), off + 12);
450         Write(state.velocity, off + 18);
451         Write(state.orient, off + 30);
452         WritePackN(state.pitch * PI_0p5_inv, off + 38);
453         WritePackN(state.yaw * PI_inv, off + 40);
454 }
455
456 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
457         Read(state.chunk_pos, off);
458         ReadPackU(state.block_pos, off + 12);
459         Read(state.velocity, off + 18);
460         Read(state.orient, off + 30);
461         ReadPackN(state.pitch, off + 38);
462         ReadPackN(state.yaw, off + 40);
463         state.block_pos *= 16.0f;
464         state.pitch *= PI_0p5;
465         state.yaw *= PI;
466 }
467
468 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
469         WritePackB(state.chunk_pos - base, off);
470         WritePackU(state.block_pos * (1.0f / 16.0f), off + 3);
471         Write(state.velocity, off + 9);
472         Write(state.orient, off + 21);
473         WritePackN(state.pitch * PI_0p5_inv, off + 29);
474         WritePackN(state.yaw * PI_inv, off + 31);
475 }
476
477 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
478         ReadPackB(state.chunk_pos, off);
479         ReadPackU(state.block_pos, off + 3);
480         Read(state.velocity, off + 9);
481         Read(state.orient, off + 21);
482         ReadPackN(state.pitch, off + 29);
483         ReadPackN(state.yaw, off + 31);
484         state.chunk_pos += base;
485         state.block_pos *= 16.0f;
486         state.pitch *= PI_0p5;
487         state.yaw *= PI;
488 }
489
490 void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept {
491         Write(int8_t(val.x), off);
492         Write(int8_t(val.y), off + 1);
493         Write(int8_t(val.z), off + 2);
494 }
495
496 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
497         int8_t conv = 0;
498         Read(conv, off);
499         val.x = conv;
500         Read(conv, off + 1);
501         val.y = conv;
502         Read(conv, off + 2);
503         val.z = conv;
504 }
505
506 void Packet::Payload::WritePackN(float val, size_t off) noexcept {
507         int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f);
508         Write(raw, off);
509 }
510
511 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
512         int16_t raw = 0;
513         Read(raw, off);
514         val = raw * (1.0f/32767.0f);
515 }
516
517 void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept {
518         WritePackN(val.x, off);
519         WritePackN(val.y, off + 2);
520         WritePackN(val.z, off + 4);
521 }
522
523 void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept {
524         ReadPackN(val.x, off);
525         ReadPackN(val.y, off + 2);
526         ReadPackN(val.z, off + 4);
527 }
528
529 void Packet::Payload::WritePackU(float val, size_t off) noexcept {
530         uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f);
531         Write(raw, off);
532 }
533
534 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
535         uint16_t raw = 0;
536         Read(raw, off);
537         val = raw * (1.0f/65535.0f);
538 }
539
540 void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept {
541         WritePackU(val.x, off);
542         WritePackU(val.y, off + 2);
543         WritePackU(val.z, off + 4);
544 }
545
546 void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept {
547         ReadPackU(val.x, off);
548         ReadPackU(val.y, off + 2);
549         ReadPackU(val.z, off + 4);
550 }
551
552
553 void Packet::Login::WritePlayerName(const string &name) noexcept {
554         WriteString(name, 0, 32);
555 }
556
557 void Packet::Login::ReadPlayerName(string &name) const noexcept {
558         ReadString(name, 0, 32);
559 }
560
561 void Packet::Join::WritePlayer(const Entity &player) noexcept {
562         Write(player.ID(), 0);
563         Write(player.GetState(), 4);
564 }
565
566 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
567         Read(id, 0);
568 }
569
570 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
571         Read(state, 4);
572 }
573
574 void Packet::Join::WriteWorldName(const string &name) noexcept {
575         WriteString(name, 46, 32);
576 }
577
578 void Packet::Join::ReadWorldName(string &name) const noexcept {
579         ReadString(name, 46, 32);
580 }
581
582 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
583         Write(state, 0);
584 }
585
586 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
587         Read(state, 0);
588 }
589
590 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
591         WritePackN(mov, 42);
592 }
593
594 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
595         ReadPackN(mov, 42);
596 }
597
598 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
599         Write(actions, 48);
600 }
601
602 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
603         Read(actions, 48);
604 }
605
606 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
607         Write(slot, 49);
608 }
609
610 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
611         Read(slot, 49);
612 }
613
614 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
615         Write(e.ID(), 0);
616         if (e.GetModel()) {
617                 Write(e.GetModel().GetModel().ID(), 4);
618         } else {
619                 Write(uint32_t(0), 4);
620         }
621         Write(e.GetState(), 8);
622         Write(e.Bounds(), 50);
623         uint32_t flags = 0;
624         if (e.WorldCollidable()) {
625                 flags |= 1;
626         }
627         Write(flags, 74);
628         WriteString(e.Name(), 78, 32);
629 }
630
631 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
632         Read(id, 0);
633 }
634
635 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
636         Read(id, 4);
637 }
638
639 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
640         EntityState state;
641         AABB bounds;
642         uint32_t flags = 0;
643         string name;
644
645         Read(state, 8);
646         Read(bounds, 50);
647         Read(flags, 74);
648         ReadString(name, 78, 32);
649
650         e.SetState(state);
651         e.Bounds(bounds);
652         e.WorldCollidable(flags & 1);
653         e.Name(name);
654 }
655
656 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
657         Write(id, 0);
658 }
659
660 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
661         Read(id, 0);
662 }
663
664 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
665         Write(count, 0);
666 }
667
668 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
669         Read(count, 0);
670 }
671
672 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
673         Write(base, 4);
674 }
675
676 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
677         Read(base, 4);
678 }
679
680 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
681         uint32_t off = GetSize(num);
682
683         Write(entity.ID(), off);
684         Write(entity.GetState(), base, off + 4);
685 }
686
687 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
688         uint32_t off = GetSize(num);
689         Read(id, off);
690 }
691
692 void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept {
693         uint32_t off = GetSize(num);
694         Read(state, base, off + 4);
695 }
696
697 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
698         Write(s, 0);
699 }
700
701 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
702         Read(s, 0);
703 }
704
705 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
706         Write(player.GetState(), 2);
707 }
708
709 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
710         Read(state, 2);
711 }
712
713 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
714         Write(id, 0);
715 }
716
717 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
718         Read(id, 0);
719 }
720
721 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
722         Write(f, 4);
723 }
724
725 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
726         Read(f, 4);
727 }
728
729 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
730         Write(pos, 8);
731 }
732
733 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
734         Read(pos, 8);
735 }
736
737 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
738         Write(s, 20);
739 }
740
741 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
742         Read(s, 20);
743 }
744
745 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
746         Write(id, 0);
747 }
748
749 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
750         Read(id, 0);
751 }
752
753 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
754         Write(o, 4);
755 }
756
757 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
758         Read(o, 4);
759 }
760
761 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
762         Write(s, 8);
763 }
764
765 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
766         Read(s, 8);
767 }
768
769 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
770         size_t len = min(length - 12, l);
771         memcpy(&data[12], d, len);
772 }
773
774 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
775         size_t len = min(length - 12, l);
776         memcpy(d, &data[12], len);
777 }
778
779 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
780         Write(coords, 0);
781 }
782
783 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
784         Read(coords, 0);
785 }
786
787 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
788         Write(count, 12);
789 }
790
791 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
792         Read(count, 12);
793 }
794
795 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
796         uint32_t off = GetSize(num);
797         Write(index, off);
798 }
799
800 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
801         uint32_t off = GetSize(num);
802         Read(index, off);
803 }
804
805 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
806         uint32_t off = GetSize(num) + 2;
807         Write(block, off);
808 }
809
810 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
811         uint32_t off = GetSize(num) + 2;
812         Read(block, off);
813 }
814
815 void Packet::Message::WriteType(uint8_t type) noexcept {
816         Write(type, 0);
817 }
818
819 void Packet::Message::ReadType(uint8_t &type) const noexcept {
820         Read(type, 0);
821 }
822
823 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
824         Write(ref, 1);
825 }
826
827 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
828         Read(ref, 1);
829 }
830
831 void Packet::Message::WriteMessage(const string &msg) noexcept {
832         WriteString(msg, 5, MAX_MESSAGE_LEN);
833 }
834
835 void Packet::Message::ReadMessage(string &msg) const noexcept {
836         ReadString(msg, 5, MAX_MESSAGE_LEN);
837 }
838
839
840 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
841         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
842         switch (pack.Type()) {
843                 case Packet::Ping::TYPE:
844                         On(Packet::As<Packet::Ping>(udp_pack));
845                         break;
846                 case Packet::Login::TYPE:
847                         On(Packet::As<Packet::Login>(udp_pack));
848                         break;
849                 case Packet::Join::TYPE:
850                         On(Packet::As<Packet::Join>(udp_pack));
851                         break;
852                 case Packet::Part::TYPE:
853                         On(Packet::As<Packet::Part>(udp_pack));
854                         break;
855                 case Packet::PlayerUpdate::TYPE:
856                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
857                         break;
858                 case Packet::SpawnEntity::TYPE:
859                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
860                         break;
861                 case Packet::DespawnEntity::TYPE:
862                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
863                         break;
864                 case Packet::EntityUpdate::TYPE:
865                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
866                         break;
867                 case Packet::PlayerCorrection::TYPE:
868                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
869                         break;
870                 case Packet::ChunkBegin::TYPE:
871                         On(Packet::As<Packet::ChunkBegin>(udp_pack));
872                         break;
873                 case Packet::ChunkData::TYPE:
874                         On(Packet::As<Packet::ChunkData>(udp_pack));
875                         break;
876                 case Packet::BlockUpdate::TYPE:
877                         On(Packet::As<Packet::BlockUpdate>(udp_pack));
878                         break;
879                 case Packet::Message::TYPE:
880                         On(Packet::As<Packet::Message>(udp_pack));
881                         break;
882                 default:
883                         // drop unknown or unhandled packets
884                         break;
885         }
886 }
887
888 }