1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
5 #include "../app/init.hpp"
6 #include "../model/CompositeModel.hpp"
7 #include "../world/ChunkIndex.hpp"
8 #include "../world/Entity.hpp"
9 #include "../world/World.hpp"
13 #include <glm/gtx/io.hpp>
21 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
24 , buffer_size(Chunk::BlockSize() + 10)
25 , buffer(new uint8_t[buffer_size])
27 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
38 ChunkTransmitter::~ChunkTransmitter() {
42 bool ChunkTransmitter::Idle() const noexcept {
43 return !Transmitting() && !Waiting();
46 bool ChunkTransmitter::Transmitting() const noexcept {
47 return cursor < num_packets;
50 void ChunkTransmitter::Transmit() {
51 if (cursor < num_packets) {
57 bool ChunkTransmitter::Waiting() const noexcept {
58 return confirm_wait > 0;
61 void ChunkTransmitter::Ack(uint16_t seq) {
65 if (seq == begin_packet) {
73 for (int i = 0, end = data_packets.size(); i < end; ++i) {
74 if (seq == data_packets[i]) {
85 void ChunkTransmitter::Nack(uint16_t seq) {
89 if (seq == begin_packet) {
93 for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
94 if (seq == data_packets[i]) {
101 void ChunkTransmitter::Abort() {
102 if (!current) return;
107 data_packets.clear();
111 void ChunkTransmitter::Send(Chunk &chunk) {
112 // abort current chunk, if any
118 // load new chunk data
120 buffer_len = buffer_size;
121 if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
122 // compression failed, send it uncompressed
123 buffer_len = Chunk::BlockSize();
124 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
128 num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
129 data_packets.resize(num_packets, -1);
135 void ChunkTransmitter::SendBegin() {
136 uint32_t flags = compressed;
137 auto pack = conn.Prepare<Packet::ChunkBegin>();
138 pack.WriteTransmissionId(trans_id);
139 pack.WriteFlags(flags);
140 pack.WriteChunkCoords(current->Position());
141 pack.WriteDataSize(buffer_len);
142 if (begin_packet == -1) {
145 begin_packet = conn.Send();
148 void ChunkTransmitter::SendData(size_t i) {
149 int pos = i * packet_len;
150 int len = min(packet_len, buffer_len - pos);
151 const uint8_t *data = &buffer[pos];
153 auto pack = conn.Prepare<Packet::ChunkData>();
154 pack.WriteTransmissionId(trans_id);
155 pack.WriteDataOffset(pos);
156 pack.WriteDataSize(len);
157 pack.WriteData(data, len);
159 if (data_packets[i] == -1) {
162 data_packets[i] = conn.Send();
165 void ChunkTransmitter::Release() {
173 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
177 , player_model(nullptr)
181 , player_update_state()
182 , player_update_pack(0)
183 , player_update_timer(1500)
188 conn.SetHandler(this);
191 ClientConnection::~ClientConnection() {
195 void ClientConnection::Update(int dt) {
197 if (Disconnected()) {
202 auto global_iter = server.GetWorld().Entities().begin();
203 auto global_end = server.GetWorld().Entities().end();
204 auto local_iter = spawns.begin();
205 auto local_end = spawns.end();
207 while (global_iter != global_end && local_iter != local_end) {
208 if (global_iter->ID() == local_iter->entity->ID()) {
210 if (CanDespawn(*global_iter)) {
211 SendDespawn(*local_iter);
214 QueueUpdate(*local_iter);
218 } else if (global_iter->ID() < local_iter->entity->ID()) {
219 // global entity was inserted
220 if (CanSpawn(*global_iter)) {
221 auto spawned = spawns.emplace(local_iter, *global_iter);
226 // global entity was removed
227 SendDespawn(*local_iter);
233 while (global_iter != global_end) {
234 if (CanSpawn(*global_iter)) {
235 spawns.emplace_back(*global_iter);
236 SendSpawn(spawns.back());
242 while (local_iter != local_end) {
243 SendDespawn(*local_iter);
252 if (conn.ShouldPing()) {
253 conn.SendPing(server.GetPacket(), server.GetSocket());
257 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
264 ClientConnection::SpawnStatus::~SpawnStatus() {
268 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
270 &e != &PlayerEntity() &&
272 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
275 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
278 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
281 uint16_t ClientConnection::Send() {
282 return conn.Send(server.GetPacket(), server.GetSocket());
285 uint16_t ClientConnection::Send(size_t len) {
286 server.GetPacket().len = len;
290 void ClientConnection::SendSpawn(SpawnStatus &status) {
291 // don't double spawn
292 if (status.spawn_pack != -1) return;
294 auto pack = Prepare<Packet::SpawnEntity>();
295 pack.WriteEntity(*status.entity);
296 status.spawn_pack = Send();
300 void ClientConnection::SendDespawn(SpawnStatus &status) {
301 // don't double despawn
302 if (status.despawn_pack != -1) return;
304 auto pack = Prepare<Packet::DespawnEntity>();
305 pack.WriteEntityID(status.entity->ID());
306 status.despawn_pack = Send();
310 void ClientConnection::QueueUpdate(SpawnStatus &status) {
311 // don't send updates while spawn not ack'd or despawn sent
312 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
313 entity_updates.push_back(&status);
317 void ClientConnection::SendUpdates() {
318 auto pack = Prepare<Packet::EntityUpdate>();
320 for (SpawnStatus *status : entity_updates) {
321 pack.WriteEntity(*status->entity, entity_pos);
323 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
324 pack.WriteEntityCount(entity_pos);
325 Send(Packet::EntityUpdate::GetSize(entity_pos));
326 pack = Prepare<Packet::EntityUpdate>();
330 if (entity_pos > 0) {
331 pack.WriteEntityCount(entity_pos);
332 Send(Packet::EntityUpdate::GetSize(entity_pos));
334 entity_updates.clear();
337 void ClientConnection::CheckPlayerFix() {
338 // player_update_state's position holds the client's most recent prediction
339 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
340 float dist_squared = dot(diff, diff);
342 // if client's prediction is off by more than 1cm, send
343 // our (authoritative) state back so it can fix it
344 constexpr float fix_thresh = 0.0001f;
346 if (dist_squared > fix_thresh) {
347 auto pack = Prepare<Packet::PlayerCorrection>();
348 pack.WritePacketSeq(player_update_pack);
349 pack.WritePlayer(PlayerEntity());
354 void ClientConnection::CheckChunkQueue() {
355 if (PlayerChunks().Base() != old_base) {
356 Chunk::Pos begin = PlayerChunks().CoordsBegin();
357 Chunk::Pos end = PlayerChunks().CoordsEnd();
358 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
359 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
360 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
361 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
362 chunk_queue.push_back(pos);
367 old_base = PlayerChunks().Base();
369 if (transmitter.Transmitting()) {
370 transmitter.Transmit();
373 if (transmitter.Idle()) {
375 constexpr int max = 64;
376 while (count < max && !chunk_queue.empty()) {
377 Chunk::Pos pos = chunk_queue.front();
378 chunk_queue.pop_front();
379 if (PlayerChunks().InRange(pos)) {
380 Chunk *chunk = PlayerChunks().Get(pos);
382 transmitter.Send(*chunk);
385 chunk_queue.push_back(pos);
393 void ClientConnection::AttachPlayer(Player &player) {
395 input.reset(new DirectInput(server.GetWorld(), player, server));
396 PlayerEntity().Ref();
398 old_base = PlayerChunks().Base();
399 Chunk::Pos begin = PlayerChunks().CoordsBegin();
400 Chunk::Pos end = PlayerChunks().CoordsEnd();
401 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
402 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
403 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
404 chunk_queue.push_back(pos);
408 if (HasPlayerModel()) {
409 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
412 cout << "player \"" << player.Name() << "\" joined" << endl;
415 void ClientConnection::DetachPlayer() {
416 if (!HasPlayer()) return;
417 cout << "player \"" << input->GetPlayer().Name() << "\" left" << endl;
418 PlayerEntity().Kill();
419 PlayerEntity().UnRef();
426 void ClientConnection::SetPlayerModel(const CompositeModel &m) noexcept {
429 m.Instantiate(PlayerEntity().GetModel());
433 bool ClientConnection::HasPlayerModel() const noexcept {
437 const CompositeModel &ClientConnection::GetPlayerModel() const noexcept {
438 return *player_model;
441 void ClientConnection::OnPacketReceived(uint16_t seq) {
442 if (transmitter.Waiting()) {
443 transmitter.Ack(seq);
445 if (!confirm_wait) return;
446 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
447 if (seq == iter->spawn_pack) {
448 iter->spawn_pack = -1;
452 if (seq == iter->despawn_pack) {
460 void ClientConnection::OnPacketLost(uint16_t seq) {
461 if (transmitter.Waiting()) {
462 transmitter.Nack(seq);
464 if (!confirm_wait) return;
465 for (SpawnStatus &status : spawns) {
466 if (seq == status.spawn_pack) {
467 status.spawn_pack = -1;
472 if (seq == status.despawn_pack) {
473 status.despawn_pack = -1;
481 void ClientConnection::On(const Packet::Login &pack) {
483 pack.ReadPlayerName(name);
485 Player *new_player = server.GetWorld().AddPlayer(name);
489 AttachPlayer(*new_player);
490 cout << "accepted login from player \"" << name << '"' << endl;
491 auto response = Prepare<Packet::Join>();
492 response.WritePlayer(new_player->GetEntity());
493 response.WriteWorldName(server.GetWorld().Name());
495 // set up update tracking
496 player_update_state = new_player->GetEntity().GetState();
497 player_update_pack = pack.Seq();
498 player_update_timer.Reset();
499 player_update_timer.Start();
502 cout << "rejected login from player \"" << name << '"' << endl;
503 Prepare<Packet::Part>();
509 void ClientConnection::On(const Packet::Part &) {
513 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
514 if (!HasPlayer()) return;
515 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
516 bool overdue = player_update_timer.HitOnce();
517 player_update_timer.Reset();
518 if (pack_diff <= 0 && !overdue) {
519 // drop old packets if we have a fairly recent state
522 glm::vec3 movement(0.0f);
528 player_update_pack = pack.Seq();
529 pack.ReadPredictedState(player_update_state);
530 pack.ReadMovement(movement);
531 pack.ReadPitch(pitch);
533 pack.ReadActions(new_actions);
536 input->SetMovement(movement);
537 input->TurnHead(pitch - input->GetPitch(), yaw - input->GetYaw());
538 input->SelectInventory(slot);
540 if ((new_actions & 0x01) && !(old_actions & 0x01)) {
541 input->StartPrimaryAction();
542 } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
543 input->StopPrimaryAction();
545 if ((new_actions & 0x02) && !(old_actions & 0x02)) {
546 input->StartSecondaryAction();
547 } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
548 input->StopSecondaryAction();
550 if ((new_actions & 0x04) && !(old_actions & 0x04)) {
551 input->StartTertiaryAction();
552 } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
553 input->StopTertiaryAction();
555 old_actions = new_actions;
559 Server::Server(const Config::Network &conf, World &world)
561 , serv_pack{ -1, nullptr, 0 }
564 , player_model(nullptr) {
565 serv_sock = SDLNet_UDP_Open(conf.port);
567 throw NetError("SDLNet_UDP_Open");
570 serv_pack.data = new Uint8[sizeof(Packet)];
571 serv_pack.maxlen = sizeof(Packet);
575 delete[] serv_pack.data;
576 SDLNet_UDP_Close(serv_sock);
580 void Server::Handle() {
581 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
583 HandlePacket(serv_pack);
584 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
587 // a boo boo happened
588 throw NetError("SDLNet_UDP_Recv");
592 void Server::HandlePacket(const UDPpacket &udp_pack) {
593 if (udp_pack.len < int(sizeof(Packet::Header))) {
594 // packet too small, drop
597 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
598 if (pack.header.tag != Packet::TAG) {
599 // mistagged packet, drop
603 ClientConnection &client = GetClient(udp_pack.address);
604 client.GetConnection().Received(udp_pack);
607 ClientConnection &Server::GetClient(const IPaddress &addr) {
608 for (ClientConnection &client : clients) {
609 if (client.Matches(addr)) {
613 clients.emplace_back(*this, addr);
614 if (HasPlayerModel()) {
615 clients.back().SetPlayerModel(GetPlayerModel());
617 return clients.back();
620 void Server::Update(int dt) {
621 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
623 if (client->Disconnected()) {
624 client = clients.erase(client);
631 void Server::SetPlayerModel(const CompositeModel &m) noexcept {
633 for (ClientConnection &client : clients) {
634 client.SetPlayerModel(m);
638 bool Server::HasPlayerModel() const noexcept {
642 const CompositeModel &Server::GetPlayerModel() const noexcept {
643 return *player_model;
646 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
647 chunk.SetBlock(index, block);
648 // TODO: send to clients
649 // also TODO: batch chunk changes