]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
basic message state
[blank.git] / src / net / net.cpp
1 #include "Connection.hpp"
2 #include "ConnectionHandler.hpp"
3 #include "io.hpp"
4 #include "Packet.hpp"
5
6 #include "../app/init.hpp"
7 #include "../model/CompositeModel.hpp"
8 #include "../world/Entity.hpp"
9 #include "../world/EntityState.hpp"
10
11 #include <cstring>
12
13 using namespace std;
14
15
16 namespace blank {
17
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
31 Connection::Connection(const IPaddress &addr)
32 : handler(nullptr)
33 , addr(addr)
34 , send_timer(500)
35 , recv_timer(10000)
36 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
37 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
38 , closed(false) {
39         send_timer.Start();
40         recv_timer.Start();
41 }
42
43 bool Connection::Matches(const IPaddress &remote) const noexcept {
44         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
45 }
46
47 void Connection::FlagSend() noexcept {
48         send_timer.Reset();
49 }
50
51 void Connection::FlagRecv() noexcept {
52         recv_timer.Reset();
53 }
54
55 bool Connection::ShouldPing() const noexcept {
56         return !closed && send_timer.HitOnce();
57 }
58
59 bool Connection::TimedOut() const noexcept {
60         return recv_timer.HitOnce();
61 }
62
63 void Connection::Update(int dt) {
64         send_timer.Update(dt);
65         recv_timer.Update(dt);
66         if (TimedOut()) {
67                 Close();
68                 if (HasHandler()) {
69                         Handler().OnTimeout();
70                 }
71         }
72 }
73
74
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++;
79
80         udp_pack.address = addr;
81         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
82                 throw NetError("SDLNet_UDP_Send");
83         }
84
85         FlagSend();
86         return seq;
87 }
88
89 void Connection::Received(const UDPpacket &udp_pack) {
90         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
91
92         // ack to the remote
93         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
94         if (diff > 0) {
95                 if (diff >= 32) {
96                         ctrl_out.hist = 0;
97                 } else {
98                         ctrl_out.hist <<= diff;
99                         ctrl_out.hist |= 1 << (diff - 1);
100                 }
101         } else if (diff < 0 && diff >= -32) {
102                 ctrl_out.hist |= 1 << (-diff - 1);
103         }
104         ctrl_out.ack = pack.header.ctrl.seq;
105         FlagRecv();
106
107         if (!HasHandler()) {
108                 return;
109         }
110
111         Packet::TControl ctrl_new = pack.header.ctrl;
112         Handler().Handle(udp_pack);
113
114         if (diff > 0) {
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…
119                 if (diff > 0) {
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);
123                                 }
124                         }
125                 }
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);
130                         }
131                 }
132                 ctrl_in = ctrl_new;
133         }
134 }
135
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;
141 }
142
143 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
144         Packet::Make<Packet::Ping>(udp_pack);
145         return Send(udp_pack, sock);
146 }
147
148
149 ConnectionHandler::ConnectionHandler()
150 : packets_lost(0)
151 , packets_received(0)
152 , packet_loss(0.0f) {
153
154 }
155
156 void ConnectionHandler::PacketLost(uint16_t seq) {
157         OnPacketLost(seq);
158         ++packets_lost;
159         UpdatePacketLoss();
160 }
161
162 void ConnectionHandler::PacketReceived(uint16_t seq) {
163         OnPacketReceived(seq);
164         ++packets_received;
165         UpdatePacketLoss();
166 }
167
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);
172                 packets_lost = 0;
173                 packets_received = 0;
174         }
175 }
176
177
178 ostream &operator <<(ostream &out, const IPaddress &addr) {
179         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
180         out << int(host[0])
181                 << '.' << int(host[1])
182                 << '.' << int(host[2])
183                 << '.' << int(host[3]);
184         if (addr.port) {
185                 out << ':' << SDLNet_Read16(&addr.port);
186         }
187         return out;
188 }
189
190
191 const char *Packet::Type2String(uint8_t t) noexcept {
192         switch (t) {
193                 case Ping::TYPE:
194                         return "Ping";
195                 case Login::TYPE:
196                         return "Login";
197                 case Join::TYPE:
198                         return "Join";
199                 case Part::TYPE:
200                         return "Part";
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:
212                         return "ChunkBegin";
213                 case ChunkData::TYPE:
214                         return "ChunkData";
215                 case BlockUpdate::TYPE:
216                         return "BlockUpdate";
217                 default:
218                         return "Unknown";
219         }
220 }
221
222 template<class T>
223 void Packet::Payload::Write(const T &src, size_t off) noexcept {
224         if ((length - off) < sizeof(T)) {
225                 // dismiss out of bounds write
226                 return;
227         }
228         *reinterpret_cast<T *>(&data[off]) = src;
229 }
230
231 template<class T>
232 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
233         if ((length - off) < sizeof(T)) {
234                 // dismiss out of bounds read
235                 return;
236         }
237         dst = *reinterpret_cast<T *>(&data[off]);
238 }
239
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());
246         } else {
247                 memcpy(dst, src.c_str(), len);
248         }
249 }
250
251 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
252         size_t len = min(maxlen, length - off);
253         dst.clear();
254         dst.reserve(len);
255         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
256                 dst.push_back(data[off + i]);
257         }
258 }
259
260
261 void Packet::Login::WritePlayerName(const string &name) noexcept {
262         WriteString(name, 0, 32);
263 }
264
265 void Packet::Login::ReadPlayerName(string &name) const noexcept {
266         ReadString(name, 0, 32);
267 }
268
269 void Packet::Join::WritePlayer(const Entity &player) noexcept {
270         Write(player.ID(), 0);
271         Write(player.GetState(), 4);
272 }
273
274 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
275         Read(id, 0);
276 }
277
278 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
279         Read(state, 4);
280 }
281
282 void Packet::Join::WriteWorldName(const string &name) noexcept {
283         WriteString(name, 68, 32);
284 }
285
286 void Packet::Join::ReadWorldName(string &name) const noexcept {
287         ReadString(name, 68, 32);
288 }
289
290 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
291         Write(state, 0);
292 }
293
294 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
295         Read(state, 0);
296 }
297
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);
303 }
304
305 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
306         int16_t x, y, z;
307         Read(x, 64);
308         Read(y, 66);
309         Read(z, 68);
310         mov = glm::vec3(x, y, z) * .00003051850947599719f;
311 }
312
313 void Packet::PlayerUpdate::WritePitch(float pitch) noexcept {
314         int16_t conv = pitch * 20860.12008116853786870640f;
315         Write(conv, 70);
316 }
317
318 void Packet::PlayerUpdate::ReadPitch(float &pitch) const noexcept {
319         int16_t conv = 0;
320         Read(conv, 70);
321         pitch = conv * .00004793836258415163f;
322 }
323
324 void Packet::PlayerUpdate::WriteYaw(float yaw) noexcept {
325         int16_t conv = yaw * 10430.06004058426893435320f;
326         Write(conv, 72);
327 }
328
329 void Packet::PlayerUpdate::ReadYaw(float &yaw) const noexcept {
330         int16_t conv = 0;
331         Read(conv, 72);
332         yaw = conv * .00009587672516830326f;
333 }
334
335 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
336         Write(actions, 74);
337 }
338
339 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
340         Read(actions, 74);
341 }
342
343 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
344         Write(slot, 75);
345 }
346
347 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
348         Read(slot, 75);
349 }
350
351 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
352         Write(e.ID(), 0);
353         if (e.GetModel()) {
354                 Write(e.GetModel().GetModel().ID(), 4);
355         } else {
356                 Write(uint32_t(0), 4);
357         }
358         Write(e.GetState(), 8);
359         Write(e.Bounds(), 72);
360         uint32_t flags = 0;
361         if (e.WorldCollidable()) {
362                 flags |= 1;
363         }
364         Write(flags, 96);
365         WriteString(e.Name(), 100, 32);
366 }
367
368 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
369         Read(id, 0);
370 }
371
372 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
373         Read(id, 4);
374 }
375
376 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
377         EntityState state;
378         AABB bounds;
379         uint32_t flags = 0;
380         string name;
381
382         Read(state, 8);
383         Read(bounds, 72);
384         Read(flags, 96);
385         ReadString(name, 100, 32);
386
387         e.SetState(state);
388         e.Bounds(bounds);
389         e.WorldCollidable(flags & 1);
390         e.Name(name);
391 }
392
393 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
394         Write(id, 0);
395 }
396
397 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
398         Read(id, 0);
399 }
400
401 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
402         Write(count, 0);
403 }
404
405 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
406         Read(count, 0);
407 }
408
409 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
410         uint32_t off = GetSize(num);
411
412         Write(entity.ID(), off);
413         Write(entity.GetState(), off + 4);
414 }
415
416 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
417         uint32_t off = GetSize(num);
418         Read(id, off);
419 }
420
421 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
422         uint32_t off = GetSize(num);
423         Read(state, off + 4);
424 }
425
426 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
427         Write(s, 0);
428 }
429
430 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
431         Read(s, 0);
432 }
433
434 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
435         Write(player.GetState(), 2);
436 }
437
438 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
439         Read(state, 2);
440 }
441
442 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
443         Write(id, 0);
444 }
445
446 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
447         Read(id, 0);
448 }
449
450 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
451         Write(f, 4);
452 }
453
454 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
455         Read(f, 4);
456 }
457
458 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
459         Write(pos, 8);
460 }
461
462 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
463         Read(pos, 8);
464 }
465
466 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
467         Write(s, 20);
468 }
469
470 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
471         Read(s, 20);
472 }
473
474 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
475         Write(id, 0);
476 }
477
478 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
479         Read(id, 0);
480 }
481
482 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
483         Write(o, 4);
484 }
485
486 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
487         Read(o, 4);
488 }
489
490 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
491         Write(s, 8);
492 }
493
494 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
495         Read(s, 8);
496 }
497
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);
501 }
502
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);
506 }
507
508 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
509         Write(coords, 0);
510 }
511
512 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
513         Read(coords, 0);
514 }
515
516 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
517         Write(count, 12);
518 }
519
520 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
521         Read(count, 12);
522 }
523
524 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
525         uint32_t off = GetSize(num);
526         Write(index, off);
527 }
528
529 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
530         uint32_t off = GetSize(num);
531         Read(index, off);
532 }
533
534 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
535         uint32_t off = GetSize(num) + 2;
536         Write(block, off);
537 }
538
539 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
540         uint32_t off = GetSize(num) + 2;
541         Read(block, off);
542 }
543
544
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));
550                         break;
551                 case Packet::Login::TYPE:
552                         On(Packet::As<Packet::Login>(udp_pack));
553                         break;
554                 case Packet::Join::TYPE:
555                         On(Packet::As<Packet::Join>(udp_pack));
556                         break;
557                 case Packet::Part::TYPE:
558                         On(Packet::As<Packet::Part>(udp_pack));
559                         break;
560                 case Packet::PlayerUpdate::TYPE:
561                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
562                         break;
563                 case Packet::SpawnEntity::TYPE:
564                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
565                         break;
566                 case Packet::DespawnEntity::TYPE:
567                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
568                         break;
569                 case Packet::EntityUpdate::TYPE:
570                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
571                         break;
572                 case Packet::PlayerCorrection::TYPE:
573                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
574                         break;
575                 case Packet::ChunkBegin::TYPE:
576                         On(Packet::As<Packet::ChunkBegin>(udp_pack));
577                         break;
578                 case Packet::ChunkData::TYPE:
579                         On(Packet::As<Packet::ChunkData>(udp_pack));
580                         break;
581                 case Packet::BlockUpdate::TYPE:
582                         On(Packet::As<Packet::BlockUpdate>(udp_pack));
583                         break;
584                 default:
585                         // drop unknown or unhandled packets
586                         break;
587         }
588 }
589
590 }