Merge with main
This commit is contained in:
commit
8a374a4231
@ -81,7 +81,7 @@ target_compile_definitions(space-game001 PRIVATE
|
|||||||
PNG_ENABLED
|
PNG_ENABLED
|
||||||
SDL_MAIN_HANDLED
|
SDL_MAIN_HANDLED
|
||||||
NETWORK
|
NETWORK
|
||||||
SIMPLIFIED
|
# SIMPLIFIED
|
||||||
)
|
)
|
||||||
|
|
||||||
# Линкуем с SDL2main, если он вообще установлен
|
# Линкуем с SDL2main, если он вообще установлен
|
||||||
|
|||||||
@ -7,14 +7,30 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
#include <map>
|
#include <map>
|
||||||
|
#include <queue>
|
||||||
|
#include <sstream>
|
||||||
#include <Eigen/Dense>
|
#include <Eigen/Dense>
|
||||||
#define _USE_MATH_DEFINES
|
#define _USE_MATH_DEFINES
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
#include "../src/network/ClientState.h"
|
#include "../src/network/ClientState.h"
|
||||||
#include <random>
|
#include <random>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
#include <chrono>
|
||||||
|
#include <unordered_set>
|
||||||
|
|
||||||
|
namespace beast = boost::beast;
|
||||||
|
namespace http = beast::http;
|
||||||
|
namespace websocket = beast::websocket;
|
||||||
|
namespace net = boost::asio;
|
||||||
|
using tcp = net::ip::tcp;
|
||||||
|
|
||||||
|
struct DeathInfo {
|
||||||
|
int targetId = -1;
|
||||||
|
uint64_t serverTime = 0;
|
||||||
|
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
||||||
|
int killerId = -1;
|
||||||
|
};
|
||||||
|
|
||||||
// Вспомогательный split
|
|
||||||
std::vector<std::string> split(const std::string& s, char delimiter) {
|
std::vector<std::string> split(const std::string& s, char delimiter) {
|
||||||
std::vector<std::string> tokens;
|
std::vector<std::string> tokens;
|
||||||
std::string token;
|
std::string token;
|
||||||
@ -25,122 +41,98 @@ std::vector<std::string> split(const std::string& s, char delimiter) {
|
|||||||
return tokens;
|
return tokens;
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace beast = boost::beast;
|
|
||||||
namespace http = beast::http;
|
|
||||||
namespace websocket = beast::websocket;
|
|
||||||
namespace net = boost::asio;
|
|
||||||
using tcp = net::ip::tcp;
|
|
||||||
|
|
||||||
class Session;
|
|
||||||
|
|
||||||
struct ServerBox {
|
struct ServerBox {
|
||||||
Eigen::Vector3f position;
|
Eigen::Vector3f position;
|
||||||
Eigen::Matrix3f rotation;
|
Eigen::Matrix3f rotation;
|
||||||
float collisionRadius = 2.0f;
|
float collisionRadius = 2.0f;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
struct Projectile {
|
||||||
|
int shooterId = -1;
|
||||||
|
uint64_t spawnMs = 0;
|
||||||
|
Eigen::Vector3f pos;
|
||||||
|
Eigen::Vector3f vel;
|
||||||
|
float lifeMs = 5000.0f;
|
||||||
|
};
|
||||||
|
|
||||||
std::vector<ServerBox> g_serverBoxes;
|
std::vector<ServerBox> g_serverBoxes;
|
||||||
std::mutex g_boxes_mutex;
|
std::mutex g_boxes_mutex;
|
||||||
|
|
||||||
|
std::vector<std::shared_ptr<class Session>> g_sessions;
|
||||||
std::vector<std::shared_ptr<Session>> g_sessions;
|
|
||||||
std::mutex g_sessions_mutex;
|
std::mutex g_sessions_mutex;
|
||||||
|
|
||||||
|
std::vector<Projectile> g_projectiles;
|
||||||
|
std::mutex g_projectiles_mutex;
|
||||||
|
|
||||||
|
std::unordered_set<int> g_dead_players;
|
||||||
|
std::mutex g_dead_mutex;
|
||||||
|
|
||||||
|
class Session;
|
||||||
|
|
||||||
|
void broadcastToAll(const std::string& message);
|
||||||
|
|
||||||
class Session : public std::enable_shared_from_this<Session> {
|
class Session : public std::enable_shared_from_this<Session> {
|
||||||
websocket::stream<beast::tcp_stream> ws_;
|
websocket::stream<beast::tcp_stream> ws_;
|
||||||
beast::flat_buffer buffer_;
|
beast::flat_buffer buffer_;
|
||||||
int id_;
|
int id_;
|
||||||
bool is_writing_ = false;
|
bool is_writing_ = false;
|
||||||
|
std::queue<std::shared_ptr<std::string>> writeQueue_;
|
||||||
|
std::mutex writeMutex_;
|
||||||
|
|
||||||
|
public:
|
||||||
ClientStateInterval timedClientStates;
|
ClientStateInterval timedClientStates;
|
||||||
|
|
||||||
void process_message(const std::string& msg) {
|
explicit Session(tcp::socket&& socket, int id)
|
||||||
auto now_server = std::chrono::system_clock::now();
|
: ws_(std::move(socket)), id_(id) {
|
||||||
auto parts = split(msg, ':');
|
|
||||||
|
|
||||||
if (parts.empty()) {
|
|
||||||
std::cerr << "Empty message received\n";
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string type = parts[0];
|
int get_id() const { return id_; }
|
||||||
|
|
||||||
if (type == "UPD") {
|
bool fetchStateAtTime(std::chrono::system_clock::time_point targetTime, ClientState& outState) const {
|
||||||
if (parts.size() < 16) {
|
if (timedClientStates.canFetchClientStateAtTime(targetTime)) {
|
||||||
std::cerr << "Invalid UPD message: too few parts (" << parts.size() << ")\n";
|
outState = timedClientStates.fetchClientStateAtTime(targetTime);
|
||||||
return;
|
return true;
|
||||||
}
|
}
|
||||||
uint64_t clientTimestamp = std::stoull(parts[1]);
|
return false;
|
||||||
ClientState receivedState;
|
|
||||||
receivedState.id = id_;
|
|
||||||
std::chrono::system_clock::time_point uptime_timepoint{
|
|
||||||
std::chrono::milliseconds(clientTimestamp)
|
|
||||||
};
|
|
||||||
receivedState.lastUpdateServerTime = uptime_timepoint;
|
|
||||||
receivedState.handle_full_sync(parts, 2);
|
|
||||||
retranslateMessage(msg);
|
|
||||||
timedClientStates.add_state(receivedState);
|
|
||||||
}
|
|
||||||
else if (parts[0] == "FIRE") {
|
|
||||||
if (parts.size() < 8) {
|
|
||||||
std::cerr << "Invalid FIRE: too few parts\n";
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
uint64_t clientTime = std::stoull(parts[1]);
|
void send_message(const std::string& msg) {
|
||||||
Eigen::Vector3f pos{
|
auto ss = std::make_shared<std::string>(msg);
|
||||||
std::stof(parts[2]), std::stof(parts[3]), std::stof(parts[4])
|
|
||||||
};
|
|
||||||
Eigen::Vector3f dir{
|
|
||||||
std::stof(parts[5]), std::stof(parts[6]), std::stof(parts[7])
|
|
||||||
};
|
|
||||||
|
|
||||||
int shotCount = 1;
|
|
||||||
if (parts.size() >= 9) {
|
|
||||||
try {
|
|
||||||
shotCount = std::stoi(parts[8]);
|
|
||||||
}
|
|
||||||
catch (...) {
|
|
||||||
shotCount = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string broadcast = "PROJECTILE:" +
|
|
||||||
std::to_string(id_) + ":" +
|
|
||||||
std::to_string(clientTime) + ":" +
|
|
||||||
std::to_string(pos.x()) + ":" +
|
|
||||||
std::to_string(pos.y()) + ":" +
|
|
||||||
std::to_string(pos.z()) + ":" +
|
|
||||||
std::to_string(dir.x()) + ":" +
|
|
||||||
std::to_string(dir.y()) + ":" +
|
|
||||||
std::to_string(dir.z()) + ":" +
|
|
||||||
std::to_string(shotCount);
|
|
||||||
|
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
|
||||||
std::cout << "Player " << id_ << " fired " << shotCount << " shots → broadcasting\n";
|
|
||||||
|
|
||||||
for (auto& session : g_sessions) {
|
|
||||||
if (session->get_id() != id_) {
|
|
||||||
session->send_message(broadcast);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
std::cerr << "Unknown message type: " << type << "\n";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void retranslateMessage(const std::string& msg)
|
|
||||||
{
|
{
|
||||||
std::string event_msg = "EVENT:" + std::to_string(id_) + ":" + msg;
|
std::lock_guard<std::mutex> lock(writeMutex_);
|
||||||
|
writeQueue_.push(ss);
|
||||||
|
}
|
||||||
|
doWrite();
|
||||||
|
}
|
||||||
|
|
||||||
|
void run() {
|
||||||
|
{
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
for (auto& session : g_sessions) {
|
g_sessions.push_back(shared_from_this());
|
||||||
if (session->get_id() != id_) { // Не шлем отправителю
|
|
||||||
session->send_message(event_msg);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ws_.async_accept([self = shared_from_this()](beast::error_code ec) {
|
||||||
|
if (ec) return;
|
||||||
|
std::cout << "Client " << self->id_ << " connected\n";
|
||||||
|
self->init();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
/*
|
||||||
|
void init() {
|
||||||
|
sendBoxesToClient();
|
||||||
|
|
||||||
|
auto timer = std::make_shared<net::steady_timer>(ws_.get_executor());
|
||||||
|
timer->expires_after(std::chrono::milliseconds(100));
|
||||||
|
timer->async_wait([self = shared_from_this(), timer](const boost::system::error_code& ec) {
|
||||||
|
if (!ec) {
|
||||||
|
self->send_message("ID:" + std::to_string(self->id_));
|
||||||
|
self->do_read();
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
void sendBoxesToClient() {
|
void sendBoxesToClient() {
|
||||||
std::lock_guard<std::mutex> lock(g_boxes_mutex);
|
std::lock_guard<std::mutex> lock(g_boxes_mutex);
|
||||||
@ -157,13 +149,73 @@ class Session : public std::enable_shared_from_this<Session> {
|
|||||||
std::to_string(q.z()) + "|";
|
std::to_string(q.z()) + "|";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!boxMsg.empty() && boxMsg.back() == '|') {
|
if (!boxMsg.empty() && boxMsg.back() == '|') boxMsg.pop_back();
|
||||||
boxMsg.pop_back();
|
|
||||||
}
|
|
||||||
|
|
||||||
send_message(boxMsg);
|
send_message(boxMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public:
|
||||||
|
/*
|
||||||
|
explicit Session(tcp::socket&& socket, int id)
|
||||||
|
: ws_(std::move(socket)), id_(id) {
|
||||||
|
}*/
|
||||||
|
|
||||||
|
void init()
|
||||||
|
{
|
||||||
|
sendBoxesToClient();
|
||||||
|
|
||||||
|
auto timer = std::make_shared<net::steady_timer>(ws_.get_executor());
|
||||||
|
timer->expires_after(std::chrono::milliseconds(100));
|
||||||
|
timer->async_wait([self = shared_from_this(), timer](const boost::system::error_code& ec) {
|
||||||
|
if (!ec) {
|
||||||
|
self->send_message("ID:" + std::to_string(self->id_));
|
||||||
|
self->do_read();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
void run() {
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
|
g_sessions.push_back(shared_from_this());
|
||||||
|
}
|
||||||
|
|
||||||
|
ws_.async_accept([self = shared_from_this()](beast::error_code ec) {
|
||||||
|
if (ec) return;
|
||||||
|
std::cout << "Client " << self->id_ << " connected\n";
|
||||||
|
self->init();
|
||||||
|
// self->send_message("ID:" + std::to_string(self->id_));
|
||||||
|
// self->do_read();
|
||||||
|
});
|
||||||
|
}*/
|
||||||
|
|
||||||
|
/*void send_message(std::string msg) {
|
||||||
|
auto ss = std::make_shared<std::string>(std::move(msg));
|
||||||
|
ws_.async_write(net::buffer(*ss), [ss](beast::error_code, std::size_t) {});
|
||||||
|
}
|
||||||
|
|
||||||
|
int get_id() const {
|
||||||
|
return id_;
|
||||||
|
}*/
|
||||||
|
|
||||||
|
ClientState get_latest_state(std::chrono::system_clock::time_point now) {
|
||||||
|
if (timedClientStates.timedStates.empty()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Берем самое последнее известное состояние
|
||||||
|
ClientState latest = timedClientStates.timedStates.back();
|
||||||
|
|
||||||
|
// 3. Применяем компенсацию лага (экстраполяцию).
|
||||||
|
// Функция внутри использует simulate_physics, чтобы переместить объект
|
||||||
|
// из точки lastUpdateServerTime в точку now.
|
||||||
|
latest.apply_lag_compensation(now);
|
||||||
|
|
||||||
|
return latest;
|
||||||
|
}
|
||||||
|
/*
|
||||||
void send_message(std::string msg) {
|
void send_message(std::string msg) {
|
||||||
auto ss = std::make_shared<std::string>(std::move(msg));
|
auto ss = std::make_shared<std::string>(std::move(msg));
|
||||||
|
|
||||||
@ -186,63 +238,42 @@ class Session : public std::enable_shared_from_this<Session> {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public:
|
|
||||||
explicit Session(tcp::socket&& socket, int id)
|
|
||||||
: ws_(std::move(socket)), id_(id) {
|
|
||||||
}
|
|
||||||
|
|
||||||
void init()
|
|
||||||
{
|
|
||||||
sendBoxesToClient();
|
|
||||||
|
|
||||||
auto timer = std::make_shared<net::steady_timer>(ws_.get_executor());
|
|
||||||
timer->expires_after(std::chrono::milliseconds(100));
|
|
||||||
timer->async_wait([self = shared_from_this(), timer](const boost::system::error_code& ec) {
|
|
||||||
if (!ec) {
|
|
||||||
self->send_message("ID:" + std::to_string(self->id_));
|
|
||||||
self->do_read();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void run() {
|
|
||||||
|
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
|
||||||
g_sessions.push_back(shared_from_this());
|
|
||||||
}
|
|
||||||
|
|
||||||
ws_.async_accept([self = shared_from_this()](beast::error_code ec) {
|
|
||||||
if (ec) return;
|
|
||||||
std::cout << "Client " << self->id_ << " connected\n";
|
|
||||||
self->init();
|
|
||||||
// self->send_message("ID:" + std::to_string(self->id_));
|
|
||||||
// self->do_read();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/*void send_message(std::string msg) {
|
|
||||||
auto ss = std::make_shared<std::string>(std::move(msg));
|
|
||||||
ws_.async_write(net::buffer(*ss), [ss](beast::error_code, std::size_t) {});
|
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
int get_id() const {
|
void doWrite() {
|
||||||
return id_;
|
std::lock_guard<std::mutex> lock(writeMutex_);
|
||||||
|
if (is_writing_ || writeQueue_.empty()) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
is_writing_ = true;
|
||||||
|
auto message = writeQueue_.front();
|
||||||
|
|
||||||
|
ws_.async_write(net::buffer(*message),
|
||||||
|
[self = shared_from_this(), message](beast::error_code ec, std::size_t) {
|
||||||
|
if (ec) {
|
||||||
|
std::cerr << "Write error: " << ec.message() << std::endl;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(self->writeMutex_);
|
||||||
|
self->writeQueue_.pop();
|
||||||
|
self->is_writing_ = false;
|
||||||
|
}
|
||||||
|
self->doWrite();
|
||||||
|
});
|
||||||
|
}
|
||||||
private:
|
private:
|
||||||
|
|
||||||
void do_read() {
|
void do_read() {
|
||||||
ws_.async_read(buffer_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
|
ws_.async_read(buffer_, [self = shared_from_this()](beast::error_code ec, std::size_t) {
|
||||||
if (ec)
|
if (ec) {
|
||||||
{
|
|
||||||
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
g_sessions.erase(std::remove_if(g_sessions.begin(), g_sessions.end(),
|
g_sessions.erase(std::remove_if(g_sessions.begin(), g_sessions.end(),
|
||||||
[self](const std::shared_ptr<Session>& session) {
|
[self](const std::shared_ptr<Session>& session) {
|
||||||
return session.get() == self.get();
|
return session.get() == self.get();
|
||||||
}), g_sessions.end());
|
}), g_sessions.end());
|
||||||
|
std::cout << "Client " << self->id_ << " disconnected\n";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -253,15 +284,266 @@ private:
|
|||||||
self->do_read();
|
self->do_read();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void process_message(const std::string& msg) {
|
||||||
|
auto parts = split(msg, ':');
|
||||||
|
|
||||||
|
if (parts.empty()) return;
|
||||||
|
|
||||||
|
std::string type = parts[0];
|
||||||
|
|
||||||
|
if (type == "UPD") {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> gd(g_dead_mutex);
|
||||||
|
if (g_dead_players.find(id_) != g_dead_players.end()) {
|
||||||
|
std::cout << "Server: Ignoring UPD from dead player " << id_ << std::endl;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parts.size() < 16) return;
|
||||||
|
uint64_t clientTimestamp = std::stoull(parts[1]);
|
||||||
|
ClientState receivedState;
|
||||||
|
receivedState.id = id_;
|
||||||
|
std::chrono::system_clock::time_point uptime_timepoint{
|
||||||
|
std::chrono::milliseconds(clientTimestamp)
|
||||||
|
};
|
||||||
|
receivedState.lastUpdateServerTime = uptime_timepoint;
|
||||||
|
receivedState.handle_full_sync(parts, 2);
|
||||||
|
timedClientStates.add_state(receivedState);
|
||||||
|
|
||||||
|
retranslateMessage(msg);
|
||||||
|
}
|
||||||
|
else if (parts[0] == "RESPAWN") {
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> gd(g_dead_mutex);
|
||||||
|
g_dead_players.erase(id_);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string respawnMsg = "RESPAWN_ACK:" + std::to_string(id_);
|
||||||
|
broadcastToAll(respawnMsg);
|
||||||
|
|
||||||
|
std::cout << "Server: Player " << id_ << " respawned\n";
|
||||||
|
}
|
||||||
|
else if (parts[0] == "FIRE") {
|
||||||
|
if (parts.size() < 10) return;
|
||||||
|
|
||||||
|
uint64_t clientTime = std::stoull(parts[1]);
|
||||||
|
Eigen::Vector3f pos{
|
||||||
|
std::stof(parts[2]), std::stof(parts[3]), std::stof(parts[4])
|
||||||
|
};
|
||||||
|
Eigen::Quaternionf dir(
|
||||||
|
std::stof(parts[5]), std::stof(parts[6]), std::stof(parts[7]), std::stof(parts[8])
|
||||||
|
);
|
||||||
|
float velocity = std::stof(parts[9]);
|
||||||
|
|
||||||
|
int shotCount = 2;
|
||||||
|
if (parts.size() >= 11) {
|
||||||
|
try { shotCount = std::stoi(parts[10]); }
|
||||||
|
catch (...) { shotCount = 2; }
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string broadcast = "PROJECTILE:" +
|
||||||
|
std::to_string(id_) + ":" +
|
||||||
|
std::to_string(clientTime) + ":" +
|
||||||
|
std::to_string(pos.x()) + ":" +
|
||||||
|
std::to_string(pos.y()) + ":" +
|
||||||
|
std::to_string(pos.z()) + ":" +
|
||||||
|
std::to_string(dir.w()) + ":" +
|
||||||
|
std::to_string(dir.x()) + ":" +
|
||||||
|
std::to_string(dir.y()) + ":" +
|
||||||
|
std::to_string(dir.z()) + ":" +
|
||||||
|
std::to_string(velocity);
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
|
for (auto& session : g_sessions) {
|
||||||
|
if (session->get_id() != id_) {
|
||||||
|
session->send_message(broadcast);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
const std::vector<Eigen::Vector3f> localOffsets = {
|
||||||
|
Eigen::Vector3f(-1.5f, 0.9f, 5.0f),
|
||||||
|
Eigen::Vector3f(1.5f, 0.9f, 5.0f)
|
||||||
|
};
|
||||||
|
|
||||||
|
uint64_t now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
std::chrono::system_clock::now().time_since_epoch()).count();
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> pl(g_projectiles_mutex);
|
||||||
|
for (int i = 0; i < std::min(shotCount, (int)localOffsets.size()); ++i) {
|
||||||
|
Projectile pr;
|
||||||
|
pr.shooterId = id_;
|
||||||
|
pr.spawnMs = now_ms;
|
||||||
|
Eigen::Vector3f shotPos = pos + dir.toRotationMatrix() * localOffsets[i];
|
||||||
|
pr.pos = shotPos;
|
||||||
|
Eigen::Vector3f localForward(0.0f, 0.0f, -1.0f);
|
||||||
|
Eigen::Vector3f worldForward = dir.toRotationMatrix() * localForward;
|
||||||
|
float len = worldForward.norm();
|
||||||
|
if (len > 1e-6f) worldForward /= len;
|
||||||
|
pr.vel = worldForward * velocity;
|
||||||
|
pr.lifeMs = 5000.0f;
|
||||||
|
g_projectiles.push_back(pr);
|
||||||
|
|
||||||
|
std::cout << "Server: Created projectile from player " << id_
|
||||||
|
<< " at pos (" << shotPos.x() << ", " << shotPos.y() << ", " << shotPos.z()
|
||||||
|
<< ") vel (" << pr.vel.x() << ", " << pr.vel.y() << ", " << pr.vel.z() << ")" << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void retranslateMessage(const std::string& msg) {
|
||||||
|
std::string event_msg = "EVENT:" + std::to_string(id_) + ":" + msg;
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
|
for (auto& session : g_sessions) {
|
||||||
|
if (session->get_id() != id_) {
|
||||||
|
session->send_message(event_msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
void broadcastToAll(const std::string& message) {
|
||||||
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
|
for (const auto& session : g_sessions) {
|
||||||
|
session->send_message(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void update_world(net::steady_timer& timer, net::io_context& ioc) {
|
void update_world(net::steady_timer& timer, net::io_context& ioc) {
|
||||||
|
|
||||||
// TODO: Renew game state
|
static auto last_snapshot_time = std::chrono::steady_clock::now();
|
||||||
|
auto now = std::chrono::steady_clock::now();
|
||||||
|
|
||||||
|
// Рассылка Snapshot раз в 1000мс
|
||||||
|
/*
|
||||||
|
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_snapshot_time).count() >= 1000) {
|
||||||
|
last_snapshot_time = now;
|
||||||
|
|
||||||
|
auto system_now = std::chrono::system_clock::now();
|
||||||
|
|
||||||
|
std::string snapshot_msg = "SNAPSHOT:" + std::to_string(
|
||||||
|
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
|
system_now.time_since_epoch()).count()
|
||||||
|
);
|
||||||
|
|
||||||
|
std::lock_guard<std::mutex> lock(g_sessions_mutex);
|
||||||
|
|
||||||
|
// Формируем общую строку состояний всех игроков
|
||||||
|
for (auto& session : g_sessions) {
|
||||||
|
ClientState st = session->get_latest_state(system_now);
|
||||||
|
snapshot_msg += "|" + std::to_string(session->get_id()) + ":" + st.formPingMessageContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (auto& session : g_sessions) {
|
||||||
|
session->send_message(snapshot_msg);
|
||||||
|
}
|
||||||
|
}*/
|
||||||
|
|
||||||
|
const std::chrono::milliseconds interval(50);
|
||||||
|
timer.expires_after(interval);
|
||||||
|
|
||||||
timer.expires_after(std::chrono::milliseconds(50));
|
|
||||||
timer.async_wait([&](const boost::system::error_code& ec) {
|
timer.async_wait([&](const boost::system::error_code& ec) {
|
||||||
if (!ec) update_world(timer, ioc);
|
if (ec) return;
|
||||||
|
|
||||||
|
auto now = std::chrono::system_clock::now();
|
||||||
|
uint64_t now_ms = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count());
|
||||||
|
|
||||||
|
std::vector<DeathInfo> deathEvents;
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> pl(g_projectiles_mutex);
|
||||||
|
std::vector<int> indicesToRemove;
|
||||||
|
|
||||||
|
float dt = 50.0f / 1000.0f;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < g_projectiles.size(); ++i) {
|
||||||
|
auto& pr = g_projectiles[i];
|
||||||
|
|
||||||
|
pr.pos += pr.vel * dt;
|
||||||
|
|
||||||
|
if (now_ms > pr.spawnMs + static_cast<uint64_t>(pr.lifeMs)) {
|
||||||
|
indicesToRemove.push_back(static_cast<int>(i));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool hitDetected = false;
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lm(g_sessions_mutex);
|
||||||
|
std::lock_guard<std::mutex> gd(g_dead_mutex);
|
||||||
|
|
||||||
|
for (auto& session : g_sessions) {
|
||||||
|
int targetId = session->get_id();
|
||||||
|
|
||||||
|
if (targetId == pr.shooterId) continue;
|
||||||
|
if (g_dead_players.find(targetId) != g_dead_players.end()) continue;
|
||||||
|
|
||||||
|
ClientState targetState;
|
||||||
|
if (!session->fetchStateAtTime(now, targetState)) continue;
|
||||||
|
|
||||||
|
Eigen::Vector3f diff = pr.pos - targetState.position;
|
||||||
|
const float shipRadius = 15.0f;
|
||||||
|
const float projectileRadius = 1.5f;
|
||||||
|
float combinedRadius = shipRadius + projectileRadius;
|
||||||
|
|
||||||
|
if (diff.squaredNorm() <= combinedRadius * combinedRadius) {
|
||||||
|
DeathInfo death;
|
||||||
|
death.targetId = targetId;
|
||||||
|
death.serverTime = now_ms;
|
||||||
|
death.position = pr.pos;
|
||||||
|
death.killerId = pr.shooterId;
|
||||||
|
|
||||||
|
deathEvents.push_back(death);
|
||||||
|
g_dead_players.insert(targetId);
|
||||||
|
indicesToRemove.push_back(static_cast<int>(i));
|
||||||
|
hitDetected = true;
|
||||||
|
|
||||||
|
std::cout << "Server: *** HIT DETECTED! ***" << std::endl;
|
||||||
|
std::cout << "Server: Projectile at ("
|
||||||
|
<< pr.pos.x() << ", " << pr.pos.y() << ", " << pr.pos.z()
|
||||||
|
<< ") hit player " << targetId << std::endl;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hitDetected) continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!indicesToRemove.empty()) {
|
||||||
|
std::sort(indicesToRemove.rbegin(), indicesToRemove.rend());
|
||||||
|
for (int idx : indicesToRemove) {
|
||||||
|
if (idx >= 0 && idx < (int)g_projectiles.size()) {
|
||||||
|
g_projectiles.erase(g_projectiles.begin() + idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!deathEvents.empty()) {
|
||||||
|
for (const auto& death : deathEvents) {
|
||||||
|
std::string deadMsg = "DEAD:" +
|
||||||
|
std::to_string(death.serverTime) + ":" +
|
||||||
|
std::to_string(death.targetId) + ":" +
|
||||||
|
std::to_string(death.position.x()) + ":" +
|
||||||
|
std::to_string(death.position.y()) + ":" +
|
||||||
|
std::to_string(death.position.z()) + ":" +
|
||||||
|
std::to_string(death.killerId);
|
||||||
|
|
||||||
|
broadcastToAll(deadMsg);
|
||||||
|
|
||||||
|
std::cout << "Server: Sent DEAD event - Player " << death.targetId
|
||||||
|
<< " killed by " << death.killerId << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
update_world(timer, ioc);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -314,7 +596,6 @@ std::vector<ServerBox> generateServerBoxes(int count) {
|
|||||||
return boxes;
|
return boxes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
try {
|
try {
|
||||||
{
|
{
|
||||||
@ -324,7 +605,8 @@ int main() {
|
|||||||
}
|
}
|
||||||
net::io_context ioc;
|
net::io_context ioc;
|
||||||
tcp::acceptor acceptor{ ioc, {tcp::v4(), 8080} };
|
tcp::acceptor acceptor{ ioc, {tcp::v4(), 8080} };
|
||||||
int next_id = 0;
|
|
||||||
|
int next_id = 1000;
|
||||||
|
|
||||||
std::cout << "Server started on port 8080...\n";
|
std::cout << "Server started on port 8080...\n";
|
||||||
|
|
||||||
@ -337,7 +619,6 @@ int main() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
net::steady_timer timer(ioc);
|
net::steady_timer timer(ioc);
|
||||||
update_world(timer, ioc);
|
update_world(timer, ioc);
|
||||||
|
|
||||||
|
|||||||
197
src/Game.cpp
197
src/Game.cpp
@ -349,6 +349,7 @@ namespace ZL
|
|||||||
uint64_t now = SDL_GetTicks64();
|
uint64_t now = SDL_GetTicks64();
|
||||||
if (now - lastProjectileFireTime >= static_cast<uint64_t>(projectileCooldownMs)) {
|
if (now - lastProjectileFireTime >= static_cast<uint64_t>(projectileCooldownMs)) {
|
||||||
lastProjectileFireTime = now;
|
lastProjectileFireTime = now;
|
||||||
|
const float projectileSpeed = 60.0f;
|
||||||
|
|
||||||
this->fireProjectiles();
|
this->fireProjectiles();
|
||||||
|
|
||||||
@ -358,15 +359,21 @@ namespace ZL
|
|||||||
Eigen::Vector3f centerPos = Environment::shipState.position +
|
Eigen::Vector3f centerPos = Environment::shipState.position +
|
||||||
Environment::shipState.rotation * Vector3f{ 0, 0.9f, 5.0f };
|
Environment::shipState.rotation * Vector3f{ 0, 0.9f, 5.0f };
|
||||||
|
|
||||||
|
Eigen::Quaternionf q(Environment::shipState.rotation);
|
||||||
|
float speedToSend = projectileSpeed + Environment::shipState.velocity;
|
||||||
|
int shotCount = 2;
|
||||||
|
|
||||||
std::string fireMsg = "FIRE:" +
|
std::string fireMsg = "FIRE:" +
|
||||||
std::to_string(now) + ":" +
|
std::to_string(now) + ":" +
|
||||||
std::to_string(centerPos.x()) + ":" +
|
std::to_string(centerPos.x()) + ":" +
|
||||||
std::to_string(centerPos.y()) + ":" +
|
std::to_string(centerPos.y()) + ":" +
|
||||||
std::to_string(centerPos.z()) + ":" +
|
std::to_string(centerPos.z()) + ":" +
|
||||||
std::to_string(worldForward.x()) + ":" +
|
std::to_string(q.w()) + ":" +
|
||||||
std::to_string(worldForward.y()) + ":" +
|
std::to_string(q.x()) + ":" +
|
||||||
std::to_string(worldForward.z()) + ":" +
|
std::to_string(q.y()) + ":" +
|
||||||
"2";
|
std::to_string(q.z()) + ":" +
|
||||||
|
std::to_string(speedToSend) + ":" +
|
||||||
|
std::to_string(shotCount);
|
||||||
|
|
||||||
networkClient->Send(fireMsg);
|
networkClient->Send(fireMsg);
|
||||||
}
|
}
|
||||||
@ -734,13 +741,13 @@ namespace ZL
|
|||||||
// Биндим текстуру корабля один раз для всех удаленных игроков (оптимизация батчинга)
|
// Биндим текстуру корабля один раз для всех удаленных игроков (оптимизация батчинга)
|
||||||
glBindTexture(GL_TEXTURE_2D, spaceshipTexture->getTexID());
|
glBindTexture(GL_TEXTURE_2D, spaceshipTexture->getTexID());
|
||||||
|
|
||||||
auto now = std::chrono::system_clock::now();
|
/*auto now = std::chrono::system_clock::now();
|
||||||
|
|
||||||
//Apply server delay:
|
//Apply server delay:
|
||||||
now -= std::chrono::milliseconds(CLIENT_DELAY);
|
now -= std::chrono::milliseconds(CLIENT_DELAY);
|
||||||
|
|
||||||
latestRemotePlayers = networkClient->getRemotePlayers();
|
latestRemotePlayers = networkClient->getRemotePlayers();
|
||||||
|
*/
|
||||||
// Если сервер прислал коробки, применяем их однократно вместо локальной генерации
|
// Если сервер прислал коробки, применяем их однократно вместо локальной генерации
|
||||||
if (!serverBoxesApplied && networkClient) {
|
if (!serverBoxesApplied && networkClient) {
|
||||||
auto sboxes = networkClient->getServerBoxes();
|
auto sboxes = networkClient->getServerBoxes();
|
||||||
@ -763,15 +770,9 @@ namespace ZL
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Итерируемся по актуальным данным из extrapolateRemotePlayers
|
// Итерируемся по актуальным данным из extrapolateRemotePlayers
|
||||||
for (auto const& [id, remotePlayer] : latestRemotePlayers) {
|
for (auto const& [id, remotePlayer] : remotePlayerStates) {
|
||||||
|
|
||||||
if (!remotePlayer.canFetchClientStateAtTime(now))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
ClientState playerState = remotePlayer.fetchClientStateAtTime(now);
|
|
||||||
|
|
||||||
|
const ClientState& playerState = remotePlayer;
|
||||||
|
|
||||||
renderer.PushMatrix();
|
renderer.PushMatrix();
|
||||||
renderer.LoadIdentity();
|
renderer.LoadIdentity();
|
||||||
@ -811,18 +812,15 @@ namespace ZL
|
|||||||
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
||||||
|
|
||||||
// Берем удаленных игроков
|
// Берем удаленных игроков
|
||||||
latestRemotePlayers = networkClient->getRemotePlayers();
|
//latestRemotePlayers = networkClient->getRemotePlayers();
|
||||||
|
|
||||||
auto now = std::chrono::system_clock::now();
|
auto now = std::chrono::system_clock::now();
|
||||||
now -= std::chrono::milliseconds(CLIENT_DELAY);
|
now -= std::chrono::milliseconds(CLIENT_DELAY);
|
||||||
|
|
||||||
for (auto const& [id, remotePlayer] : latestRemotePlayers)
|
for (auto const& [id, remotePlayer] : remotePlayerStates)
|
||||||
{
|
{
|
||||||
if (!remotePlayer.canFetchClientStateAtTime(now))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
ClientState st = remotePlayer.fetchClientStateAtTime(now);
|
|
||||||
|
|
||||||
|
const ClientState& st = remotePlayer;
|
||||||
// Позиция корабля в мире
|
// Позиция корабля в мире
|
||||||
Vector3f shipWorld = st.position;
|
Vector3f shipWorld = st.position;
|
||||||
|
|
||||||
@ -872,6 +870,9 @@ namespace ZL
|
|||||||
lastTickCount = std::chrono::duration_cast<std::chrono::milliseconds>(
|
lastTickCount = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||||
std::chrono::system_clock::now().time_since_epoch()
|
std::chrono::system_clock::now().time_since_epoch()
|
||||||
).count();
|
).count();
|
||||||
|
|
||||||
|
lastTickCount = (lastTickCount / 50)*50;
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -880,6 +881,8 @@ namespace ZL
|
|||||||
std::chrono::system_clock::now().time_since_epoch()
|
std::chrono::system_clock::now().time_since_epoch()
|
||||||
).count();
|
).count();
|
||||||
|
|
||||||
|
newTickCount = (newTickCount / 50) * 50;
|
||||||
|
|
||||||
if (newTickCount - lastTickCount > CONST_TIMER_INTERVAL) {
|
if (newTickCount - lastTickCount > CONST_TIMER_INTERVAL) {
|
||||||
|
|
||||||
size_t delta = newTickCount - lastTickCount;
|
size_t delta = newTickCount - lastTickCount;
|
||||||
@ -893,15 +896,7 @@ namespace ZL
|
|||||||
sparkEmitter.update(static_cast<float>(delta));
|
sparkEmitter.update(static_cast<float>(delta));
|
||||||
planetObject.update(static_cast<float>(delta));
|
planetObject.update(static_cast<float>(delta));
|
||||||
|
|
||||||
static float pingTimer = 0.0f;
|
|
||||||
pingTimer += delta;
|
|
||||||
if (pingTimer >= 1000.0f) {
|
|
||||||
std::string pingMsg = "UPD:" + std::to_string(now_ms) + ":" + Environment::shipState.formPingMessageContent();
|
|
||||||
|
|
||||||
networkClient->Send(pingMsg);
|
|
||||||
std::cout << "Sending: " << pingMsg << std::endl;
|
|
||||||
pingTimer = 0.0f;
|
|
||||||
}
|
|
||||||
|
|
||||||
//Handle input:
|
//Handle input:
|
||||||
|
|
||||||
@ -957,9 +952,44 @@ namespace ZL
|
|||||||
std::cout << "Sending: " << msg << std::endl;
|
std::cout << "Sending: " << msg << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
Environment::shipState.simulate_physics(delta);
|
long long leftoverDelta = delta;
|
||||||
|
while (leftoverDelta > 0)
|
||||||
|
{
|
||||||
|
long long miniDelta = 50;
|
||||||
|
Environment::shipState.simulate_physics(miniDelta);
|
||||||
|
leftoverDelta -= miniDelta;
|
||||||
|
}
|
||||||
Environment::inverseShipMatrix = Environment::shipState.rotation.inverse();
|
Environment::inverseShipMatrix = Environment::shipState.rotation.inverse();
|
||||||
|
|
||||||
|
static float pingTimer = 0.0f;
|
||||||
|
pingTimer += delta;
|
||||||
|
if (pingTimer >= 1000.0f) {
|
||||||
|
std::string pingMsg = "UPD:" + std::to_string(now_ms) + ":" + Environment::shipState.formPingMessageContent();
|
||||||
|
|
||||||
|
networkClient->Send(pingMsg);
|
||||||
|
std::cout << "Sending: " << pingMsg << std::endl;
|
||||||
|
pingTimer = 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
auto latestRemotePlayers = networkClient->getRemotePlayers();
|
||||||
|
|
||||||
|
std::chrono::system_clock::time_point nowRounded{ std::chrono::milliseconds(newTickCount) };
|
||||||
|
|
||||||
|
|
||||||
|
for (auto const& [id, remotePlayer] : latestRemotePlayers) {
|
||||||
|
|
||||||
|
if (!remotePlayer.canFetchClientStateAtTime(nowRounded))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ClientState playerState = remotePlayer.fetchClientStateAtTime(nowRounded);
|
||||||
|
|
||||||
|
remotePlayerStates[id] = playerState;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
for (auto& p : projectiles) {
|
for (auto& p : projectiles) {
|
||||||
if (p && p->isActive()) {
|
if (p && p->isActive()) {
|
||||||
p->update(static_cast<float>(delta), renderer);
|
p->update(static_cast<float>(delta), renderer);
|
||||||
@ -1027,11 +1057,16 @@ namespace ZL
|
|||||||
if (!uiGameOverShown) {
|
if (!uiGameOverShown) {
|
||||||
if (uiManager.pushMenuFromFile("resources/config/game_over.json", this->renderer, CONST_ZIP_FILE)) {
|
if (uiManager.pushMenuFromFile("resources/config/game_over.json", this->renderer, CONST_ZIP_FILE)) {
|
||||||
uiManager.setButtonCallback("restartButton", [this](const std::string& name) {
|
uiManager.setButtonCallback("restartButton", [this](const std::string& name) {
|
||||||
|
|
||||||
|
std::string respawnMsg = "RESPAWN:" + std::to_string(networkClient->GetClientId());
|
||||||
|
networkClient->Send(respawnMsg);
|
||||||
|
|
||||||
this->shipAlive = true;
|
this->shipAlive = true;
|
||||||
this->gameOver = false;
|
this->gameOver = false;
|
||||||
this->uiGameOverShown = false;
|
this->uiGameOverShown = false;
|
||||||
this->showExplosion = false;
|
this->showExplosion = false;
|
||||||
this->explosionEmitter.setEmissionPoints(std::vector<Vector3f>());
|
this->explosionEmitter.setEmissionPoints(std::vector<Vector3f>());
|
||||||
|
this->deadRemotePlayers.clear();
|
||||||
|
|
||||||
Environment::shipState.position = Vector3f{ 0, 0, 45000.f };
|
Environment::shipState.position = Vector3f{ 0, 0, 45000.f };
|
||||||
Environment::shipState.velocity = 0.0f;
|
Environment::shipState.velocity = 0.0f;
|
||||||
@ -1358,7 +1393,37 @@ namespace ZL
|
|||||||
const float projectileSpeed = 60.0f;
|
const float projectileSpeed = 60.0f;
|
||||||
const float lifeMs = 5000.0f;
|
const float lifeMs = 5000.0f;
|
||||||
const float size = 0.5f;
|
const float size = 0.5f;
|
||||||
|
for (const auto& pi : pending) {
|
||||||
|
const std::vector<Vector3f> localOffsets = {
|
||||||
|
Vector3f{ -1.5f, 0.9f, 5.0f },
|
||||||
|
Vector3f{ 1.5f, 0.9f, 5.0f }
|
||||||
|
//Vector3f{},
|
||||||
|
//Vector3f{}
|
||||||
|
};
|
||||||
|
|
||||||
|
Vector3f localForward = { 0, 0, -1 };
|
||||||
|
Vector3f worldForward = pi.rotation * localForward;
|
||||||
|
|
||||||
|
float len = worldForward.norm();
|
||||||
|
if (len <= 1e-6f) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
worldForward /= len;
|
||||||
|
|
||||||
|
Vector3f baseVel = worldForward * pi.velocity;
|
||||||
|
|
||||||
|
for (const auto& off : localOffsets) {
|
||||||
|
Vector3f shotPos = pi.position + (pi.rotation * off);
|
||||||
|
|
||||||
|
for (auto& p : projectiles) {
|
||||||
|
if (!p->isActive()) {
|
||||||
|
p->init(shotPos, baseVel, lifeMs, size, projectileTexture, renderer);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/*
|
||||||
auto remotePlayersSnapshot = networkClient->getRemotePlayers();
|
auto remotePlayersSnapshot = networkClient->getRemotePlayers();
|
||||||
for (const auto& pi : pending) {
|
for (const auto& pi : pending) {
|
||||||
Eigen::Vector3f dir = pi.direction;
|
Eigen::Vector3f dir = pi.direction;
|
||||||
@ -1399,6 +1464,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
13
src/Game.h
13
src/Game.h
@ -15,6 +15,8 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <render/TextRenderer.h>
|
#include <render/TextRenderer.h>
|
||||||
|
|
||||||
|
#include <unordered_set>
|
||||||
|
|
||||||
namespace ZL {
|
namespace ZL {
|
||||||
|
|
||||||
|
|
||||||
@ -73,7 +75,8 @@ namespace ZL {
|
|||||||
std::vector<std::string> boxLabels;
|
std::vector<std::string> boxLabels;
|
||||||
std::unique_ptr<TextRenderer> textRenderer;
|
std::unique_ptr<TextRenderer> textRenderer;
|
||||||
|
|
||||||
std::unordered_map<int, ClientStateInterval> latestRemotePlayers;
|
//std::unordered_map<int, ClientStateInterval> latestRemotePlayers;
|
||||||
|
std::unordered_map<int, ClientState> remotePlayerStates;
|
||||||
|
|
||||||
float newShipVelocity = 0;
|
float newShipVelocity = 0;
|
||||||
|
|
||||||
@ -116,6 +119,9 @@ namespace ZL {
|
|||||||
uint64_t lastExplosionTime = 0;
|
uint64_t lastExplosionTime = 0;
|
||||||
const uint64_t explosionDurationMs = 500;
|
const uint64_t explosionDurationMs = 500;
|
||||||
|
|
||||||
|
|
||||||
|
bool serverBoxesApplied = false;
|
||||||
|
|
||||||
static constexpr float MAX_DIST_SQ = 10000.f * 10000.f;
|
static constexpr float MAX_DIST_SQ = 10000.f * 10000.f;
|
||||||
static constexpr float FADE_START = 6000.f;
|
static constexpr float FADE_START = 6000.f;
|
||||||
static constexpr float FADE_RANGE = 4000.f;
|
static constexpr float FADE_RANGE = 4000.f;
|
||||||
@ -124,7 +130,10 @@ namespace ZL {
|
|||||||
static constexpr float MIN_SCALE = 0.4f;
|
static constexpr float MIN_SCALE = 0.4f;
|
||||||
static constexpr float MAX_SCALE = 0.8f;
|
static constexpr float MAX_SCALE = 0.8f;
|
||||||
static constexpr float CLOSE_DIST = 600.0f;
|
static constexpr float CLOSE_DIST = 600.0f;
|
||||||
bool serverBoxesApplied = false;
|
|
||||||
|
std::unordered_set<int> deadRemotePlayers;
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -157,6 +157,16 @@ void ClientState::apply_lag_compensation(std::chrono::system_clock::time_point n
|
|||||||
deltaMs = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - lastUpdateServerTime).count();
|
deltaMs = std::chrono::duration_cast<std::chrono::milliseconds>(nowTime - lastUpdateServerTime).count();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
long long deltaMsLeftover = deltaMs;
|
||||||
|
|
||||||
|
while (deltaMsLeftover > 0)
|
||||||
|
{
|
||||||
|
long long miniDelta = 50;
|
||||||
|
simulate_physics(miniDelta);
|
||||||
|
deltaMsLeftover -= miniDelta;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
// 3. Защита от слишком больших скачков (Clamp)
|
// 3. Защита от слишком больших скачков (Clamp)
|
||||||
// Если лаг более 500мс, ограничиваем его, чтобы избежать резких рывков
|
// Если лаг более 500мс, ограничиваем его, чтобы избежать резких рывков
|
||||||
long long final_lag_ms = deltaMs;//min(deltaMs, 500ll);
|
long long final_lag_ms = deltaMs;//min(deltaMs, 500ll);
|
||||||
@ -165,7 +175,7 @@ void ClientState::apply_lag_compensation(std::chrono::system_clock::time_point n
|
|||||||
// Доматываем симуляцию на величину задержки
|
// Доматываем симуляцию на величину задержки
|
||||||
// Мы предполагаем, что за это время параметры управления не менялись
|
// Мы предполагаем, что за это время параметры управления не менялись
|
||||||
simulate_physics(final_lag_ms);
|
simulate_physics(final_lag_ms);
|
||||||
}
|
}*/
|
||||||
}
|
}
|
||||||
|
|
||||||
void ClientState::handle_full_sync(const std::vector<std::string>& parts, int startFrom) {
|
void ClientState::handle_full_sync(const std::vector<std::string>& parts, int startFrom) {
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
// WebSocketClient.h
|
|
||||||
#include "NetworkInterface.h"
|
#include "NetworkInterface.h"
|
||||||
#include <queue>
|
#include <queue>
|
||||||
|
|
||||||
@ -16,8 +15,8 @@ namespace ZL {
|
|||||||
void Send(const std::string& message) override;
|
void Send(const std::string& message) override;
|
||||||
|
|
||||||
bool IsConnected() const override { return true; }
|
bool IsConnected() const override { return true; }
|
||||||
int GetClientId() const { return 1; }
|
int GetClientId() const override { return 1; }
|
||||||
std::vector<ProjectileInfo> getPendingProjectiles();
|
std::vector<ProjectileInfo> getPendingProjectiles() override;
|
||||||
|
|
||||||
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
|
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
|
||||||
return std::unordered_map<int, ClientStateInterval>();
|
return std::unordered_map<int, ClientStateInterval>();
|
||||||
@ -26,5 +25,13 @@ namespace ZL {
|
|||||||
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
|
std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() override {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::vector<DeathInfo> getPendingDeaths() override {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<int> getPendingRespawns() override {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -11,7 +11,16 @@ namespace ZL {
|
|||||||
int shooterId = -1;
|
int shooterId = -1;
|
||||||
uint64_t clientTime = 0;
|
uint64_t clientTime = 0;
|
||||||
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
||||||
Eigen::Vector3f direction = Eigen::Vector3f::Zero();
|
//Eigen::Vector3f direction = Eigen::Vector3f::Zero();
|
||||||
|
Eigen::Matrix3f rotation = Eigen::Matrix3f::Identity();
|
||||||
|
float velocity = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DeathInfo {
|
||||||
|
int targetId = -1;
|
||||||
|
uint64_t serverTime = 0;
|
||||||
|
Eigen::Vector3f position = Eigen::Vector3f::Zero();
|
||||||
|
int killerId = -1;
|
||||||
};
|
};
|
||||||
|
|
||||||
class INetworkClient {
|
class INetworkClient {
|
||||||
@ -26,5 +35,9 @@ namespace ZL {
|
|||||||
virtual std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() = 0;
|
virtual std::vector<std::pair<Eigen::Vector3f, Eigen::Matrix3f>> getServerBoxes() = 0;
|
||||||
|
|
||||||
virtual std::vector<ProjectileInfo> getPendingProjectiles() = 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; }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -71,6 +71,20 @@ namespace ZL {
|
|||||||
return copy;
|
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() {
|
void WebSocketClient::Poll() {
|
||||||
std::lock_guard<std::mutex> lock(queueMutex);
|
std::lock_guard<std::mutex> lock(queueMutex);
|
||||||
|
|
||||||
@ -125,10 +139,29 @@ namespace ZL {
|
|||||||
}
|
}
|
||||||
continue;
|
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) {
|
if (msg.rfind("PROJECTILE:", 0) == 0) {
|
||||||
auto parts = split(msg, ':');
|
auto parts = split(msg, ':');
|
||||||
if (parts.size() >= 9) {
|
if (parts.size() >= 10) {
|
||||||
try {
|
try {
|
||||||
ProjectileInfo pi;
|
ProjectileInfo pi;
|
||||||
pi.shooterId = std::stoi(parts[1]);
|
pi.shooterId = std::stoi(parts[1]);
|
||||||
@ -138,16 +171,41 @@ namespace ZL {
|
|||||||
std::stof(parts[4]),
|
std::stof(parts[4]),
|
||||||
std::stof(parts[5])
|
std::stof(parts[5])
|
||||||
);
|
);
|
||||||
pi.direction = Eigen::Vector3f(
|
Eigen::Quaternionf q(
|
||||||
std::stof(parts[6]),
|
std::stof(parts[6]),
|
||||||
std::stof(parts[7]),
|
std::stof(parts[7]),
|
||||||
std::stof(parts[8])
|
std::stof(parts[8]),
|
||||||
|
std::stof(parts[9])
|
||||||
);
|
);
|
||||||
|
pi.rotation = q.toRotationMatrix();
|
||||||
|
|
||||||
|
pi.velocity = std::stof(parts[10]);
|
||||||
std::lock_guard<std::mutex> pl(projMutex_);
|
std::lock_guard<std::mutex> pl(projMutex_);
|
||||||
pendingProjectiles_.push_back(pi);
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
@ -198,6 +256,35 @@ namespace ZL {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (msg.rfind("SNAPSHOT:", 0) == 0) {
|
||||||
|
auto mainParts = split(msg.substr(9), '|'); // Отсекаем "SNAPSHOT:" и делим по игрокам
|
||||||
|
if (mainParts.empty()) continue;
|
||||||
|
|
||||||
|
uint64_t serverTimestamp = std::stoull(mainParts[0]);
|
||||||
|
std::chrono::system_clock::time_point serverTime{ std::chrono::milliseconds(serverTimestamp) };
|
||||||
|
|
||||||
|
for (size_t i = 1; i < mainParts.size(); ++i) {
|
||||||
|
auto playerParts = split(mainParts[i], ':');
|
||||||
|
if (playerParts.size() < 15) continue; // ID + 14 полей ClientState
|
||||||
|
|
||||||
|
int rId = std::stoi(playerParts[0]);
|
||||||
|
if (rId == clientId) continue; // Свое состояние игрок знает лучше всех (Client Side Prediction)
|
||||||
|
|
||||||
|
ClientState remoteState;
|
||||||
|
remoteState.id = rId;
|
||||||
|
remoteState.lastUpdateServerTime = serverTime;
|
||||||
|
|
||||||
|
// Используем твой handle_full_sync, начиная со 2-го индекса (пропускаем ID в playerParts)
|
||||||
|
remoteState.handle_full_sync(playerParts, 1);
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> pLock(playersMutex);
|
||||||
|
remotePlayers[rId].add_state(remoteState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
void WebSocketClient::Send(const std::string& message) {
|
void WebSocketClient::Send(const std::string& message) {
|
||||||
|
|||||||
@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
#ifdef NETWORK
|
#ifdef NETWORK
|
||||||
|
|
||||||
// WebSocketClient.h
|
|
||||||
#include "NetworkInterface.h"
|
#include "NetworkInterface.h"
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <boost/beast/core.hpp>
|
#include <boost/beast/core.hpp>
|
||||||
@ -41,6 +40,12 @@ namespace ZL {
|
|||||||
std::vector<ProjectileInfo> pendingProjectiles_;
|
std::vector<ProjectileInfo> pendingProjectiles_;
|
||||||
std::mutex projMutex_;
|
std::mutex projMutex_;
|
||||||
|
|
||||||
|
std::vector<DeathInfo> pendingDeaths_;
|
||||||
|
std::mutex deathsMutex_;
|
||||||
|
|
||||||
|
std::vector<int> pendingRespawns_;
|
||||||
|
std::mutex respawnMutex_;
|
||||||
|
|
||||||
void startAsyncRead();
|
void startAsyncRead();
|
||||||
void processIncomingMessage(const std::string& msg);
|
void processIncomingMessage(const std::string& msg);
|
||||||
|
|
||||||
@ -55,7 +60,7 @@ namespace ZL {
|
|||||||
void doWrite();
|
void doWrite();
|
||||||
|
|
||||||
bool IsConnected() const override { return connected; }
|
bool IsConnected() const override { return connected; }
|
||||||
int GetClientId() const { return clientId; }
|
int GetClientId() const override { return clientId; }
|
||||||
|
|
||||||
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
|
std::unordered_map<int, ClientStateInterval> getRemotePlayers() override {
|
||||||
std::lock_guard<std::mutex> lock(playersMutex);
|
std::lock_guard<std::mutex> lock(playersMutex);
|
||||||
@ -68,6 +73,8 @@ namespace ZL {
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::vector<ProjectileInfo> getPendingProjectiles() override;
|
std::vector<ProjectileInfo> getPendingProjectiles() override;
|
||||||
|
std::vector<DeathInfo> getPendingDeaths() override;
|
||||||
|
std::vector<int> getPendingRespawns() override;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user