Major clean up
This commit is contained in:
1 parent
6aff22ec53
commit
1a7e424085
16 files changed
+390
-490
No files matched your search
+49
-153
@@ -19,8 +19,6 @@
|
||||
#include "network/LocalClient.h"
|
||||
#endif
|
||||
|
||||
#include "network/RemotePlayer.h"
|
||||
|
||||
namespace ZL
|
||||
{
|
||||
#ifdef EMSCRIPTEN
|
||||
@@ -239,15 +237,8 @@ namespace ZL
|
||||
|
||||
uiManager.setSliderCallback("velocitySlider", [this](const std::string& name, float value) {
|
||||
int newVel = roundf(value * 10);
|
||||
if (newVel != Environment::shipSelectedVelocity) {
|
||||
if (newVel != Environment::shipState.selectedVelocity) {
|
||||
newShipVelocity = newVel;
|
||||
//Environment::shipSelectedVelocity = newVel;
|
||||
/*auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::system_clock::now().time_since_epoch()
|
||||
).count();
|
||||
std::string msg = "VEL:" + std::to_string(now_ms) + ":" + std::to_string(Environment::shipSelectedVelocity);
|
||||
msg = msg + ":" + formPingMessageContent();
|
||||
networkClient->Send(msg);*/
|
||||
}
|
||||
});
|
||||
|
||||
@@ -358,7 +349,7 @@ namespace ZL
|
||||
|
||||
// 1. Вектор направления от центра планеты к игроку (в мировых координатах)
|
||||
// Предполагаем, что планета в (0,0,0). Если нет, то (shipPosition - planetCenter)
|
||||
Vector3f playerDirWorld = Environment::shipPosition.normalized();
|
||||
Vector3f playerDirWorld = Environment::shipState.position.normalized();
|
||||
|
||||
// 2. Направление света в мировом пространстве
|
||||
//Vector3f worldLightDir = Vector3f(1.0f, -1.0f, -1.0f).normalized();
|
||||
@@ -470,7 +461,7 @@ namespace ZL
|
||||
renderer.LoadIdentity();
|
||||
renderer.TranslateMatrix({ 0,0, -1.0f * Environment::zoom });
|
||||
renderer.RotateMatrix(Environment::inverseShipMatrix);
|
||||
renderer.TranslateMatrix(-Environment::shipPosition);
|
||||
renderer.TranslateMatrix(-Environment::shipState.position);
|
||||
renderer.TranslateMatrix({ 0.f, 0.f, 45000.f });
|
||||
renderer.TranslateMatrix(boxCoordsArr[i].pos);
|
||||
renderer.RotateMatrix(boxCoordsArr[i].m);
|
||||
@@ -528,7 +519,7 @@ namespace ZL
|
||||
CheckGlError();
|
||||
|
||||
float skyPercent = 0.0;
|
||||
float distance = planetObject.distanceToPlanetSurface(Environment::shipPosition);
|
||||
float distance = planetObject.distanceToPlanetSurface(Environment::shipState.position);
|
||||
if (distance > 1500.f)
|
||||
{
|
||||
skyPercent = 0.0f;
|
||||
@@ -545,7 +536,7 @@ namespace ZL
|
||||
|
||||
drawCubemap(skyPercent);
|
||||
planetObject.draw(renderer);
|
||||
if (planetObject.distanceToPlanetSurface(Environment::shipPosition) > 100.f)
|
||||
if (planetObject.distanceToPlanetSurface(Environment::shipState.position) > 100.f)
|
||||
{
|
||||
glClear(GL_DEPTH_BUFFER_BIT);
|
||||
}
|
||||
@@ -602,7 +593,7 @@ namespace ZL
|
||||
renderer.TranslateMatrix({ 0,0, -1.0f * Environment::zoom });
|
||||
renderer.TranslateMatrix({ 0, -6.f, 0 }); //Ship camera offset
|
||||
renderer.RotateMatrix(Environment::inverseShipMatrix);
|
||||
renderer.TranslateMatrix(-Environment::shipPosition);
|
||||
renderer.TranslateMatrix(-Environment::shipState.position);
|
||||
|
||||
|
||||
Eigen::Vector3f relativePos = playerState.position;// -Environment::shipPosition;
|
||||
@@ -654,22 +645,25 @@ namespace ZL
|
||||
static float pingTimer = 0.0f;
|
||||
pingTimer += delta;
|
||||
if (pingTimer >= 1000.0f) {
|
||||
std::string pingMsg = "UPD:" + std::to_string(now_ms) + ":" + formPingMessageContent();
|
||||
std::string pingMsg = "UPD:" + std::to_string(now_ms) + ":" + Environment::shipState.formPingMessageContent();
|
||||
|
||||
networkClient->Send(pingMsg);
|
||||
std::cout << "Sending: " << pingMsg << std::endl;
|
||||
pingTimer = 0.0f;
|
||||
}
|
||||
|
||||
if (newShipVelocity != Environment::shipSelectedVelocity)
|
||||
{
|
||||
Environment::shipSelectedVelocity = newShipVelocity;
|
||||
//Handle input:
|
||||
|
||||
std::string msg = "UPD:" + std::to_string(now_ms) + ":" + formPingMessageContent();
|
||||
if (newShipVelocity != Environment::shipState.selectedVelocity)
|
||||
{
|
||||
Environment::shipState.selectedVelocity = newShipVelocity;
|
||||
|
||||
std::string msg = "UPD:" + std::to_string(now_ms) + ":" + Environment::shipState.formPingMessageContent();
|
||||
networkClient->Send(msg);
|
||||
//}
|
||||
}
|
||||
|
||||
float discreteMag;
|
||||
int discreteAngle;
|
||||
|
||||
if (Environment::tapDownHold) {
|
||||
float diffx = Environment::tapDownCurrentPos(0) - Environment::tapDownStartPos(0);
|
||||
@@ -681,140 +675,40 @@ namespace ZL
|
||||
if (rawMag > 10.0f) { // Мертвая зона
|
||||
// 1. Дискретизируем отклонение (0.0 - 1.0 с шагом 0.1)
|
||||
float normalizedMag = min(rawMag / maxRadius, 1.0f);
|
||||
float discreteMag = std::round(normalizedMag * 10.0f) / 10.0f;
|
||||
discreteMag = std::round(normalizedMag * 10.0f) / 10.0f;
|
||||
|
||||
// 2. Дискретизируем угол (0-359 градусов)
|
||||
// atan2 возвращает радианы, переводим в градусы
|
||||
float radians = atan2f(diffy, diffx);
|
||||
int discreteAngle = static_cast<int>(radians * 180.0f / M_PI);
|
||||
discreteAngle = static_cast<int>(radians * 180.0f / M_PI);
|
||||
if (discreteAngle < 0) discreteAngle += 360;
|
||||
|
||||
bool sendRotation = false;
|
||||
|
||||
std::cout << "OUTPUT discreteAngle=" << discreteAngle << std::endl;
|
||||
|
||||
// 3. Проверяем, изменились ли параметры значимо для отправки на сервер
|
||||
if (discreteAngle != Environment::lastSentAngle || discreteMag != Environment::lastSentMagnitude) {
|
||||
Environment::lastSentAngle = discreteAngle;
|
||||
Environment::lastSentMagnitude = discreteMag;
|
||||
|
||||
std::string msg = "UPD:" + std::to_string(now_ms) + ":" + formPingMessageContent();
|
||||
networkClient->Send(msg);
|
||||
std::cout << "Sending: " << msg << std::endl;
|
||||
}
|
||||
|
||||
// 4. Логика вращения (угловое ускорение)
|
||||
// Теперь используем discreteAngle и discreteMag как "цель" для набора угловой скорости
|
||||
// ... (код интерполяции скорости к этой цели)
|
||||
|
||||
// Вычисляем целевой вектор оси вращения из дискретного угла
|
||||
// В 3D пространстве экранные X и Y преобразуются в оси вращения вокруг Y и X соответственно
|
||||
float rad = static_cast<float>(discreteAngle) * static_cast<float>(M_PI) / 180.0f;
|
||||
|
||||
// Целевая угловая скорость (дискретная сила определяет модуль вектора)
|
||||
// Вектор {cos, sin, 0} дает нам направление отклонения джойстика
|
||||
Eigen::Vector3f targetAngularVelDir(sinf(rad), cosf(rad), 0.0f);
|
||||
Eigen::Vector3f targetAngularVelocity = targetAngularVelDir * discreteMag;
|
||||
|
||||
|
||||
Eigen::Vector3f diffVel = targetAngularVelocity - Environment::currentAngularVelocity;
|
||||
float diffLen = diffVel.norm();
|
||||
|
||||
if (diffLen > 0.0001f) {
|
||||
// Вычисляем, на сколько мы можем изменить скорость в этом кадре
|
||||
float maxChange = ANGULAR_ACCEL * static_cast<float>(delta);
|
||||
|
||||
if (diffLen <= maxChange) {
|
||||
// Если до цели осталось меньше, чем шаг ускорения — просто прыгаем в цель
|
||||
Environment::currentAngularVelocity = targetAngularVelocity;
|
||||
}
|
||||
else {
|
||||
// Линейно двигаемся в сторону целевого вектора
|
||||
Environment::currentAngularVelocity += (diffVel / diffLen) * maxChange;
|
||||
}
|
||||
}
|
||||
|
||||
// Применяем вращение к матрице корабля
|
||||
float speedScale = Environment::currentAngularVelocity.norm();
|
||||
if (speedScale > 0.0001f) {
|
||||
// Коэффициент чувствительности вращения
|
||||
const float ROTATION_SENSITIVITY = 0.002f;
|
||||
float deltaAlpha = speedScale * static_cast<float>(delta) * ROTATION_SENSITIVITY;
|
||||
|
||||
Eigen::Vector3f axis = Environment::currentAngularVelocity.normalized();
|
||||
Eigen::Quaternionf rotateQuat(Eigen::AngleAxisf(deltaAlpha, axis));
|
||||
|
||||
Environment::shipMatrix = Environment::shipMatrix * rotateQuat.toRotationMatrix();
|
||||
Environment::inverseShipMatrix = Environment::shipMatrix.inverse();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Если джойстик не зажат — сбрасываем дискретные значения и плавно замедляем вращение
|
||||
int discreteAngle = -1;
|
||||
float discreteMag = 0.0f;
|
||||
|
||||
if (discreteAngle != Environment::lastSentAngle || discreteMag != Environment::lastSentMagnitude) {
|
||||
Environment::lastSentAngle = discreteAngle;
|
||||
Environment::lastSentMagnitude = discreteMag;
|
||||
|
||||
std::string msg = "UPD:" + std::to_string(now_ms) + ":" + formPingMessageContent();
|
||||
networkClient->Send(msg);
|
||||
std::cout << "Sending: " << msg << std::endl;
|
||||
}
|
||||
|
||||
|
||||
float currentSpeed = Environment::currentAngularVelocity.norm();
|
||||
|
||||
if (currentSpeed > 0.0001f) {
|
||||
float drop = ANGULAR_ACCEL * static_cast<float>(delta);
|
||||
if (currentSpeed <= drop) {
|
||||
Environment::currentAngularVelocity = Eigen::Vector3f::Zero();
|
||||
}
|
||||
else {
|
||||
// Уменьшаем модуль вектора, сохраняя направление
|
||||
Environment::currentAngularVelocity -= (Environment::currentAngularVelocity / currentSpeed) * drop;
|
||||
}
|
||||
}
|
||||
|
||||
// Применяем остаточное вращение (инерция)
|
||||
float speedScale = Environment::currentAngularVelocity.norm();
|
||||
if (speedScale > 0.0001f) {
|
||||
float deltaAlpha = speedScale * static_cast<float>(delta) * 0.002f;
|
||||
Eigen::Quaternionf rotateQuat(Eigen::AngleAxisf(deltaAlpha, Environment::currentAngularVelocity.normalized()));
|
||||
Environment::shipMatrix = Environment::shipMatrix * rotateQuat.toRotationMatrix();
|
||||
Environment::inverseShipMatrix = Environment::shipMatrix.inverse();
|
||||
}
|
||||
}
|
||||
|
||||
float shipDesiredVelocity = Environment::shipSelectedVelocity * 100.f;
|
||||
|
||||
if (Environment::shipVelocity < shipDesiredVelocity)
|
||||
{
|
||||
Environment::shipVelocity += delta * SHIP_ACCEL;
|
||||
if (Environment::shipVelocity > shipDesiredVelocity)
|
||||
else
|
||||
{
|
||||
Environment::shipVelocity = shipDesiredVelocity;
|
||||
discreteAngle = -1;
|
||||
discreteMag = 0.0f;
|
||||
}
|
||||
}
|
||||
else if (Environment::shipVelocity > shipDesiredVelocity)
|
||||
else
|
||||
{
|
||||
Environment::shipVelocity -= delta * SHIP_ACCEL;
|
||||
if (Environment::shipVelocity < shipDesiredVelocity)
|
||||
{
|
||||
Environment::shipVelocity = shipDesiredVelocity;
|
||||
}
|
||||
discreteAngle = -1;
|
||||
discreteMag = 0.0f;
|
||||
}
|
||||
|
||||
// Движение вперед (существующая логика)
|
||||
if (fabs(Environment::shipVelocity) > 0.01f)
|
||||
{
|
||||
Vector3f velocityDirection = { 0,0, -Environment::shipVelocity * delta / 1000.f };
|
||||
Vector3f velocityDirectionAdjusted = Environment::shipMatrix * velocityDirection;
|
||||
Environment::shipPosition = Environment::shipPosition + velocityDirectionAdjusted;
|
||||
|
||||
if (discreteAngle != Environment::shipState.discreteAngle || discreteMag != Environment::shipState.discreteMag) {
|
||||
Environment::shipState.discreteAngle = discreteAngle;
|
||||
Environment::shipState.discreteMag = discreteMag;
|
||||
|
||||
std::string msg = "UPD:" + std::to_string(now_ms) + ":" + Environment::shipState.formPingMessageContent();
|
||||
networkClient->Send(msg);
|
||||
std::cout << "Sending: " << msg << std::endl;
|
||||
}
|
||||
|
||||
Environment::shipState.simulate_physics(delta);
|
||||
Environment::inverseShipMatrix = Environment::shipState.rotation.inverse();
|
||||
|
||||
for (auto& p : projectiles) {
|
||||
if (p && p->isActive()) {
|
||||
p->update(static_cast<float>(delta), renderer);
|
||||
@@ -825,7 +719,7 @@ namespace ZL
|
||||
for (const auto& p : projectiles) {
|
||||
if (p && p->isActive()) {
|
||||
Vector3f worldPos = p->getPosition();
|
||||
Vector3f rel = worldPos - Environment::shipPosition;
|
||||
Vector3f rel = worldPos - Environment::shipState.position;
|
||||
Vector3f camPos = Environment::inverseShipMatrix * rel;
|
||||
projCameraPoints.push_back(camPos);
|
||||
}
|
||||
@@ -852,16 +746,17 @@ namespace ZL
|
||||
|
||||
explosionEmitter.update(static_cast<float>(delta));
|
||||
if (shipAlive) {
|
||||
float distToSurface = planetObject.distanceToPlanetSurface(Environment::shipPosition);
|
||||
float distToSurface = planetObject.distanceToPlanetSurface(Environment::shipState.position);
|
||||
if (distToSurface <= 0.0f) {
|
||||
|
||||
Vector3f localForward = { 0,0,-1 };
|
||||
Vector3f worldForward = (Environment::shipMatrix * localForward).normalized();
|
||||
Vector3f worldForward = (Environment::shipState.rotation * localForward).normalized();
|
||||
const float backDistance = 400.0f;
|
||||
Environment::shipPosition = Environment::shipPosition - worldForward * backDistance;
|
||||
Environment::shipState.position = Environment::shipState.position - worldForward * backDistance;
|
||||
|
||||
shipAlive = false;
|
||||
gameOver = true;
|
||||
Environment::shipVelocity = 0.0f;
|
||||
Environment::shipState.velocity = 0.0f;
|
||||
showExplosion = true;
|
||||
|
||||
explosionEmitter.setUseWorldSpace(false);
|
||||
@@ -878,8 +773,8 @@ namespace ZL
|
||||
this->uiGameOverShown = false;
|
||||
this->showExplosion = false;
|
||||
this->explosionEmitter.setEmissionPoints(std::vector<Vector3f>());
|
||||
Environment::shipPosition = Vector3f{ 0, 0, 45000.f };
|
||||
Environment::shipVelocity = 0.0f;
|
||||
Environment::shipState.position = Vector3f{ 0, 0, 45000.f };
|
||||
Environment::shipState.velocity = 0.0f;
|
||||
uiManager.popMenu();
|
||||
std::cerr << "Game restarted\n";
|
||||
});
|
||||
@@ -900,7 +795,7 @@ namespace ZL
|
||||
for (int i = 0; i < boxCoordsArr.size(); ++i) {
|
||||
if (!boxAlive[i]) continue;
|
||||
Vector3f boxWorld = boxCoordsArr[i].pos + Vector3f{ 0.0f, 0.0f, 45000.0f };
|
||||
Vector3f diff = Environment::shipPosition - boxWorld;
|
||||
Vector3f diff = Environment::shipState.position - boxWorld;
|
||||
float thresh = shipCollisionRadius + boxCollisionRadius;
|
||||
if (diff.squaredNorm() <= thresh * thresh) {
|
||||
boxAlive[i] = false;
|
||||
@@ -911,7 +806,7 @@ namespace ZL
|
||||
boxRenderArr[i].texCoordVBO.reset();
|
||||
showExplosion = true;
|
||||
|
||||
Vector3f rel = boxWorld - Environment::shipPosition;
|
||||
Vector3f rel = boxWorld - Environment::shipState.position;
|
||||
Vector3f camPos = Environment::inverseShipMatrix * rel;
|
||||
explosionEmitter.setUseWorldSpace(true);
|
||||
explosionEmitter.setEmissionPoints(std::vector<Vector3f>{ boxWorld });
|
||||
@@ -936,11 +831,11 @@ namespace ZL
|
||||
const float size = 0.5f;
|
||||
|
||||
Vector3f localForward = { 0,0,-1 };
|
||||
Vector3f worldForward = (Environment::shipMatrix * localForward).normalized();
|
||||
Vector3f worldForward = (Environment::shipState.rotation * localForward).normalized();
|
||||
|
||||
for (const auto& lo : localOffsets) {
|
||||
Vector3f worldPos = Environment::shipPosition + Environment::shipMatrix * lo;
|
||||
Vector3f worldVel = worldForward * (projectileSpeed + Environment::shipVelocity);
|
||||
Vector3f worldPos = Environment::shipState.position + Environment::shipState.rotation * lo;
|
||||
Vector3f worldVel = worldForward * (projectileSpeed + Environment::shipState.velocity);
|
||||
|
||||
for (auto& p : projectiles) {
|
||||
if (!p->isActive()) {
|
||||
@@ -1097,6 +992,7 @@ namespace ZL
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
std::string Game::formPingMessageContent()
|
||||
{
|
||||
Eigen::Quaternionf q(Environment::shipMatrix);
|
||||
@@ -1117,7 +1013,7 @@ namespace ZL
|
||||
+ std::to_string(Environment::lastSentAngle);
|
||||
|
||||
return pingMsg;
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
} // namespace ZL
|
||||
Reference in new issue
Block a user