1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
5 #include "../app/init.hpp"
6 #include "../io/WorldSave.hpp"
7 #include "../model/Model.hpp"
8 #include "../world/ChunkIndex.hpp"
9 #include "../world/Entity.hpp"
10 #include "../world/World.hpp"
15 #include <glm/gtx/io.hpp>
23 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
26 , buffer_size(Chunk::BlockSize() + 10)
27 , buffer(new uint8_t[buffer_size])
29 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
40 ChunkTransmitter::~ChunkTransmitter() {
44 bool ChunkTransmitter::Idle() const noexcept {
45 return !Transmitting() && !Waiting();
48 bool ChunkTransmitter::Transmitting() const noexcept {
49 return cursor < num_packets;
52 void ChunkTransmitter::Transmit() {
53 if (cursor < num_packets) {
59 bool ChunkTransmitter::Waiting() const noexcept {
60 return confirm_wait > 0;
63 void ChunkTransmitter::Ack(uint16_t seq) {
67 if (seq == begin_packet) {
75 for (int i = 0, end = data_packets.size(); i < end; ++i) {
76 if (seq == data_packets[i]) {
87 void ChunkTransmitter::Nack(uint16_t seq) {
91 if (seq == begin_packet) {
95 for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
96 if (seq == data_packets[i]) {
103 void ChunkTransmitter::Abort() {
104 if (!current) return;
109 data_packets.clear();
113 void ChunkTransmitter::Send(Chunk &chunk) {
114 // abort current chunk, if any
120 // load new chunk data
122 buffer_len = buffer_size;
123 if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
124 // compression failed, send it uncompressed
125 buffer_len = Chunk::BlockSize();
126 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
130 num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
131 data_packets.resize(num_packets, -1);
137 void ChunkTransmitter::SendBegin() {
138 uint32_t flags = compressed;
139 auto pack = conn.Prepare<Packet::ChunkBegin>();
140 pack.WriteTransmissionId(trans_id);
141 pack.WriteFlags(flags);
142 pack.WriteChunkCoords(current->Position());
143 pack.WriteDataSize(buffer_len);
144 if (begin_packet == -1) {
147 begin_packet = conn.Send();
150 void ChunkTransmitter::SendData(size_t i) {
151 int pos = i * packet_len;
152 int len = min(packet_len, buffer_len - pos);
153 const uint8_t *data = &buffer[pos];
155 auto pack = conn.Prepare<Packet::ChunkData>();
156 pack.WriteTransmissionId(trans_id);
157 pack.WriteDataOffset(pos);
158 pack.WriteDataSize(len);
159 pack.WriteData(data, len);
161 if (data_packets[i] == -1) {
164 data_packets[i] = conn.Send();
167 void ChunkTransmitter::Release() {
175 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
179 , player_model(nullptr)
183 , entity_updates_skipped(0)
184 , player_update_state()
185 , player_update_pack(0)
186 , player_update_timer(1500)
191 conn.SetHandler(this);
194 ClientConnection::~ClientConnection() {
198 void ClientConnection::Update(int dt) {
200 if (Disconnected()) {
205 auto global_iter = server.GetWorld().Entities().begin();
206 auto global_end = server.GetWorld().Entities().end();
207 auto local_iter = spawns.begin();
208 auto local_end = spawns.end();
210 while (global_iter != global_end && local_iter != local_end) {
211 if (global_iter->ID() == local_iter->entity->ID()) {
213 if (CanDespawn(*global_iter)) {
214 SendDespawn(*local_iter);
215 } else if (SendingUpdates()) {
217 QueueUpdate(*local_iter);
221 } else if (global_iter->ID() < local_iter->entity->ID()) {
222 // global entity was inserted
223 if (CanSpawn(*global_iter)) {
224 auto spawned = spawns.emplace(local_iter, *global_iter);
229 // global entity was removed
230 SendDespawn(*local_iter);
236 while (global_iter != global_end) {
237 if (CanSpawn(*global_iter)) {
238 spawns.emplace_back(*global_iter);
239 SendSpawn(spawns.back());
245 while (local_iter != local_end) {
246 SendDespawn(*local_iter);
254 if (conn.ShouldPing()) {
255 conn.SendPing(server.GetPacket(), server.GetSocket());
259 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
266 ClientConnection::SpawnStatus::~SpawnStatus() {
270 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
272 &e != &PlayerEntity() &&
274 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
277 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
280 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
283 uint16_t ClientConnection::Send() {
284 return conn.Send(server.GetPacket(), server.GetSocket());
287 uint16_t ClientConnection::Send(size_t len) {
288 server.GetPacket().len = sizeof(Packet::Header) + len;
292 void ClientConnection::SendSpawn(SpawnStatus &status) {
293 // don't double spawn
294 if (status.spawn_pack != -1) return;
296 auto pack = Prepare<Packet::SpawnEntity>();
297 pack.WriteEntity(*status.entity);
298 status.spawn_pack = Send();
302 void ClientConnection::SendDespawn(SpawnStatus &status) {
303 // don't double despawn
304 if (status.despawn_pack != -1) return;
306 auto pack = Prepare<Packet::DespawnEntity>();
307 pack.WriteEntityID(status.entity->ID());
308 status.despawn_pack = Send();
312 bool ClientConnection::SendingUpdates() const noexcept {
313 return entity_updates_skipped >= NetStat().SuggestedPacketSkip();
316 void ClientConnection::QueueUpdate(SpawnStatus &status) {
317 // don't send updates while spawn not ack'd or despawn sent
318 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
319 entity_updates.push_back(&status);
323 void ClientConnection::SendUpdates() {
324 if (!SendingUpdates()) {
325 entity_updates.clear();
326 ++entity_updates_skipped;
329 auto base = PlayerChunks().Base();
330 auto pack = Prepare<Packet::EntityUpdate>();
331 pack.WriteChunkBase(base);
333 for (SpawnStatus *status : entity_updates) {
334 pack.WriteEntity(*status->entity, base, entity_pos);
336 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
337 pack.WriteEntityCount(entity_pos);
338 Send(Packet::EntityUpdate::GetSize(entity_pos));
339 pack = Prepare<Packet::EntityUpdate>();
343 if (entity_pos > 0) {
344 pack.WriteEntityCount(entity_pos);
345 Send(Packet::EntityUpdate::GetSize(entity_pos));
347 entity_updates.clear();
348 entity_updates_skipped = 0;
351 void ClientConnection::CheckPlayerFix() {
352 // player_update_state's position holds the client's most recent prediction
353 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
354 float dist_squared = dot(diff, diff);
356 // if client's prediction is off by more than 1cm, send
357 // our (authoritative) state back so it can fix it
358 constexpr float fix_thresh = 0.0001f;
360 if (dist_squared > fix_thresh) {
361 auto pack = Prepare<Packet::PlayerCorrection>();
362 pack.WritePacketSeq(player_update_pack);
363 pack.WritePlayer(PlayerEntity());
370 struct QueueCompare {
371 explicit QueueCompare(const glm::ivec3 &base)
373 bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
374 const glm::ivec3 ld(left - base);
375 const glm::ivec3 rd(right - base);
377 ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
378 rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
380 const glm::ivec3 &base;
385 void ClientConnection::CheckChunkQueue() {
386 if (PlayerChunks().Base() != old_base) {
387 Chunk::Pos begin = PlayerChunks().CoordsBegin();
388 Chunk::Pos end = PlayerChunks().CoordsEnd();
389 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
390 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
391 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
392 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
393 chunk_queue.push_back(pos);
398 old_base = PlayerChunks().Base();
399 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
401 if (transmitter.Transmitting()) {
402 transmitter.Transmit();
405 if (transmitter.Idle()) {
407 constexpr int max = 64;
408 while (count < max && !chunk_queue.empty()) {
409 Chunk::Pos pos = chunk_queue.front();
410 chunk_queue.pop_front();
411 if (PlayerChunks().InRange(pos)) {
412 Chunk *chunk = PlayerChunks().Get(pos);
414 transmitter.Send(*chunk);
417 chunk_queue.push_back(pos);
425 void ClientConnection::AttachPlayer(Player &player) {
427 input.reset(new DirectInput(server.GetWorld(), player, server));
428 PlayerEntity().Ref();
430 old_base = PlayerChunks().Base();
431 Chunk::Pos begin = PlayerChunks().CoordsBegin();
432 Chunk::Pos end = PlayerChunks().CoordsEnd();
433 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
434 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
435 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
436 chunk_queue.push_back(pos);
440 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
441 // TODO: should the server do this?
442 if (HasPlayerModel()) {
443 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
446 string msg = "player \"" + player.Name() + "\" joined";
448 server.DistributeMessage(0, 0, msg);
451 void ClientConnection::DetachPlayer() {
452 if (!HasPlayer()) return;
453 string msg = "player \"" + input->GetPlayer().Name() + "\" left";
455 server.DistributeMessage(0, 0, msg);
457 server.GetWorldSave().Write(input->GetPlayer());
458 PlayerEntity().Kill();
459 PlayerEntity().UnRef();
466 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
469 m.Instantiate(PlayerEntity().GetModel());
473 bool ClientConnection::HasPlayerModel() const noexcept {
477 const Model &ClientConnection::GetPlayerModel() const noexcept {
478 return *player_model;
481 void ClientConnection::OnPacketReceived(uint16_t seq) {
482 if (transmitter.Waiting()) {
483 transmitter.Ack(seq);
485 if (!confirm_wait) return;
486 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
487 if (seq == iter->spawn_pack) {
488 iter->spawn_pack = -1;
492 if (seq == iter->despawn_pack) {
500 void ClientConnection::OnPacketLost(uint16_t seq) {
501 if (transmitter.Waiting()) {
502 transmitter.Nack(seq);
504 if (!confirm_wait) return;
505 for (SpawnStatus &status : spawns) {
506 if (seq == status.spawn_pack) {
507 status.spawn_pack = -1;
512 if (seq == status.despawn_pack) {
513 status.despawn_pack = -1;
521 void ClientConnection::On(const Packet::Login &pack) {
523 pack.ReadPlayerName(name);
525 Player *new_player = server.JoinPlayer(name);
529 AttachPlayer(*new_player);
530 cout << "accepted login from player \"" << name << '"' << endl;
531 auto response = Prepare<Packet::Join>();
532 response.WritePlayer(new_player->GetEntity());
533 response.WriteWorldName(server.GetWorld().Name());
535 // set up update tracking
536 player_update_state = new_player->GetEntity().GetState();
537 player_update_pack = pack.Seq();
538 player_update_timer.Reset();
539 player_update_timer.Start();
542 cout << "rejected login from player \"" << name << '"' << endl;
543 Prepare<Packet::Part>();
549 void ClientConnection::On(const Packet::Part &) {
553 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
554 if (!HasPlayer()) return;
555 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
556 bool overdue = player_update_timer.HitOnce();
557 player_update_timer.Reset();
558 if (pack_diff <= 0 && !overdue) {
559 // drop old packets if we have a fairly recent state
562 glm::vec3 movement(0.0f);
566 player_update_pack = pack.Seq();
567 pack.ReadPredictedState(player_update_state);
568 pack.ReadMovement(movement);
569 pack.ReadActions(new_actions);
572 input->SetMovement(movement);
573 input->TurnHead(player_update_state.pitch - input->GetPitch(), player_update_state.yaw - input->GetYaw());
574 input->SelectInventory(slot);
576 if ((new_actions & 0x01) && !(old_actions & 0x01)) {
577 input->StartPrimaryAction();
578 } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
579 input->StopPrimaryAction();
581 if ((new_actions & 0x02) && !(old_actions & 0x02)) {
582 input->StartSecondaryAction();
583 } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
584 input->StopSecondaryAction();
586 if ((new_actions & 0x04) && !(old_actions & 0x04)) {
587 input->StartTertiaryAction();
588 } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
589 input->StopTertiaryAction();
591 old_actions = new_actions;
594 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
595 return HasPlayer() && PlayerChunks().InRange(pos);
598 void ClientConnection::On(const Packet::Message &pack) {
603 pack.ReadReferral(ref);
604 pack.ReadMessage(msg);
606 if (type == 1 && HasPlayer()) {
607 server.DispatchMessage(input->GetPlayer(), msg);
613 const Config::Network &conf,
615 const World::Config &wc,
616 const WorldSave &save)
618 , serv_pack{ -1, nullptr, 0 }
621 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
623 , player_model(nullptr)
625 serv_sock = SDLNet_UDP_Open(conf.port);
627 throw NetError("SDLNet_UDP_Open");
630 serv_pack.data = new Uint8[sizeof(Packet)];
631 serv_pack.maxlen = sizeof(Packet);
635 world.Chunks().UnregisterIndex(spawn_index);
636 delete[] serv_pack.data;
637 SDLNet_UDP_Close(serv_sock);
641 void Server::Handle() {
642 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
644 HandlePacket(serv_pack);
645 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
648 // a boo boo happened
649 throw NetError("SDLNet_UDP_Recv");
653 void Server::HandlePacket(const UDPpacket &udp_pack) {
654 if (udp_pack.len < int(sizeof(Packet::Header))) {
655 // packet too small, drop
658 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
659 if (pack.header.tag != Packet::TAG) {
660 // mistagged packet, drop
664 ClientConnection &client = GetClient(udp_pack.address);
665 client.GetConnection().Received(udp_pack);
668 ClientConnection &Server::GetClient(const IPaddress &addr) {
669 for (ClientConnection &client : clients) {
670 if (client.Matches(addr)) {
674 clients.emplace_back(*this, addr);
675 if (HasPlayerModel()) {
676 clients.back().SetPlayerModel(GetPlayerModel());
678 return clients.back();
681 void Server::Update(int dt) {
682 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
684 if (client->Disconnected()) {
685 client = clients.erase(client);
692 void Server::SetPlayerModel(const Model &m) noexcept {
694 for (ClientConnection &client : clients) {
695 client.SetPlayerModel(m);
699 bool Server::HasPlayerModel() const noexcept {
703 const Model &Server::GetPlayerModel() const noexcept {
704 return *player_model;
707 Player *Server::JoinPlayer(const string &name) {
708 if (spawn_index.MissingChunks() > 0) {
711 Player *player = world.AddPlayer(name);
715 if (save.Exists(*player)) {
723 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
724 chunk.SetBlock(index, block);
725 // TODO: batch chunk changes
726 auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
727 pack.WriteChunkCoords(chunk.Position());
728 pack.WriteBlockCount(uint32_t(1));
729 pack.WriteIndex(index, 0);
730 pack.WriteBlock(chunk.BlockAt(index), 0);
731 GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
732 for (ClientConnection &client : clients) {
733 if (client.ChunkInRange(chunk.Position())) {
739 void Server::DispatchMessage(Player &player, const string &msg) {
743 if (msg[0] == '/' && msg.size() > 1 && msg[1] != '/') {
744 cli.Execute(player, msg.substr(1));
746 DistributeMessage(1, player.GetEntity().ID(), msg);
750 void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
751 auto pack = Packet::Make<Packet::Message>(serv_pack);
752 pack.WriteType(type);
753 pack.WriteReferral(ref);
754 pack.WriteMessage(msg);
755 serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
759 void Server::SendAll() {
760 for (ClientConnection &client : clients) {
761 client.GetConnection().Send(serv_pack, serv_sock);