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 , player_update_state()
184 , player_update_pack(0)
185 , player_update_timer(1500)
190 conn.SetHandler(this);
193 ClientConnection::~ClientConnection() {
197 void ClientConnection::Update(int dt) {
199 if (Disconnected()) {
204 auto global_iter = server.GetWorld().Entities().begin();
205 auto global_end = server.GetWorld().Entities().end();
206 auto local_iter = spawns.begin();
207 auto local_end = spawns.end();
209 while (global_iter != global_end && local_iter != local_end) {
210 if (global_iter->ID() == local_iter->entity->ID()) {
212 if (CanDespawn(*global_iter)) {
213 SendDespawn(*local_iter);
216 QueueUpdate(*local_iter);
220 } else if (global_iter->ID() < local_iter->entity->ID()) {
221 // global entity was inserted
222 if (CanSpawn(*global_iter)) {
223 auto spawned = spawns.emplace(local_iter, *global_iter);
228 // global entity was removed
229 SendDespawn(*local_iter);
235 while (global_iter != global_end) {
236 if (CanSpawn(*global_iter)) {
237 spawns.emplace_back(*global_iter);
238 SendSpawn(spawns.back());
244 while (local_iter != local_end) {
245 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 void ClientConnection::QueueUpdate(SpawnStatus &status) {
313 // don't send updates while spawn not ack'd or despawn sent
314 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
315 entity_updates.push_back(&status);
319 void ClientConnection::SendUpdates() {
320 auto pack = Prepare<Packet::EntityUpdate>();
322 for (SpawnStatus *status : entity_updates) {
323 pack.WriteEntity(*status->entity, entity_pos);
325 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
326 pack.WriteEntityCount(entity_pos);
327 Send(Packet::EntityUpdate::GetSize(entity_pos));
328 pack = Prepare<Packet::EntityUpdate>();
332 if (entity_pos > 0) {
333 pack.WriteEntityCount(entity_pos);
334 Send(Packet::EntityUpdate::GetSize(entity_pos));
336 entity_updates.clear();
339 void ClientConnection::CheckPlayerFix() {
340 // player_update_state's position holds the client's most recent prediction
341 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
342 float dist_squared = dot(diff, diff);
344 // if client's prediction is off by more than 1cm, send
345 // our (authoritative) state back so it can fix it
346 constexpr float fix_thresh = 0.0001f;
348 if (dist_squared > fix_thresh) {
349 auto pack = Prepare<Packet::PlayerCorrection>();
350 pack.WritePacketSeq(player_update_pack);
351 pack.WritePlayer(PlayerEntity());
358 struct QueueCompare {
359 explicit QueueCompare(const glm::ivec3 &base)
361 bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
362 const glm::ivec3 ld(left - base);
363 const glm::ivec3 rd(right - base);
365 ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
366 rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
368 const glm::ivec3 &base;
373 void ClientConnection::CheckChunkQueue() {
374 if (PlayerChunks().Base() != old_base) {
375 Chunk::Pos begin = PlayerChunks().CoordsBegin();
376 Chunk::Pos end = PlayerChunks().CoordsEnd();
377 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
378 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
379 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
380 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
381 chunk_queue.push_back(pos);
386 old_base = PlayerChunks().Base();
387 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
389 if (transmitter.Transmitting()) {
390 transmitter.Transmit();
393 if (transmitter.Idle()) {
395 constexpr int max = 64;
396 while (count < max && !chunk_queue.empty()) {
397 Chunk::Pos pos = chunk_queue.front();
398 chunk_queue.pop_front();
399 if (PlayerChunks().InRange(pos)) {
400 Chunk *chunk = PlayerChunks().Get(pos);
402 transmitter.Send(*chunk);
405 chunk_queue.push_back(pos);
413 void ClientConnection::AttachPlayer(Player &player) {
415 input.reset(new DirectInput(server.GetWorld(), player, server));
416 PlayerEntity().Ref();
418 old_base = PlayerChunks().Base();
419 Chunk::Pos begin = PlayerChunks().CoordsBegin();
420 Chunk::Pos end = PlayerChunks().CoordsEnd();
421 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
422 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
423 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
424 chunk_queue.push_back(pos);
428 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
429 // TODO: should the server do this?
430 if (HasPlayerModel()) {
431 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
434 cout << "player \"" << player.Name() << "\" joined" << endl;
437 void ClientConnection::DetachPlayer() {
438 if (!HasPlayer()) return;
439 cout << "player \"" << input->GetPlayer().Name() << "\" left" << endl;
440 server.GetWorldSave().Write(input->GetPlayer());
441 PlayerEntity().Kill();
442 PlayerEntity().UnRef();
449 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
452 m.Instantiate(PlayerEntity().GetModel());
456 bool ClientConnection::HasPlayerModel() const noexcept {
460 const Model &ClientConnection::GetPlayerModel() const noexcept {
461 return *player_model;
464 void ClientConnection::OnPacketReceived(uint16_t seq) {
465 if (transmitter.Waiting()) {
466 transmitter.Ack(seq);
468 if (!confirm_wait) return;
469 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
470 if (seq == iter->spawn_pack) {
471 iter->spawn_pack = -1;
475 if (seq == iter->despawn_pack) {
483 void ClientConnection::OnPacketLost(uint16_t seq) {
484 if (transmitter.Waiting()) {
485 transmitter.Nack(seq);
487 if (!confirm_wait) return;
488 for (SpawnStatus &status : spawns) {
489 if (seq == status.spawn_pack) {
490 status.spawn_pack = -1;
495 if (seq == status.despawn_pack) {
496 status.despawn_pack = -1;
504 void ClientConnection::On(const Packet::Login &pack) {
506 pack.ReadPlayerName(name);
508 Player *new_player = server.JoinPlayer(name);
512 AttachPlayer(*new_player);
513 cout << "accepted login from player \"" << name << '"' << endl;
514 auto response = Prepare<Packet::Join>();
515 response.WritePlayer(new_player->GetEntity());
516 response.WriteWorldName(server.GetWorld().Name());
518 // set up update tracking
519 player_update_state = new_player->GetEntity().GetState();
520 player_update_pack = pack.Seq();
521 player_update_timer.Reset();
522 player_update_timer.Start();
525 cout << "rejected login from player \"" << name << '"' << endl;
526 Prepare<Packet::Part>();
532 void ClientConnection::On(const Packet::Part &) {
536 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
537 if (!HasPlayer()) return;
538 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
539 bool overdue = player_update_timer.HitOnce();
540 player_update_timer.Reset();
541 if (pack_diff <= 0 && !overdue) {
542 // drop old packets if we have a fairly recent state
545 glm::vec3 movement(0.0f);
551 player_update_pack = pack.Seq();
552 pack.ReadPredictedState(player_update_state);
553 pack.ReadMovement(movement);
554 pack.ReadPitch(pitch);
556 pack.ReadActions(new_actions);
559 input->SetMovement(movement);
560 input->TurnHead(pitch - input->GetPitch(), yaw - input->GetYaw());
561 input->SelectInventory(slot);
563 if ((new_actions & 0x01) && !(old_actions & 0x01)) {
564 input->StartPrimaryAction();
565 } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
566 input->StopPrimaryAction();
568 if ((new_actions & 0x02) && !(old_actions & 0x02)) {
569 input->StartSecondaryAction();
570 } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
571 input->StopSecondaryAction();
573 if ((new_actions & 0x04) && !(old_actions & 0x04)) {
574 input->StartTertiaryAction();
575 } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
576 input->StopTertiaryAction();
578 old_actions = new_actions;
581 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
582 return HasPlayer() && PlayerChunks().InRange(pos);
587 const Config::Network &conf,
589 const World::Config &wc,
590 const WorldSave &save)
592 , serv_pack{ -1, nullptr, 0 }
595 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
597 , player_model(nullptr) {
598 serv_sock = SDLNet_UDP_Open(conf.port);
600 throw NetError("SDLNet_UDP_Open");
603 serv_pack.data = new Uint8[sizeof(Packet)];
604 serv_pack.maxlen = sizeof(Packet);
608 world.Chunks().UnregisterIndex(spawn_index);
609 delete[] serv_pack.data;
610 SDLNet_UDP_Close(serv_sock);
614 void Server::Handle() {
615 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
617 HandlePacket(serv_pack);
618 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
621 // a boo boo happened
622 throw NetError("SDLNet_UDP_Recv");
626 void Server::HandlePacket(const UDPpacket &udp_pack) {
627 if (udp_pack.len < int(sizeof(Packet::Header))) {
628 // packet too small, drop
631 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
632 if (pack.header.tag != Packet::TAG) {
633 // mistagged packet, drop
637 ClientConnection &client = GetClient(udp_pack.address);
638 client.GetConnection().Received(udp_pack);
641 ClientConnection &Server::GetClient(const IPaddress &addr) {
642 for (ClientConnection &client : clients) {
643 if (client.Matches(addr)) {
647 clients.emplace_back(*this, addr);
648 if (HasPlayerModel()) {
649 clients.back().SetPlayerModel(GetPlayerModel());
651 return clients.back();
654 void Server::Update(int dt) {
655 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
657 if (client->Disconnected()) {
658 client = clients.erase(client);
665 void Server::SetPlayerModel(const Model &m) noexcept {
667 for (ClientConnection &client : clients) {
668 client.SetPlayerModel(m);
672 bool Server::HasPlayerModel() const noexcept {
676 const Model &Server::GetPlayerModel() const noexcept {
677 return *player_model;
680 Player *Server::JoinPlayer(const string &name) {
681 if (spawn_index.MissingChunks() > 0) {
684 Player *player = world.AddPlayer(name);
688 if (save.Exists(*player)) {
696 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
697 chunk.SetBlock(index, block);
698 // TODO: batch chunk changes
699 auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
700 pack.WriteChunkCoords(chunk.Position());
701 pack.WriteBlockCount(uint32_t(1));
702 pack.WriteIndex(index, 0);
703 pack.WriteBlock(chunk.BlockAt(index), 0);
704 GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
705 for (ClientConnection &client : clients) {
706 if (client.ChunkInRange(chunk.Position())) {