add sync projectiles

This commit is contained in:
Vlad committed 2026-02-05 13:29:21 +06:00
1 parent 88f68b20ea
commit ec156bd679
7 files changed
+561 -240

No files matched your search

+84
View File
@@ -645,6 +645,11 @@ namespace ZL
// Итерируемся по актуальным данным из extrapolateRemotePlayers
for (auto const& [id, remotePlayer] : latestRemotePlayers) {
// если локально помечен как убитый — пропускаем рендер
if (deadRemotePlayers.find(id) != deadRemotePlayers.end()) {
continue;
}
if (!remotePlayer.canFetchClientStateAtTime(now))
{
continue;
@@ -842,11 +847,16 @@ namespace ZL
if (!uiGameOverShown) {
if (uiManager.pushMenuFromFile("resources/config/game_over.json", this->renderer, CONST_ZIP_FILE)) {
uiManager.setButtonCallback("restartButton", [this](const std::string& name) {
std::string respawnMsg = "RESPAWN:" + std::to_string(networkClient->GetClientId());
networkClient->Send(respawnMsg);
this->shipAlive = true;
this->gameOver = false;
this->uiGameOverShown = false;
this->showExplosion = false;
this->explosionEmitter.setEmissionPoints(std::vector<Vector3f>());
this->deadRemotePlayers.clear();
Environment::shipState.position = Vector3f{ 0, 0, 45000.f };
Environment::shipState.velocity = 0.0f;
@@ -1229,6 +1239,80 @@ namespace ZL
}
}*/
}
// Обработка событий смерти, присланных сервером
auto deaths = networkClient->getPendingDeaths();
if (!deaths.empty()) {
int localId = networkClient->GetClientId();
std::cout << "Client: Received " << deaths.size() << " death events" << std::endl;
for (const auto& d : deaths) {
std::cout << "Client: Processing death - target=" << d.targetId
<< ", killer=" << d.killerId << ", pos=("
<< d.position.x() << ", " << d.position.y() << ", " << d.position.z() << ")" << std::endl;
showExplosion = true;
explosionEmitter.setUseWorldSpace(true);
explosionEmitter.setEmissionPoints(std::vector<Vector3f>{ d.position });
explosionEmitter.emit();
lastExplosionTime = SDL_GetTicks64();
std::cout << "Client: Explosion emitted at (" << d.position.x() << ", "
<< d.position.y() << ", " << d.position.z() << ")" << std::endl;
if (d.targetId == localId) {
std::cout << "Client: Local ship destroyed!" << std::endl;
shipAlive = false;
gameOver = true;
Environment::shipState.velocity = 0.0f;
if (!uiGameOverShown) {
if (uiManager.pushMenuFromFile("resources/config/game_over.json",
this->renderer, CONST_ZIP_FILE)) {
uiManager.setButtonCallback("restartButton", [this](const std::string& name) {
std::cout << "Client: Restart button clicked, sending RESPAWN" << std::endl;
std::string respawnMsg = "RESPAWN:" + std::to_string(networkClient->GetClientId());
networkClient->Send(respawnMsg);
this->shipAlive = true;
this->gameOver = false;
this->uiGameOverShown = false;
this->showExplosion = false;
this->explosionEmitter.setEmissionPoints(std::vector<Vector3f>());
this->deadRemotePlayers.clear();
Environment::shipState.position = Vector3f{ 0, 0, 45000.f };
Environment::shipState.velocity = 0.0f;
Environment::shipState.rotation = Eigen::Matrix3f::Identity();
Environment::inverseShipMatrix = Eigen::Matrix3f::Identity();
Environment::zoom = DEFAULT_ZOOM;
Environment::tapDownHold = false;
uiManager.popMenu();
std::cerr << "Game restarted\n";
});
uiManager.setButtonCallback("gameOverExitButton", [this](const std::string& name) {
Environment::exitGameLoop = true;
});
uiGameOverShown = true;
}
}
}
else {
deadRemotePlayers.insert(d.targetId);
std::cout << "Marked remote player " << d.targetId << " as dead" << std::endl;
}
}
}
auto respawns = networkClient->getPendingRespawns();
if (!respawns.empty()) {
for (const auto& respawnId : respawns) {
deadRemotePlayers.erase(respawnId);
std::cout << "Client: Remote player " << respawnId << " respawned, removed from dead list" << std::endl;
}
}
}
}
+2 -1
View File
@@ -10,7 +10,7 @@
#include "utils/TaskManager.h"
#include "network/NetworkInterface.h"
#include <queue>
#include <unordered_set>
namespace ZL {
@@ -105,6 +105,7 @@ namespace ZL {
const uint64_t explosionDurationMs = 500;
bool serverBoxesApplied = false;
std::unordered_set<int> deadRemotePlayers;
};
+10 -3
View File
@@ -1,6 +1,5 @@
#pragma once
// WebSocketClient.h
#include "NetworkInterface.h"
#include <queue>
@@ -16,8 +15,8 @@ namespace ZL {
void Send(const std::string& message) override;
bool IsConnected() const override { return true; }
int GetClientId() const { return 1; }
std::vector<ProjectileInfo> getPendingProjectiles();
int GetClientId() const override { return 1; }
std::vector<ProjectileInfo> getPendingProjectiles() override;
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
return std::unordered_map<int, ClientStateInterval>();
@@ -26,5 +25,13 @@ namespace ZL {
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
return {};
}
std::vector<DeathInfo> getPendingDeaths() override {
return {};
}
std::vector<int> getPendingRespawns() override {
return {};
}
};
}
+30 -19
View File
@@ -7,26 +7,37 @@
// NetworkInterface.h - »нтерфейс дл¤ разных типов соединений
namespace ZL {
struct ProjectileInfo {
int shooterId = -1;
uint64_t clientTime = 0;
Eigen::Vector3f position = Eigen::Vector3f::Zero();
//Eigen::Vector3f direction = Eigen::Vector3f::Zero();
Eigen::Matrix3f rotation = Eigen::Matrix3f::Identity();
float velocity = 0;
};
struct ProjectileInfo {
int shooterId = -1;
uint64_t clientTime = 0;
Eigen::Vector3f position = Eigen::Vector3f::Zero();
//Eigen::Vector3f direction = Eigen::Vector3f::Zero();
Eigen::Matrix3f rotation = Eigen::Matrix3f::Identity();
float velocity = 0;
};
class INetworkClient {
public:
virtual ~INetworkClient() = default;
virtual void Connect(const std::string& host, uint16_t port) = 0;
virtual void Send(const std::string& message) = 0;
virtual bool IsConnected() const = 0;
virtual void Poll() = 0; // ƒл¤ обработки вход¤щих пакетов
virtual std::unordered_map<int, ClientStateInterval> getRemotePlayers() = 0;
struct DeathInfo {
int targetId = -1;
uint64_t serverTime = 0;
Eigen::Vector3f position = Eigen::Vector3f::Zero();
int killerId = -1;
};
virtual std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() = 0;
class INetworkClient {
public:
virtual ~INetworkClient() = default;
virtual void Connect(const std::string& host, uint16_t port) = 0;
virtual void Send(const std::string& message) = 0;
virtual bool IsConnected() const = 0;
virtual void Poll() = 0; // ƒл¤ обработки вход¤щих пакетов
virtual std::unordered_map<int, ClientStateInterval> getRemotePlayers() = 0;
virtual std::vector<ProjectileInfo> getPendingProjectiles() = 0;
};
virtual std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() = 0;
virtual std::vector<ProjectileInfo> getPendingProjectiles() = 0;
virtual std::vector<DeathInfo> getPendingDeaths() = 0;
virtual std::vector<int> getPendingRespawns() = 0;
virtual int GetClientId() const { return -1; }
};
}
+55 -1
View File
@@ -71,6 +71,20 @@ namespace ZL {
return copy;
}
std::vector<DeathInfo> WebSocketClient::getPendingDeaths() {
std::lock_guard<std::mutex> lock(deathsMutex_);
auto copy = pendingDeaths_;
pendingDeaths_.clear();
return copy;
}
std::vector<int> WebSocketClient::getPendingRespawns() {
std::lock_guard<std::mutex> lock(respawnMutex_);
auto copy = pendingRespawns_;
pendingRespawns_.clear();
return copy;
}
void WebSocketClient::Poll() {
std::lock_guard<std::mutex> lock(queueMutex);
@@ -125,6 +139,25 @@ namespace ZL {
}
continue;
}
if (msg.rfind("RESPAWN_ACK:", 0) == 0) {
auto parts = split(msg, ':');
if (parts.size() >= 2) {
try {
int respawnedPlayerId = std::stoi(parts[1]);
{
std::lock_guard<std::mutex> rLock(respawnMutex_);
pendingRespawns_.push_back(respawnedPlayerId);
}
{
std::lock_guard<std::mutex> pLock(playersMutex);
remotePlayers.erase(respawnedPlayerId);
}
std::cout << "Client: Received RESPAWN_ACK for player " << respawnedPlayerId << std::endl;
}
catch (...) {}
}
continue;
}
if (msg.rfind("PROJECTILE:", 0) == 0) {
auto parts = split(msg, ':');
@@ -150,8 +183,29 @@ namespace ZL {
std::lock_guard<std::mutex> pl(projMutex_);
pendingProjectiles_.push_back(pi);
}
catch (...) {
catch (...) {}
}
continue;
}
if (msg.rfind("DEAD:", 0) == 0) {
auto parts = split(msg, ':');
if (parts.size() >= 7) {
try {
DeathInfo di;
di.serverTime = std::stoull(parts[1]);
di.targetId = std::stoi(parts[2]);
di.position = Eigen::Vector3f(
std::stof(parts[3]),
std::stof(parts[4]),
std::stof(parts[5])
);
di.killerId = std::stoi(parts[6]);
std::lock_guard<std::mutex> dl(deathsMutex_);
pendingDeaths_.push_back(di);
}
catch (...) {}
}
continue;
}
+49 -42
View File
@@ -2,7 +2,6 @@
#ifdef NETWORK
// WebSocketClient.h
#include "NetworkInterface.h"
#include <queue>
#include <boost/beast/core.hpp>
@@ -12,62 +11,70 @@
namespace ZL {
class WebSocketClient : public INetworkClient {
private:
// Переиспользуем io_context из TaskManager
boost::asio::io_context& ioc_;
class WebSocketClient : public INetworkClient {
private:
// Переиспользуем io_context из TaskManager
boost::asio::io_context& ioc_;
// Объекты переехали в члены класса
std::unique_ptr<boost::beast::websocket::stream<boost::beast::tcp_stream>> ws_;
boost::beast::flat_buffer buffer_;
// Объекты переехали в члены класса
std::unique_ptr<boost::beast::websocket::stream<boost::beast::tcp_stream>> ws_;
boost::beast::flat_buffer buffer_;
std::queue<std::string> messageQueue;
std::mutex queueMutex; // Защита для messageQueue
std::queue<std::string> messageQueue;
std::mutex queueMutex; // Защита для messageQueue
std::queue<std::shared_ptr<std::string>> writeQueue_;
bool isWriting_ = false;
std::mutex writeMutex_; // Отдельный мьютекс для очереди записи
std::queue<std::shared_ptr<std::string>> writeQueue_;
bool isWriting_ = false;
std::mutex writeMutex_; // Отдельный мьютекс для очереди записи
bool connected = false;
int clientId = -1;
bool connected = false;
int clientId = -1;
std::unordered_map<int, ClientStateInterval> remotePlayers;
std::mutex playersMutex;
std::unordered_map<int, ClientStateInterval> remotePlayers;
std::mutex playersMutex;
// Серверные коробки
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> serverBoxes_;
std::mutex boxesMutex;
// Серверные коробки
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> serverBoxes_;
std::mutex boxesMutex;
std::vector<ProjectileInfo> pendingProjectiles_;
std::mutex projMutex_;
std::vector<ProjectileInfo> pendingProjectiles_;
std::mutex projMutex_;
void startAsyncRead();
void processIncomingMessage(const std::string& msg);
std::vector<DeathInfo> pendingDeaths_;
std::mutex deathsMutex_;
public:
explicit WebSocketClient(boost::asio::io_context& ioc) : ioc_(ioc) {}
std::vector<int> pendingRespawns_;
std::mutex respawnMutex_;
void Connect(const std::string& host, uint16_t port) override;
void startAsyncRead();
void processIncomingMessage(const std::string& msg);
void Poll() override;
public:
explicit WebSocketClient(boost::asio::io_context& ioc) : ioc_(ioc) {}
void Send(const std::string& message) override;
void doWrite();
void Connect(const std::string& host, uint16_t port) override;
bool IsConnected() const override { return connected; }
int GetClientId() const { return clientId; }
void Poll() override;
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
std::lock_guard<std::mutex> lock(playersMutex);
return remotePlayers;
}
void Send(const std::string& message) override;
void doWrite();
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
std::lock_guard<std::mutex> lock(boxesMutex);
return serverBoxes_;
}
bool IsConnected() const override { return connected; }
int GetClientId() const override { return clientId; }
std::vector<ProjectileInfo> getPendingProjectiles() override;
};
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
std::lock_guard<std::mutex> lock(playersMutex);
return remotePlayers;
}
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
std::lock_guard<std::mutex> lock(boxesMutex);
return serverBoxes_;
}
std::vector<ProjectileInfo> getPendingProjectiles() override;
std::vector<DeathInfo> getPendingDeaths() override;
std::vector<int> getPendingRespawns() override;
};
}
#endif