]> git.localhorst.tv Git - blank.git/blob - src/server/net.cpp
group entity updates in as few packets as possible
[blank.git] / src / server / net.cpp
1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
3 #include "Server.hpp"
4
5 #include "../app/init.hpp"
6 #include "../world/ChunkIndex.hpp"
7 #include "../world/Entity.hpp"
8 #include "../world/World.hpp"
9
10 #include <iostream>
11 #include <zlib.h>
12
13 using namespace std;
14
15
16 namespace blank {
17 namespace server {
18
19 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
20 : conn(conn)
21 , current(nullptr)
22 , buffer_size(Chunk::BlockSize() + 10)
23 , buffer(new uint8_t[buffer_size])
24 , buffer_len(0)
25 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
26 , cursor(0)
27 , num_packets(0)
28 , begin_packet(-1)
29 , data_packets()
30 , confirm_wait(0)
31 , trans_id(0)
32 , compressed(false) {
33
34 }
35
36 ChunkTransmitter::~ChunkTransmitter() {
37         Abort();
38 }
39
40 bool ChunkTransmitter::Idle() const noexcept {
41         return !Transmitting() && !Waiting();
42 }
43
44 bool ChunkTransmitter::Transmitting() const noexcept {
45         return cursor < num_packets;
46 }
47
48 void ChunkTransmitter::Transmit() {
49         if (cursor < num_packets) {
50                 SendData(cursor);
51                 ++cursor;
52         }
53 }
54
55 bool ChunkTransmitter::Waiting() const noexcept {
56         return confirm_wait > 0;
57 }
58
59 void ChunkTransmitter::Ack(uint16_t seq) {
60         if (!Waiting()) {
61                 return;
62         }
63         if (seq == begin_packet) {
64                 begin_packet = -1;
65                 --confirm_wait;
66                 if (Idle()) {
67                         Release();
68                 }
69                 return;
70         }
71         for (int i = 0, end = data_packets.size(); i < end; ++i) {
72                 if (seq == data_packets[i]) {
73                         data_packets[i] = -1;
74                         --confirm_wait;
75                         if (Idle()) {
76                                 Release();
77                         }
78                         return;
79                 }
80         }
81 }
82
83 void ChunkTransmitter::Nack(uint16_t seq) {
84         if (!Waiting()) {
85                 return;
86         }
87         if (seq == begin_packet) {
88                 SendBegin();
89                 return;
90         }
91         for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
92                 if (seq == data_packets[i]) {
93                         SendData(i);
94                         return;
95                 }
96         }
97 }
98
99 void ChunkTransmitter::Abort() {
100         if (!current) return;
101
102         Release();
103
104         begin_packet = -1;
105         data_packets.clear();
106         confirm_wait = 0;
107 }
108
109 void ChunkTransmitter::Send(Chunk &chunk) {
110         // abort current chunk, if any
111         Abort();
112
113         current = &chunk;
114         current->Ref();
115
116         // load new chunk data
117         compressed = true;
118         buffer_len = buffer_size;
119         if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
120                 // compression failed, send it uncompressed
121                 buffer_len = Chunk::BlockSize();
122                 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
123                 compressed = false;
124         }
125         cursor = 0;
126         num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
127         data_packets.resize(num_packets, -1);
128
129         ++trans_id;
130         SendBegin();
131 }
132
133 void ChunkTransmitter::SendBegin() {
134         uint32_t flags = compressed;
135         auto pack = conn.Prepare<Packet::ChunkBegin>();
136         pack.WriteTransmissionId(trans_id);
137         pack.WriteFlags(flags);
138         pack.WriteChunkCoords(current->Position());
139         pack.WriteDataSize(buffer_len);
140         if (begin_packet == -1) {
141                 ++confirm_wait;
142         }
143         begin_packet = conn.Send();
144 }
145
146 void ChunkTransmitter::SendData(size_t i) {
147         int pos = i * packet_len;
148         int len = min(packet_len, buffer_len - pos);
149         const uint8_t *data = &buffer[pos];
150
151         auto pack = conn.Prepare<Packet::ChunkData>();
152         pack.WriteTransmissionId(trans_id);
153         pack.WriteDataOffset(pos);
154         pack.WriteDataSize(len);
155         pack.WriteData(data, len);
156
157         if (data_packets[i] == -1) {
158                 ++confirm_wait;
159         }
160         data_packets[i] = conn.Send();
161 }
162
163 void ChunkTransmitter::Release() {
164         if (current) {
165                 current->UnRef();
166                 current = nullptr;
167         }
168 }
169
170
171 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
172 : server(server)
173 , conn(addr)
174 , player(nullptr, nullptr)
175 , spawns()
176 , confirm_wait(0)
177 , entity_updates()
178 , player_update_state()
179 , player_update_pack(0)
180 , player_update_timer(1500)
181 , transmitter(*this)
182 , chunk_queue()
183 , old_base() {
184         conn.SetHandler(this);
185 }
186
187 ClientConnection::~ClientConnection() {
188         DetachPlayer();
189 }
190
191 void ClientConnection::Update(int dt) {
192         conn.Update(dt);
193         if (Disconnected()) {
194                 return;
195         }
196         if (HasPlayer()) {
197                 // sync entities
198                 auto global_iter = server.GetWorld().Entities().begin();
199                 auto global_end = server.GetWorld().Entities().end();
200                 auto local_iter = spawns.begin();
201                 auto local_end = spawns.end();
202
203                 while (global_iter != global_end && local_iter != local_end) {
204                         if (global_iter->ID() == local_iter->entity->ID()) {
205                                 // they're the same
206                                 if (CanDespawn(*global_iter)) {
207                                         SendDespawn(*local_iter);
208                                 } else {
209                                         // update
210                                         QueueUpdate(*local_iter);
211                                 }
212                                 ++global_iter;
213                                 ++local_iter;
214                         } else if (global_iter->ID() < local_iter->entity->ID()) {
215                                 // global entity was inserted
216                                 if (CanSpawn(*global_iter)) {
217                                         auto spawned = spawns.emplace(local_iter, *global_iter);
218                                         SendSpawn(*spawned);
219                                 }
220                                 ++global_iter;
221                         } else {
222                                 // global entity was removed
223                                 SendDespawn(*local_iter);
224                                 ++local_iter;
225                         }
226                 }
227
228                 // leftover spawns
229                 while (global_iter != global_end) {
230                         if (CanSpawn(*global_iter)) {
231                                 spawns.emplace_back(*global_iter);
232                                 SendSpawn(spawns.back());
233                         }
234                         ++global_iter;
235                 }
236
237                 // leftover despawns
238                 while (local_iter != local_end) {
239                         SendDespawn(*local_iter);
240                         ++local_iter;
241                 }
242                 SendUpdates();
243
244                 CheckPlayerFix();
245                 CheckChunkQueue();
246         }
247         if (conn.ShouldPing()) {
248                 conn.SendPing(server.GetPacket(), server.GetSocket());
249         }
250 }
251
252 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
253 : entity(&e)
254 , spawn_pack(-1)
255 , despawn_pack(-1) {
256         entity->Ref();
257 }
258
259 ClientConnection::SpawnStatus::~SpawnStatus() {
260         entity->UnRef();
261 }
262
263 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
264         return
265                 &e != player.entity &&
266                 !e.Dead() &&
267                 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
268 }
269
270 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
271         return
272                 e.Dead() ||
273                 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
274 }
275
276 uint16_t ClientConnection::Send() {
277         return conn.Send(server.GetPacket(), server.GetSocket());
278 }
279
280 uint16_t ClientConnection::Send(size_t len) {
281         server.GetPacket().len = len;
282         return Send();
283 }
284
285 void ClientConnection::SendSpawn(SpawnStatus &status) {
286         // don't double spawn
287         if (status.spawn_pack != -1) return;
288
289         auto pack = Prepare<Packet::SpawnEntity>();
290         pack.WriteEntity(*status.entity);
291         status.spawn_pack = Send();
292         ++confirm_wait;
293 }
294
295 void ClientConnection::SendDespawn(SpawnStatus &status) {
296         // don't double despawn
297         if (status.despawn_pack != -1) return;
298
299         auto pack = Prepare<Packet::DespawnEntity>();
300         pack.WriteEntityID(status.entity->ID());
301         status.despawn_pack = Send();
302         ++confirm_wait;
303 }
304
305 void ClientConnection::QueueUpdate(SpawnStatus &status) {
306         // don't send updates while spawn not ack'd or despawn sent
307         if (status.spawn_pack == -1 && status.despawn_pack == -1) {
308                 entity_updates.push_back(&status);
309         }
310 }
311
312 void ClientConnection::SendUpdates() {
313         auto pack = Prepare<Packet::EntityUpdate>();
314         int entity_pos = 0;
315         for (SpawnStatus *status : entity_updates) {
316                 pack.WriteEntity(*status->entity, entity_pos);
317                 ++entity_pos;
318                 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
319                         pack.WriteEntityCount(entity_pos);
320                         Send(Packet::EntityUpdate::GetSize(entity_pos));
321                         pack = Prepare<Packet::EntityUpdate>();
322                         entity_pos = 0;
323                 }
324         }
325         if (entity_pos > 0) {
326                 pack.WriteEntityCount(entity_pos);
327                 Send(Packet::EntityUpdate::GetSize(entity_pos));
328         }
329         entity_updates.clear();
330 }
331
332 void ClientConnection::CheckPlayerFix() {
333         // player_update_state's position holds the client's most recent prediction
334         glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
335         float dist_squared = dot(diff, diff);
336
337         // if client's prediction is off by more than 1cm, send
338         // our (authoritative) state back so it can fix it
339         constexpr float fix_thresh = 0.0001f;
340
341         if (dist_squared > fix_thresh) {
342                 auto pack = Prepare<Packet::PlayerCorrection>();
343                 pack.WritePacketSeq(player_update_pack);
344                 pack.WritePlayer(PlayerEntity());
345                 Send();
346         }
347 }
348
349 void ClientConnection::CheckChunkQueue() {
350         if (PlayerChunks().Base() != old_base) {
351                 Chunk::Pos begin = PlayerChunks().CoordsBegin();
352                 Chunk::Pos end = PlayerChunks().CoordsEnd();
353                 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
354                         for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
355                                 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
356                                         if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
357                                                 chunk_queue.push_back(pos);
358                                         }
359                                 }
360                         }
361                 }
362                 old_base = PlayerChunks().Base();
363         }
364         if (transmitter.Transmitting()) {
365                 transmitter.Transmit();
366                 return;
367         }
368         if (transmitter.Idle()) {
369                 int count = 0;
370                 constexpr int max = 64;
371                 while (count < max && !chunk_queue.empty()) {
372                         Chunk::Pos pos = chunk_queue.front();
373                         chunk_queue.pop_front();
374                         if (PlayerChunks().InRange(pos)) {
375                                 Chunk *chunk = PlayerChunks().Get(pos);
376                                 if (chunk) {
377                                         transmitter.Send(*chunk);
378                                         return;
379                                 } else {
380                                         chunk_queue.push_back(pos);
381                                 }
382                                 ++count;
383                         }
384                 }
385         }
386 }
387
388 void ClientConnection::AttachPlayer(const Player &new_player) {
389         DetachPlayer();
390         player = new_player;
391         player.entity->Ref();
392
393         old_base = player.chunks->Base();
394         Chunk::Pos begin = player.chunks->CoordsBegin();
395         Chunk::Pos end = player.chunks->CoordsEnd();
396         for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
397                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
398                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
399                                 chunk_queue.push_back(pos);
400                         }
401                 }
402         }
403
404         cout << "player \"" << player.entity->Name() << "\" joined" << endl;
405 }
406
407 void ClientConnection::DetachPlayer() {
408         if (!HasPlayer()) return;
409         cout << "player \"" << player.entity->Name() << "\" left" << endl;
410         player.entity->Kill();
411         player.entity->UnRef();
412         player.entity = nullptr;
413         player.chunks = nullptr;
414         transmitter.Abort();
415         chunk_queue.clear();
416 }
417
418 void ClientConnection::OnPacketReceived(uint16_t seq) {
419         if (transmitter.Waiting()) {
420                 transmitter.Ack(seq);
421         }
422         if (!confirm_wait) return;
423         for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
424                 if (seq == iter->spawn_pack) {
425                         iter->spawn_pack = -1;
426                         --confirm_wait;
427                         return;
428                 }
429                 if (seq == iter->despawn_pack) {
430                         spawns.erase(iter);
431                         --confirm_wait;
432                         return;
433                 }
434         }
435 }
436
437 void ClientConnection::OnPacketLost(uint16_t seq) {
438         if (transmitter.Waiting()) {
439                 transmitter.Nack(seq);
440         }
441         if (!confirm_wait) return;
442         for (SpawnStatus &status : spawns) {
443                 if (seq == status.spawn_pack) {
444                         status.spawn_pack = -1;
445                         --confirm_wait;
446                         SendSpawn(status);
447                         return;
448                 }
449                 if (seq == status.despawn_pack) {
450                         status.despawn_pack = -1;
451                         --confirm_wait;
452                         SendDespawn(status);
453                         return;
454                 }
455         }
456 }
457
458 void ClientConnection::On(const Packet::Login &pack) {
459         string name;
460         pack.ReadPlayerName(name);
461
462         Player new_player = server.GetWorld().AddPlayer(name);
463
464         if (new_player.entity) {
465                 // success!
466                 AttachPlayer(new_player);
467                 cout << "accepted login from player \"" << name << '"' << endl;
468                 auto response = Prepare<Packet::Join>();
469                 response.WritePlayer(*new_player.entity);
470                 response.WriteWorldName(server.GetWorld().Name());
471                 Send();
472                 // set up update tracking
473                 player_update_state = new_player.entity->GetState();
474                 player_update_pack = pack.Seq();
475                 player_update_timer.Reset();
476                 player_update_timer.Start();
477         } else {
478                 // aw no :(
479                 cout << "rejected login from player \"" << name << '"' << endl;
480                 Prepare<Packet::Part>();
481                 Send();
482                 conn.Close();
483         }
484 }
485
486 void ClientConnection::On(const Packet::Part &) {
487         conn.Close();
488 }
489
490 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
491         if (!HasPlayer()) return;
492         int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
493         bool overdue = player_update_timer.HitOnce();
494         player_update_timer.Reset();
495         if (pack_diff > 0 || overdue) {
496                 player_update_pack = pack.Seq();
497                 pack.ReadPlayerState(player_update_state);
498                 // accept velocity and orientation as "user input"
499                 PlayerEntity().Velocity(player_update_state.velocity);
500                 PlayerEntity().Orientation(player_update_state.orient);
501         }
502 }
503
504
505 Server::Server(const Config &conf, World &world)
506 : serv_sock(nullptr)
507 , serv_pack{ -1, nullptr, 0 }
508 , clients()
509 , world(world) {
510         serv_sock = SDLNet_UDP_Open(conf.port);
511         if (!serv_sock) {
512                 throw NetError("SDLNet_UDP_Open");
513         }
514
515         serv_pack.data = new Uint8[sizeof(Packet)];
516         serv_pack.maxlen = sizeof(Packet);
517 }
518
519 Server::~Server() {
520         delete[] serv_pack.data;
521         SDLNet_UDP_Close(serv_sock);
522 }
523
524
525 void Server::Handle() {
526         int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
527         while (result > 0) {
528                 HandlePacket(serv_pack);
529                 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
530         }
531         if (result == -1) {
532                 // a boo boo happened
533                 throw NetError("SDLNet_UDP_Recv");
534         }
535 }
536
537 void Server::HandlePacket(const UDPpacket &udp_pack) {
538         if (udp_pack.len < int(sizeof(Packet::Header))) {
539                 // packet too small, drop
540                 return;
541         }
542         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
543         if (pack.header.tag != Packet::TAG) {
544                 // mistagged packet, drop
545                 return;
546         }
547
548         ClientConnection &client = GetClient(udp_pack.address);
549         client.GetConnection().Received(udp_pack);
550 }
551
552 ClientConnection &Server::GetClient(const IPaddress &addr) {
553         for (ClientConnection &client : clients) {
554                 if (client.Matches(addr)) {
555                         return client;
556                 }
557         }
558         clients.emplace_back(*this, addr);
559         return clients.back();
560 }
561
562 void Server::Update(int dt) {
563         for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
564                 client->Update(dt);
565                 if (client->Disconnected()) {
566                         client = clients.erase(client);
567                 } else {
568                         ++client;
569                 }
570         }
571 }
572
573 }
574 }