]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
4de800e2429eb4c1c65e4a87ef0ec17567692058
[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         Uint32 now = SDL_GetTicks();
52         for (Uint32 &s : stamps) {
53                 s = now;
54         }
55         next_sample += now;
56 }
57
58 void CongestionControl::PacketSent(uint16_t seq) noexcept {
59         if (!SamplePacket(seq)) {
60                 return;
61         }
62         stamp_cursor = (stamp_cursor + 1) % 16;
63         stamps[stamp_cursor] = SDL_GetTicks();
64         stamp_last = seq;
65 }
66
67 void CongestionControl::PacketLost(uint16_t seq) noexcept {
68         ++packets_lost;
69         UpdatePacketLoss();
70         UpdateRTT(seq);
71 }
72
73 void CongestionControl::PacketReceived(uint16_t seq) noexcept {
74         ++packets_received;
75         UpdatePacketLoss();
76         UpdateRTT(seq);
77 }
78
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);
83                 packets_lost = 0;
84                 packets_received = 0;
85         }
86 }
87
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
93                 return;
94         }
95         int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16];
96         rtt += (cur_rtt - rtt) * 0.1f;
97 }
98
99 bool CongestionControl::SamplePacket(std::uint16_t seq) const noexcept {
100         return seq % sample_skip == 0;
101 }
102
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;
106 }
107
108 void CongestionControl::PacketIn(const UDPpacket &pack) noexcept {
109         rx_bytes += pack.len + packet_overhead;
110         UpdateStats();
111 }
112
113 void CongestionControl::PacketOut(const UDPpacket &pack) noexcept {
114         tx_bytes += pack.len + packet_overhead;
115         UpdateStats();
116 }
117
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);
123                 tx_bytes = 0;
124                 rx_bytes = 0;
125                 next_sample += 1000;
126         }
127 }
128
129
130 Connection::Connection(const IPaddress &addr)
131 : handler(nullptr)
132 , addr(addr)
133 , send_timer(500)
134 , recv_timer(10000)
135 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
136 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
137 , closed(false) {
138         send_timer.Start();
139         recv_timer.Start();
140 }
141
142 bool Connection::Matches(const IPaddress &remote) const noexcept {
143         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
144 }
145
146 void Connection::FlagSend() noexcept {
147         send_timer.Reset();
148 }
149
150 void Connection::FlagRecv() noexcept {
151         recv_timer.Reset();
152 }
153
154 bool Connection::ShouldPing() const noexcept {
155         return !closed && send_timer.HitOnce();
156 }
157
158 bool Connection::TimedOut() const noexcept {
159         return recv_timer.HitOnce();
160 }
161
162 void Connection::Update(int dt) {
163         send_timer.Update(dt);
164         recv_timer.Update(dt);
165         if (TimedOut()) {
166                 Close();
167                 if (HasHandler()) {
168                         Handler().OnTimeout();
169                 }
170         }
171 }
172
173
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++;
178
179         udp_pack.address = addr;
180         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
181                 throw NetError("SDLNet_UDP_Send");
182         }
183
184         if (HasHandler()) {
185                 Handler().PacketOut(udp_pack);
186                 Handler().PacketSent(seq);
187         }
188
189         FlagSend();
190         return seq;
191 }
192
193 void Connection::Received(const UDPpacket &udp_pack) {
194         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
195
196         // ack to the remote
197         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
198         if (diff > 0) {
199                 if (diff >= 32) {
200                         ctrl_out.hist = 0;
201                 } else {
202                         ctrl_out.hist <<= diff;
203                         ctrl_out.hist |= 1 << (diff - 1);
204                 }
205         } else if (diff < 0 && diff >= -32) {
206                 ctrl_out.hist |= 1 << (-diff - 1);
207         }
208         ctrl_out.ack = pack.header.ctrl.seq;
209         FlagRecv();
210
211         if (!HasHandler()) {
212                 return;
213         }
214
215         Packet::TControl ctrl_new = pack.header.ctrl;
216         Handler().PacketIn(udp_pack);
217         Handler().Handle(udp_pack);
218
219         if (diff > 0) {
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…
224                 if (diff > 0) {
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);
228                                 }
229                         }
230                 }
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);
235                         }
236                 }
237                 ctrl_in = ctrl_new;
238         }
239 }
240
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;
246 }
247
248 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
249         Packet::Make<Packet::Ping>(udp_pack);
250         return Send(udp_pack, sock);
251 }
252
253
254 ConnectionHandler::ConnectionHandler()
255 : cc() {
256
257 }
258
259 void ConnectionHandler::PacketSent(uint16_t seq) noexcept {
260         cc.PacketSent(seq);
261 }
262
263 void ConnectionHandler::PacketLost(uint16_t seq) {
264         OnPacketLost(seq);
265         cc.PacketLost(seq);
266 }
267
268 void ConnectionHandler::PacketReceived(uint16_t seq) {
269         OnPacketReceived(seq);
270         cc.PacketReceived(seq);
271 }
272
273 void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept {
274         cc.PacketIn(pack);
275 }
276
277 void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept {
278         cc.PacketOut(pack);
279 }
280
281
282 ostream &operator <<(ostream &out, const IPaddress &addr) {
283         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
284         out << int(host[0])
285                 << '.' << int(host[1])
286                 << '.' << int(host[2])
287                 << '.' << int(host[3]);
288         if (addr.port) {
289                 out << ':' << SDLNet_Read16(&addr.port);
290         }
291         return out;
292 }
293
294
295 const char *Packet::Type2String(uint8_t t) noexcept {
296         switch (t) {
297                 case Ping::TYPE:
298                         return "Ping";
299                 case Login::TYPE:
300                         return "Login";
301                 case Join::TYPE:
302                         return "Join";
303                 case Part::TYPE:
304                         return "Part";
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:
316                         return "ChunkBegin";
317                 case ChunkData::TYPE:
318                         return "ChunkData";
319                 case BlockUpdate::TYPE:
320                         return "BlockUpdate";
321                 case Message::TYPE:
322                         return "Message";
323                 default:
324                         return "Unknown";
325         }
326 }
327
328 template<class T>
329 void Packet::Payload::Write(const T &src, size_t off) noexcept {
330         if ((length - off) < sizeof(T)) {
331                 // dismiss out of bounds write
332                 return;
333         }
334         *reinterpret_cast<T *>(&data[off]) = src;
335 }
336
337 template<class T>
338 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
339         if ((length - off) < sizeof(T)) {
340                 // dismiss out of bounds read
341                 return;
342         }
343         dst = *reinterpret_cast<T *>(&data[off]);
344 }
345
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());
352         } else {
353                 memcpy(dst, src.c_str(), len);
354         }
355 }
356
357 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
358         size_t len = min(maxlen, length - off);
359         dst.clear();
360         dst.reserve(len);
361         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
362                 dst.push_back(data[off + i]);
363         }
364 }
365
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);
371 }
372
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);
379 }
380
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);
388 }
389
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;
399         state.yaw *= PI;
400 }
401
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);
409 }
410
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;
421         state.yaw *= PI;
422 }
423
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);
428 }
429
430 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
431         int8_t conv = 0;
432         Read(conv, off);
433         val.x = conv;
434         Read(conv, off + 1);
435         val.y = conv;
436         Read(conv, off + 2);
437         val.z = conv;
438 }
439
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);
442         Write(raw, off);
443 }
444
445 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
446         int16_t raw = 0;
447         Read(raw, off);
448         val = raw * (1.0f/32767.0f);
449 }
450
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);
455 }
456
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);
461 }
462
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);
465         Write(raw, off);
466 }
467
468 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
469         uint16_t raw = 0;
470         Read(raw, off);
471         val = raw * (1.0f/65535.0f);
472 }
473
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);
478 }
479
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);
484 }
485
486
487 void Packet::Login::WritePlayerName(const string &name) noexcept {
488         WriteString(name, 0, 32);
489 }
490
491 void Packet::Login::ReadPlayerName(string &name) const noexcept {
492         ReadString(name, 0, 32);
493 }
494
495 void Packet::Join::WritePlayer(const Entity &player) noexcept {
496         Write(player.ID(), 0);
497         Write(player.GetState(), 4);
498 }
499
500 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
501         Read(id, 0);
502 }
503
504 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
505         Read(state, 4);
506 }
507
508 void Packet::Join::WriteWorldName(const string &name) noexcept {
509         WriteString(name, 46, 32);
510 }
511
512 void Packet::Join::ReadWorldName(string &name) const noexcept {
513         ReadString(name, 46, 32);
514 }
515
516 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
517         Write(state, 0);
518 }
519
520 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
521         Read(state, 0);
522 }
523
524 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
525         WritePackN(mov, 42);
526 }
527
528 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
529         ReadPackN(mov, 42);
530 }
531
532 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
533         Write(actions, 48);
534 }
535
536 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
537         Read(actions, 48);
538 }
539
540 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
541         Write(slot, 49);
542 }
543
544 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
545         Read(slot, 49);
546 }
547
548 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
549         Write(e.ID(), 0);
550         if (e.GetModel()) {
551                 Write(e.GetModel().GetModel().ID(), 4);
552         } else {
553                 Write(uint32_t(0), 4);
554         }
555         Write(e.GetState(), 8);
556         Write(e.Bounds(), 50);
557         uint32_t flags = 0;
558         if (e.WorldCollidable()) {
559                 flags |= 1;
560         }
561         Write(flags, 74);
562         WriteString(e.Name(), 78, 32);
563 }
564
565 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
566         Read(id, 0);
567 }
568
569 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
570         Read(id, 4);
571 }
572
573 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
574         EntityState state;
575         AABB bounds;
576         uint32_t flags = 0;
577         string name;
578
579         Read(state, 8);
580         Read(bounds, 50);
581         Read(flags, 74);
582         ReadString(name, 78, 32);
583
584         e.SetState(state);
585         e.Bounds(bounds);
586         e.WorldCollidable(flags & 1);
587         e.Name(name);
588 }
589
590 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
591         Write(id, 0);
592 }
593
594 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
595         Read(id, 0);
596 }
597
598 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
599         Write(count, 0);
600 }
601
602 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
603         Read(count, 0);
604 }
605
606 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
607         Write(base, 4);
608 }
609
610 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
611         Read(base, 4);
612 }
613
614 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
615         uint32_t off = GetSize(num);
616
617         Write(entity.ID(), off);
618         Write(entity.GetState(), base, off + 4);
619 }
620
621 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
622         uint32_t off = GetSize(num);
623         Read(id, off);
624 }
625
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);
629 }
630
631 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
632         Write(s, 0);
633 }
634
635 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
636         Read(s, 0);
637 }
638
639 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
640         Write(player.GetState(), 2);
641 }
642
643 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
644         Read(state, 2);
645 }
646
647 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
648         Write(id, 0);
649 }
650
651 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
652         Read(id, 0);
653 }
654
655 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
656         Write(f, 4);
657 }
658
659 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
660         Read(f, 4);
661 }
662
663 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
664         Write(pos, 8);
665 }
666
667 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
668         Read(pos, 8);
669 }
670
671 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
672         Write(s, 20);
673 }
674
675 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
676         Read(s, 20);
677 }
678
679 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
680         Write(id, 0);
681 }
682
683 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
684         Read(id, 0);
685 }
686
687 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
688         Write(o, 4);
689 }
690
691 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
692         Read(o, 4);
693 }
694
695 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
696         Write(s, 8);
697 }
698
699 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
700         Read(s, 8);
701 }
702
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);
706 }
707
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);
711 }
712
713 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
714         Write(coords, 0);
715 }
716
717 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
718         Read(coords, 0);
719 }
720
721 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
722         Write(count, 12);
723 }
724
725 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
726         Read(count, 12);
727 }
728
729 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
730         uint32_t off = GetSize(num);
731         Write(index, off);
732 }
733
734 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
735         uint32_t off = GetSize(num);
736         Read(index, off);
737 }
738
739 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
740         uint32_t off = GetSize(num) + 2;
741         Write(block, off);
742 }
743
744 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
745         uint32_t off = GetSize(num) + 2;
746         Read(block, off);
747 }
748
749 void Packet::Message::WriteType(uint8_t type) noexcept {
750         Write(type, 0);
751 }
752
753 void Packet::Message::ReadType(uint8_t &type) const noexcept {
754         Read(type, 0);
755 }
756
757 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
758         Write(ref, 1);
759 }
760
761 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
762         Read(ref, 1);
763 }
764
765 void Packet::Message::WriteMessage(const string &msg) noexcept {
766         WriteString(msg, 5, MAX_MESSAGE_LEN);
767 }
768
769 void Packet::Message::ReadMessage(string &msg) const noexcept {
770         ReadString(msg, 5, MAX_MESSAGE_LEN);
771 }
772
773
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));
779                         break;
780                 case Packet::Login::TYPE:
781                         On(Packet::As<Packet::Login>(udp_pack));
782                         break;
783                 case Packet::Join::TYPE:
784                         On(Packet::As<Packet::Join>(udp_pack));
785                         break;
786                 case Packet::Part::TYPE:
787                         On(Packet::As<Packet::Part>(udp_pack));
788                         break;
789                 case Packet::PlayerUpdate::TYPE:
790                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
791                         break;
792                 case Packet::SpawnEntity::TYPE:
793                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
794                         break;
795                 case Packet::DespawnEntity::TYPE:
796                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
797                         break;
798                 case Packet::EntityUpdate::TYPE:
799                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
800                         break;
801                 case Packet::PlayerCorrection::TYPE:
802                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
803                         break;
804                 case Packet::ChunkBegin::TYPE:
805                         On(Packet::As<Packet::ChunkBegin>(udp_pack));
806                         break;
807                 case Packet::ChunkData::TYPE:
808                         On(Packet::As<Packet::ChunkData>(udp_pack));
809                         break;
810                 case Packet::BlockUpdate::TYPE:
811                         On(Packet::As<Packet::BlockUpdate>(udp_pack));
812                         break;
813                 case Packet::Message::TYPE:
814                         On(Packet::As<Packet::Message>(udp_pack));
815                         break;
816                 default:
817                         // drop unknown or unhandled packets
818                         break;
819         }
820 }
821
822 }