1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
5 #include "../app/init.hpp"
6 #include "../geometry/distance.hpp"
7 #include "../io/WorldSave.hpp"
8 #include "../model/Model.hpp"
9 #include "../world/ChunkIndex.hpp"
10 #include "../world/Entity.hpp"
11 #include "../world/World.hpp"
16 #include <glm/gtx/io.hpp>
24 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
27 , buffer_size(Chunk::BlockSize() + 10)
28 , buffer(new uint8_t[buffer_size])
30 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
41 ChunkTransmitter::~ChunkTransmitter() {
45 bool ChunkTransmitter::Idle() const noexcept {
46 return !Transmitting() && !Waiting();
49 bool ChunkTransmitter::Transmitting() const noexcept {
50 return cursor < num_packets;
53 void ChunkTransmitter::Transmit() {
54 if (cursor < num_packets) {
60 bool ChunkTransmitter::Waiting() const noexcept {
61 return confirm_wait > 0;
64 void ChunkTransmitter::Ack(uint16_t seq) {
68 if (seq == begin_packet) {
76 for (int i = 0, end = data_packets.size(); i < end; ++i) {
77 if (seq == data_packets[i]) {
88 void ChunkTransmitter::Nack(uint16_t seq) {
92 if (seq == begin_packet) {
96 for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
97 if (seq == data_packets[i]) {
104 void ChunkTransmitter::Abort() {
105 if (!current) return;
110 data_packets.clear();
114 void ChunkTransmitter::Send(Chunk &chunk) {
115 // abort current chunk, if any
121 // load new chunk data
123 buffer_len = buffer_size;
124 if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
125 // compression failed, send it uncompressed
126 buffer_len = Chunk::BlockSize();
127 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
131 num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
132 data_packets.resize(num_packets, -1);
138 void ChunkTransmitter::SendBegin() {
139 uint32_t flags = compressed;
140 auto pack = conn.Prepare<Packet::ChunkBegin>();
141 pack.WriteTransmissionId(trans_id);
142 pack.WriteFlags(flags);
143 pack.WriteChunkCoords(current->Position());
144 pack.WriteDataSize(buffer_len);
145 if (begin_packet == -1) {
148 begin_packet = conn.Send();
151 void ChunkTransmitter::SendData(size_t i) {
152 int pos = i * packet_len;
153 int len = min(packet_len, buffer_len - pos);
154 const uint8_t *data = &buffer[pos];
156 auto pack = conn.Prepare<Packet::ChunkData>();
157 pack.WriteTransmissionId(trans_id);
158 pack.WriteDataOffset(pos);
159 pack.WriteDataSize(len);
160 pack.WriteData(data, len);
162 if (data_packets[i] == -1) {
165 data_packets[i] = conn.Send(Packet::ChunkData::GetSize(len));
168 void ChunkTransmitter::Release() {
176 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
180 , player_model(nullptr)
184 , entity_updates_skipped(0)
185 , player_update_state()
186 , player_update_pack(0)
187 , player_update_timer(1500)
192 , chunk_blocks_skipped(0) {
193 conn.SetHandler(this);
196 ClientConnection::~ClientConnection() {
200 void ClientConnection::Update(int dt) {
202 if (Disconnected()) {
211 if (conn.ShouldPing()) {
212 conn.SendPing(server.GetPacket(), server.GetSocket());
216 void ClientConnection::CheckEntities() {
217 auto global_iter = server.GetWorld().Entities().begin();
218 auto global_end = server.GetWorld().Entities().end();
219 auto local_iter = spawns.begin();
220 auto local_end = spawns.end();
222 while (global_iter != global_end && local_iter != local_end) {
223 if (global_iter->ID() == local_iter->entity->ID()) {
225 if (CanDespawn(*global_iter)) {
226 SendDespawn(*local_iter);
227 } else if (SendingUpdates()) {
229 QueueUpdate(*local_iter);
233 } else if (global_iter->ID() < local_iter->entity->ID()) {
234 // global entity was inserted
235 if (CanSpawn(*global_iter)) {
236 auto spawned = spawns.emplace(local_iter, *global_iter);
241 // global entity was removed
242 SendDespawn(*local_iter);
248 while (global_iter != global_end) {
249 if (CanSpawn(*global_iter)) {
250 spawns.emplace_back(*global_iter);
251 SendSpawn(spawns.back());
257 while (local_iter != local_end) {
258 SendDespawn(*local_iter);
263 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
270 ClientConnection::SpawnStatus::~SpawnStatus() {
274 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
276 &e != &PlayerEntity() &&
278 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
281 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
284 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
287 uint16_t ClientConnection::Send() {
288 return conn.Send(server.GetPacket(), server.GetSocket());
291 uint16_t ClientConnection::Send(size_t len) {
292 server.GetPacket().len = sizeof(Packet::Header) + len;
296 void ClientConnection::SendSpawn(SpawnStatus &status) {
297 // don't double spawn
298 if (status.spawn_pack != -1) return;
300 auto pack = Prepare<Packet::SpawnEntity>();
301 pack.WriteEntity(*status.entity);
302 status.spawn_pack = Send();
306 void ClientConnection::SendDespawn(SpawnStatus &status) {
307 // don't double despawn
308 if (status.despawn_pack != -1) return;
310 auto pack = Prepare<Packet::DespawnEntity>();
311 pack.WriteEntityID(status.entity->ID());
312 status.despawn_pack = Send();
316 bool ClientConnection::SendingUpdates() const noexcept {
317 return entity_updates_skipped >= NetStat().SuggestedPacketHold();
320 void ClientConnection::QueueUpdate(SpawnStatus &status) {
321 // don't send updates while spawn not ack'd or despawn sent
322 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
323 entity_updates.push_back(&status);
327 void ClientConnection::SendUpdates() {
328 if (!SendingUpdates()) {
329 entity_updates.clear();
330 ++entity_updates_skipped;
333 auto base = PlayerChunks().Base();
334 auto pack = Prepare<Packet::EntityUpdate>();
335 pack.WriteChunkBase(base);
337 for (SpawnStatus *status : entity_updates) {
338 pack.WriteEntity(*status->entity, base, entity_pos);
340 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
341 pack.WriteEntityCount(entity_pos);
342 Send(Packet::EntityUpdate::GetSize(entity_pos));
343 pack = Prepare<Packet::EntityUpdate>();
347 if (entity_pos > 0) {
348 pack.WriteEntityCount(entity_pos);
349 Send(Packet::EntityUpdate::GetSize(entity_pos));
351 entity_updates.clear();
352 entity_updates_skipped = 0;
355 void ClientConnection::CheckPlayerFix() {
356 // player_update_state's position holds the client's most recent prediction
357 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
358 float dist_squared = dot(diff, diff);
360 // if client's prediction is off by more than 1cm, send
361 // our (authoritative) state back so it can fix it
362 constexpr float fix_thresh = 0.0001f;
364 if (dist_squared > fix_thresh) {
365 auto pack = Prepare<Packet::PlayerCorrection>();
366 pack.WritePacketSeq(player_update_pack);
367 pack.WritePlayer(PlayerEntity());
374 struct QueueCompare {
375 explicit QueueCompare(const glm::ivec3 &base)
377 bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
378 const glm::ivec3 ld(left - base);
379 const glm::ivec3 rd(right - base);
381 ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
382 rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
384 const glm::ivec3 &base;
389 void ClientConnection::CheckChunkQueue() {
390 if (PlayerChunks().Base() != old_base) {
391 ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
392 ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
393 for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
394 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
395 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
396 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
397 chunk_queue.push_back(pos);
402 old_base = PlayerChunks().Base();
403 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
405 // don't push entity updates and chunk data in the same tick
406 if (chunk_blocks_skipped >= NetStat().SuggestedPacketHold() && !SendingUpdates()) {
407 ++chunk_blocks_skipped;
410 if (transmitter.Transmitting()) {
411 transmitter.Transmit();
412 chunk_blocks_skipped = 0;
415 if (transmitter.Idle()) {
417 constexpr int max = 64;
418 while (count < max && !chunk_queue.empty()) {
419 ExactLocation::Coarse pos = chunk_queue.front();
420 chunk_queue.pop_front();
421 if (PlayerChunks().InRange(pos)) {
422 Chunk *chunk = PlayerChunks().Get(pos);
424 transmitter.Send(*chunk);
425 chunk_blocks_skipped = 0;
428 chunk_queue.push_back(pos);
436 void ClientConnection::AttachPlayer(Player &player) {
438 input.reset(new DirectInput(server.GetWorld(), player, server));
439 PlayerEntity().Ref();
441 old_base = PlayerChunks().Base();
442 ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
443 ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
444 for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
445 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
446 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
447 chunk_queue.push_back(pos);
451 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
452 // TODO: should the server do this?
453 if (HasPlayerModel()) {
454 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
457 string msg = "player \"" + player.Name() + "\" joined";
459 server.DistributeMessage(0, 0, msg);
462 void ClientConnection::DetachPlayer() {
463 if (!HasPlayer()) return;
464 string msg = "player \"" + input->GetPlayer().Name() + "\" left";
466 server.DistributeMessage(0, 0, msg);
468 server.GetWorldSave().Write(input->GetPlayer());
469 PlayerEntity().Kill();
470 PlayerEntity().UnRef();
477 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
480 m.Instantiate(PlayerEntity().GetModel());
484 bool ClientConnection::HasPlayerModel() const noexcept {
488 const Model &ClientConnection::GetPlayerModel() const noexcept {
489 return *player_model;
492 void ClientConnection::OnPacketReceived(uint16_t seq) {
493 if (transmitter.Waiting()) {
494 transmitter.Ack(seq);
496 if (!confirm_wait) return;
497 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
498 if (seq == iter->spawn_pack) {
499 iter->spawn_pack = -1;
503 if (seq == iter->despawn_pack) {
511 void ClientConnection::OnPacketLost(uint16_t seq) {
512 if (transmitter.Waiting()) {
513 transmitter.Nack(seq);
515 if (!confirm_wait) return;
516 for (SpawnStatus &status : spawns) {
517 if (seq == status.spawn_pack) {
518 status.spawn_pack = -1;
523 if (seq == status.despawn_pack) {
524 status.despawn_pack = -1;
532 void ClientConnection::On(const Packet::Login &pack) {
534 pack.ReadPlayerName(name);
536 Player *new_player = server.JoinPlayer(name);
540 AttachPlayer(*new_player);
541 cout << "accepted login from player \"" << name << '"' << endl;
542 auto response = Prepare<Packet::Join>();
543 response.WritePlayer(new_player->GetEntity());
544 response.WriteWorldName(server.GetWorld().Name());
546 // set up update tracking
547 player_update_state = new_player->GetEntity().GetState();
548 player_update_pack = pack.Seq();
549 player_update_timer.Reset();
550 player_update_timer.Start();
553 cout << "rejected login from player \"" << name << '"' << endl;
554 Prepare<Packet::Part>();
560 void ClientConnection::On(const Packet::Part &) {
564 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
565 if (!HasPlayer()) return;
566 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
567 bool overdue = player_update_timer.HitOnce();
568 player_update_timer.Reset();
569 if (pack_diff <= 0 && !overdue) {
570 // drop old packets if we have a fairly recent state
573 glm::vec3 movement(0.0f);
577 player_update_pack = pack.Seq();
578 pack.ReadPredictedState(player_update_state);
579 pack.ReadMovement(movement);
580 pack.ReadActions(new_actions);
583 // accept client's orientation as is
584 input->GetPlayer().GetEntity().Orientation(player_update_state.orient);
586 input->SetMovement(movement);
587 // rotate head to match client's "prediction"
588 input->TurnHead(player_update_state.pitch - input->GetPitch(), player_update_state.yaw - input->GetYaw());
589 // select the given inventory slot
590 input->SelectInventory(slot);
592 // check if any actions have been started or stopped
593 if ((new_actions & 0x01) && !(old_actions & 0x01)) {
594 input->StartPrimaryAction();
595 } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
596 input->StopPrimaryAction();
598 if ((new_actions & 0x02) && !(old_actions & 0x02)) {
599 input->StartSecondaryAction();
600 } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
601 input->StopSecondaryAction();
603 if ((new_actions & 0x04) && !(old_actions & 0x04)) {
604 input->StartTertiaryAction();
605 } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
606 input->StopTertiaryAction();
608 old_actions = new_actions;
611 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
612 return HasPlayer() && PlayerChunks().InRange(pos);
615 void ClientConnection::On(const Packet::Message &pack) {
620 pack.ReadReferral(ref);
621 pack.ReadMessage(msg);
623 if (type == 1 && HasPlayer()) {
624 server.DispatchMessage(input->GetPlayer(), msg);
630 const Config::Network &conf,
632 const World::Config &wc,
633 const WorldSave &save)
635 , serv_pack{ -1, nullptr, 0 }
636 , serv_set(SDLNet_AllocSocketSet(1))
639 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
641 , player_model(nullptr)
644 throw NetError("SDLNet_AllocSocketSet");
647 serv_sock = SDLNet_UDP_Open(conf.port);
649 SDLNet_FreeSocketSet(serv_set);
650 throw NetError("SDLNet_UDP_Open");
653 if (SDLNet_UDP_AddSocket(serv_set, serv_sock) == -1) {
654 SDLNet_UDP_Close(serv_sock);
655 SDLNet_FreeSocketSet(serv_set);
656 throw NetError("SDLNet_UDP_AddSocket");
659 serv_pack.data = new Uint8[sizeof(Packet)];
660 serv_pack.maxlen = sizeof(Packet);
664 for (ClientConnection &client : clients) {
665 client.Disconnected();
668 world.Chunks().UnregisterIndex(spawn_index);
669 delete[] serv_pack.data;
670 SDLNet_UDP_DelSocket(serv_set, serv_sock);
671 SDLNet_UDP_Close(serv_sock);
672 SDLNet_FreeSocketSet(serv_set);
676 void Server::Wait(int dt) noexcept {
677 SDLNet_CheckSockets(serv_set, dt);
680 bool Server::Ready() noexcept {
681 return SDLNet_CheckSockets(serv_set, 0) > 0;
684 void Server::Handle() {
685 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
687 HandlePacket(serv_pack);
688 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
691 // a boo boo happened
692 throw NetError("SDLNet_UDP_Recv");
696 void Server::HandlePacket(const UDPpacket &udp_pack) {
697 if (udp_pack.len < int(sizeof(Packet::Header))) {
698 // packet too small, drop
701 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
702 if (pack.header.tag != Packet::TAG) {
703 // mistagged packet, drop
707 ClientConnection &client = GetClient(udp_pack.address);
708 client.GetConnection().Received(udp_pack);
711 ClientConnection &Server::GetClient(const IPaddress &addr) {
712 for (ClientConnection &client : clients) {
713 if (client.Matches(addr)) {
717 clients.emplace_back(*this, addr);
718 if (HasPlayerModel()) {
719 clients.back().SetPlayerModel(GetPlayerModel());
721 return clients.back();
724 void Server::Update(int dt) {
725 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
727 if (client->Disconnected()) {
728 client = clients.erase(client);
735 void Server::SetPlayerModel(const Model &m) noexcept {
737 for (ClientConnection &client : clients) {
738 client.SetPlayerModel(m);
742 bool Server::HasPlayerModel() const noexcept {
746 const Model &Server::GetPlayerModel() const noexcept {
747 return *player_model;
750 Player *Server::JoinPlayer(const string &name) {
751 if (spawn_index.MissingChunks() > 0) {
754 Player *player = world.AddPlayer(name);
758 if (save.Exists(*player)) {
766 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
767 chunk.SetBlock(index, block);
768 // TODO: batch chunk changes
769 auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
770 pack.WriteChunkCoords(chunk.Position());
771 pack.WriteBlockCount(uint32_t(1));
772 pack.WriteIndex(index, 0);
773 pack.WriteBlock(chunk.BlockAt(index), 0);
774 GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
775 for (ClientConnection &client : clients) {
776 if (client.ChunkInRange(chunk.Position())) {
782 void Server::DispatchMessage(Player &player, const string &msg) {
786 if (msg[0] == '/' && msg.size() > 1 && msg[1] != '/') {
787 cli.Execute(player, msg.substr(1));
789 DistributeMessage(1, player.GetEntity().ID(), msg);
793 void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
794 auto pack = Packet::Make<Packet::Message>(serv_pack);
795 pack.WriteType(type);
796 pack.WriteReferral(ref);
797 pack.WriteMessage(msg);
798 serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
802 void Server::SendAll() {
803 for (ClientConnection &client : clients) {
804 client.GetConnection().Send(serv_pack, serv_sock);