]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
cube map textures
[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
30 Connection::Connection(const IPaddress &addr)
31 : handler(nullptr)
32 , addr(addr)
33 , send_timer(500)
34 , recv_timer(10000)
35 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
36 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
37 , closed(false) {
38         send_timer.Start();
39         recv_timer.Start();
40 }
41
42 bool Connection::Matches(const IPaddress &remote) const noexcept {
43         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
44 }
45
46 void Connection::FlagSend() noexcept {
47         send_timer.Reset();
48 }
49
50 void Connection::FlagRecv() noexcept {
51         recv_timer.Reset();
52 }
53
54 bool Connection::ShouldPing() const noexcept {
55         return !closed && send_timer.HitOnce();
56 }
57
58 bool Connection::TimedOut() const noexcept {
59         return recv_timer.HitOnce();
60 }
61
62 void Connection::Update(int dt) {
63         send_timer.Update(dt);
64         recv_timer.Update(dt);
65         if (TimedOut()) {
66                 Close();
67                 if (HasHandler()) {
68                         Handler().OnTimeout();
69                 }
70         }
71 }
72
73
74 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
75         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
76         pack.header.ctrl = ctrl_out;
77         uint16_t seq = ctrl_out.seq++;
78
79         udp_pack.address = addr;
80         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
81                 throw NetError("SDLNet_UDP_Send");
82         }
83
84         FlagSend();
85         return seq;
86 }
87
88 void Connection::Received(const UDPpacket &udp_pack) {
89         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
90
91         // ack to the remote
92         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
93         if (diff > 0) {
94                 if (diff >= 32) {
95                         ctrl_out.hist = 0;
96                 } else {
97                         ctrl_out.hist <<= diff;
98                         ctrl_out.hist |= 1 << (diff - 1);
99                 }
100         } else if (diff < 0 && diff >= -32) {
101                 ctrl_out.hist |= 1 << (-diff - 1);
102         }
103         ctrl_out.ack = pack.header.ctrl.seq;
104         FlagRecv();
105
106         if (!HasHandler()) {
107                 return;
108         }
109
110         Packet::TControl ctrl_new = pack.header.ctrl;
111         Handler().Handle(udp_pack);
112
113         if (diff > 0) {
114                 // if the packet holds more recent information
115                 // check if remote failed to ack one of our packets
116                 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
117                 // should always be true, but you never know…
118                 if (diff > 0) {
119                         for (int i = 0; i < diff; ++i) {
120                                 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
121                                         Handler().PacketLost(ctrl_in.ack - 32 + i);
122                                 }
123                         }
124                 }
125                 // check for newly ack'd packets
126                 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
127                         if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
128                                 Handler().PacketReceived(s);
129                         }
130                 }
131                 ctrl_in = ctrl_new;
132         }
133 }
134
135 bool Packet::TControl::Acks(uint16_t s) const noexcept {
136         int16_t diff = int16_t(ack) - int16_t(s);
137         if (diff == 0) return true;
138         if (diff < 0 || diff > 32) return false;
139         return (hist & (1 << (diff - 1))) != 0;
140 }
141
142 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
143         Packet::Make<Packet::Ping>(udp_pack);
144         return Send(udp_pack, sock);
145 }
146
147
148 ConnectionHandler::ConnectionHandler()
149 : packets_lost(0)
150 , packets_received(0)
151 , packet_loss(0.0f) {
152
153 }
154
155 void ConnectionHandler::PacketLost(uint16_t seq) {
156         OnPacketLost(seq);
157         ++packets_lost;
158         UpdatePacketLoss();
159 }
160
161 void ConnectionHandler::PacketReceived(uint16_t seq) {
162         OnPacketReceived(seq);
163         ++packets_received;
164         UpdatePacketLoss();
165 }
166
167 void ConnectionHandler::UpdatePacketLoss() noexcept {
168         unsigned int packets_total = packets_lost + packets_received;
169         if (packets_total >= 256) {
170                 packet_loss = float(packets_lost) / float(packets_total);
171                 packets_lost = 0;
172                 packets_received = 0;
173         }
174 }
175
176
177 ostream &operator <<(ostream &out, const IPaddress &addr) {
178         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
179         out << int(host[0])
180                 << '.' << int(host[1])
181                 << '.' << int(host[2])
182                 << '.' << int(host[3]);
183         if (addr.port) {
184                 out << ':' << SDLNet_Read16(&addr.port);
185         }
186         return out;
187 }
188
189
190 const char *Packet::Type2String(uint8_t t) noexcept {
191         switch (t) {
192                 case Ping::TYPE:
193                         return "Ping";
194                 case Login::TYPE:
195                         return "Login";
196                 case Join::TYPE:
197                         return "Join";
198                 case Part::TYPE:
199                         return "Part";
200                 case PlayerUpdate::TYPE:
201                         return "PlayerUpdate";
202                 case SpawnEntity::TYPE:
203                         return "SpawnEntity";
204                 case DespawnEntity::TYPE:
205                         return "DespawnEntity";
206                 case EntityUpdate::TYPE:
207                         return "EntityUpdate";
208                 case PlayerCorrection::TYPE:
209                         return "PlayerCorrection";
210                 case ChunkBegin::TYPE:
211                         return "ChunkBegin";
212                 case ChunkData::TYPE:
213                         return "ChunkData";
214                 default:
215                         return "Unknown";
216         }
217 }
218
219 template<class T>
220 void Packet::Payload::Write(const T &src, size_t off) noexcept {
221         if ((length - off) < sizeof(T)) {
222                 // dismiss out of bounds write
223                 return;
224         }
225         *reinterpret_cast<T *>(&data[off]) = src;
226 }
227
228 template<class T>
229 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
230         if ((length - off) < sizeof(T)) {
231                 // dismiss out of bounds read
232                 return;
233         }
234         dst = *reinterpret_cast<T *>(&data[off]);
235 }
236
237 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
238         uint8_t *dst = &data[off];
239         size_t len = min(maxlen, length - off);
240         if (src.size() < len) {
241                 memset(dst, '\0', len);
242                 memcpy(dst, src.c_str(), src.size());
243         } else {
244                 memcpy(dst, src.c_str(), len);
245         }
246 }
247
248 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
249         size_t len = min(maxlen, length - off);
250         dst.clear();
251         dst.reserve(len);
252         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
253                 dst.push_back(data[off + i]);
254         }
255 }
256
257
258 void Packet::Login::WritePlayerName(const string &name) noexcept {
259         WriteString(name, 0, 32);
260 }
261
262 void Packet::Login::ReadPlayerName(string &name) const noexcept {
263         ReadString(name, 0, 32);
264 }
265
266 void Packet::Join::WritePlayer(const Entity &player) noexcept {
267         Write(player.ID(), 0);
268         Write(player.GetState(), 4);
269 }
270
271 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
272         Read(id, 0);
273 }
274
275 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
276         Read(state, 4);
277 }
278
279 void Packet::Join::WriteWorldName(const string &name) noexcept {
280         WriteString(name, 68, 32);
281 }
282
283 void Packet::Join::ReadWorldName(string &name) const noexcept {
284         ReadString(name, 68, 32);
285 }
286
287 void Packet::PlayerUpdate::WritePlayer(const Entity &player) noexcept {
288         Write(player.GetState(), 0);
289 }
290
291 void Packet::PlayerUpdate::ReadPlayerState(EntityState &state) const noexcept {
292         Read(state, 0);
293 }
294
295 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
296         Write(e.ID(), 0);
297         if (e.GetModel()) {
298                 Write(e.GetModel().GetModel().ID(), 4);
299         } else {
300                 Write(uint32_t(0), 4);
301         }
302         Write(e.GetState(), 8);
303         Write(e.Bounds(), 72);
304         uint32_t flags = 0;
305         if (e.WorldCollidable()) {
306                 flags |= 1;
307         }
308         Write(flags, 96);
309         WriteString(e.Name(), 100, 32);
310 }
311
312 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
313         Read(id, 0);
314 }
315
316 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
317         Read(id, 4);
318 }
319
320 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
321         EntityState state;
322         AABB bounds;
323         uint32_t flags = 0;
324         string name;
325
326         Read(state, 8);
327         Read(bounds, 72);
328         Read(flags, 96);
329         ReadString(name, 100, 32);
330
331         e.SetState(state);
332         e.Bounds(bounds);
333         e.WorldCollidable(flags & 1);
334         e.Name(name);
335 }
336
337 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
338         Write(id, 0);
339 }
340
341 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
342         Read(id, 0);
343 }
344
345 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
346         Write(count, 0);
347 }
348
349 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
350         Read(count, 0);
351 }
352
353 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
354         uint32_t off = GetSize(num);;
355
356         Write(entity.ID(), off);
357         Write(entity.GetState(), off + 4);
358 }
359
360 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
361         uint32_t off = GetSize(num);;
362         Read(id, off);
363 }
364
365 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
366         uint32_t off = GetSize(num);;
367         Read(state, off + 4);
368 }
369
370 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
371         Write(s, 0);
372 }
373
374 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
375         Read(s, 0);
376 }
377
378 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
379         Write(player.GetState(), 2);
380 }
381
382 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
383         Read(state, 2);
384 }
385
386 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
387         Write(id, 0);
388 }
389
390 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
391         Read(id, 0);
392 }
393
394 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
395         Write(f, 4);
396 }
397
398 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
399         Read(f, 4);
400 }
401
402 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
403         Write(pos, 8);
404 }
405
406 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
407         Read(pos, 8);
408 }
409
410 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
411         Write(s, 20);
412 }
413
414 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
415         Read(s, 20);
416 }
417
418 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
419         Write(id, 0);
420 }
421
422 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
423         Read(id, 0);
424 }
425
426 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
427         Write(o, 4);
428 }
429
430 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
431         Read(o, 4);
432 }
433
434 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
435         Write(s, 8);
436 }
437
438 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
439         Read(s, 8);
440 }
441
442 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
443         size_t len = min(length - 12, l);
444         memcpy(&data[12], d, len);
445 }
446
447 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
448         size_t len = min(length - 12, l);
449         memcpy(d, &data[12], len);
450 }
451
452
453 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
454         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
455         switch (pack.Type()) {
456                 case Packet::Ping::TYPE:
457                         On(Packet::As<Packet::Ping>(udp_pack));
458                         break;
459                 case Packet::Login::TYPE:
460                         On(Packet::As<Packet::Login>(udp_pack));
461                         break;
462                 case Packet::Join::TYPE:
463                         On(Packet::As<Packet::Join>(udp_pack));
464                         break;
465                 case Packet::Part::TYPE:
466                         On(Packet::As<Packet::Part>(udp_pack));
467                         break;
468                 case Packet::PlayerUpdate::TYPE:
469                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
470                         break;
471                 case Packet::SpawnEntity::TYPE:
472                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
473                         break;
474                 case Packet::DespawnEntity::TYPE:
475                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
476                         break;
477                 case Packet::EntityUpdate::TYPE:
478                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
479                         break;
480                 case Packet::PlayerCorrection::TYPE:
481                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
482                         break;
483                 case Packet::ChunkBegin::TYPE:
484                         On(Packet::As<Packet::ChunkBegin>(udp_pack));
485                         break;
486                 case Packet::ChunkData::TYPE:
487                         On(Packet::As<Packet::ChunkData>(udp_pack));
488                         break;
489                 default:
490                         // drop unknown or unhandled packets
491                         break;
492         }
493 }
494
495 }