Modify path visualization

This commit is contained in:
Vladislav Khorev committed 2026-11-17 18:52:40 +06:00
1 parent 542fc191fa
commit 53328484b8
14 files changed
+175 -41

No files matched your search

+5 -1
View File
@@ -343,6 +343,8 @@ int main()
guardedMover.velocity = {
FRG::fp::from_raw_value(12345),
FRG::fp::from_raw_value(-6789)};
guardedMover.navigationOutcome =
FRG::PathFinder::PathOutcome::NearestReachable;
guardedMover.save(guardedJson);
FRG::CharacterState restoredGuardedMover;
restoredGuardedMover.load(guardedJson);
@@ -351,7 +353,9 @@ int main()
restoredGuardedMover.navigationRetryTicks !=
guardedMover.navigationRetryTicks ||
restoredGuardedMover.velocity.x.raw_value() != 12345 ||
restoredGuardedMover.velocity.y.raw_value() != -6789) {
restoredGuardedMover.velocity.y.raw_value() != -6789 ||
restoredGuardedMover.navigationOutcome !=
FRG::PathFinder::PathOutcome::NearestReachable) {
return fail("Character velocity did not round trip");
}
+24
View File
@@ -58,6 +58,30 @@ int main()
const Eigen::Vector3f end(5.f, 0.f, 5.f);
const auto path = pathFinder.findPathToNearest(start, end);
if (path.size() < 2) return fail("Path query did not produce a route");
const auto exactResult = pathFinder.findPathResult(
FRG::Vec3fp::fromEigen(start), FRG::Vec3fp::fromEigen(end));
if (exactResult.outcome !=
FRG::PathFinder::PathOutcome::ReachedExactGoal ||
exactResult.waypoints.size() < 2 ||
exactResult.endpoint.x != static_cast<FRG::fp>(end.x()) ||
exactResult.endpoint.z != static_cast<FRG::fp>(end.z())) {
return fail("Reachable destination was not reported as exact");
}
const auto blockedResult = pathFinder.findPathResult(
FRG::Vec3fp::fromEigen(start),
FRG::Vec3fp::fromEigen(Eigen::Vector3f(0.f, 0.f, 0.f)));
if (blockedResult.outcome !=
FRG::PathFinder::PathOutcome::NearestReachable ||
blockedResult.waypoints.empty() ||
!pathFinder.isWalkable(blockedResult.endpoint)) {
return fail("Blocked destination did not return a reachable partial path");
}
if ((blockedResult.endpoint -
FRG::Vec3fp::fromEigen(Eigen::Vector3f(0.f, 0.f, 0.f))).normSquared() <=
static_cast<FRG::fp>(0.01f * 0.01f)) {
return fail("Blocked destination was incorrectly reported as reached");
}
if (!pathFinder.isWalkable(Eigen::Vector3f(0.f, 0.f, 5.f)))
return fail("Walkability query failed");
if (path.back().y() != 2.5f)
+22 -5
View File
@@ -91,6 +91,7 @@ void CharacterState::stopInPlace() {
pathWaypoints.clear();
currentWaypointIndex = 0;
onArrivedCallbackName.clear();
navigationOutcome = PathFinder::PathOutcome::ReachedExactGoal;
movementBlockedTicks = 0;
navigationRetryTicks = 0;
velocity = Vec2fp(fp(0), fp(0));
@@ -128,11 +129,14 @@ void CharacterState::setTarget(
if (location.activeNavigationIndex < 0 ||
location.activeNavigationIndex >= static_cast<int>(location.navigationMaps.size())) {
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
navigationOutcome = PathFinder::PathOutcome::NoPath;
return;
}
pathWaypoints = location.navigationMaps[location.activeNavigationIndex]
.findPathToNearest(this->position, normalizedTarget);
const auto pathResult = location.navigationMaps[location.activeNavigationIndex]
.findPathResult(this->position, normalizedTarget);
pathWaypoints = pathResult.waypoints;
navigationOutcome = pathResult.outcome;
// Сразу целимся во второй элемент (индекс 1), так как индекс 0 — это точка старта
currentWaypointIndex = (pathWaypoints.size() > 1) ? 1 : 0;
@@ -160,11 +164,14 @@ void CharacterState::forceReplan(
if (location.activeNavigationIndex < 0 ||
location.activeNavigationIndex >= static_cast<int>(location.navigationMaps.size())) {
walkTarget = Vec3fp(position.x, static_cast<fp>(0.f), position.z);
navigationOutcome = PathFinder::PathOutcome::NoPath;
return;
}
pathWaypoints = location.navigationMaps[location.activeNavigationIndex]
.findPathToNearest(this->position, normalizedTarget);
const auto pathResult = location.navigationMaps[location.activeNavigationIndex]
.findPathResult(this->position, normalizedTarget);
pathWaypoints = pathResult.waypoints;
navigationOutcome = pathResult.outcome;
currentWaypointIndex = (pathWaypoints.size() > 1) ? 1 : 0;
movementBlockedTicks = 0;
@@ -316,14 +323,21 @@ CharacterUpdateEvents CharacterState::update(
currentWaypointIndex = 0;
if (completedPath &&
navigationOutcome == PathFinder::PathOutcome::ReachedExactGoal &&
(requestedWalkTarget - position).normSquared() > TARGET_REPLAN_THRESHOLD_SQUARED &&
!isPlayer) {
scheduleNextNavigationRetry();
}
if (completedPath && !onArrivedCallbackName.empty()) {
if (completedPath &&
navigationOutcome == PathFinder::PathOutcome::ReachedExactGoal &&
!onArrivedCallbackName.empty()) {
events.arrivedCallbackName = onArrivedCallbackName;
onArrivedCallbackName.clear();
}
else if (completedPath &&
navigationOutcome != PathFinder::PathOutcome::ReachedExactGoal) {
onArrivedCallbackName.clear();
}
if (faceTarget) {
Vec3fp toFace = faceTarget->position - position;
toFace.y = fp(0);
@@ -516,6 +530,7 @@ void CharacterState::save(nlohmann::json& out) const
}
out["pathWaypoints"] = std::move(wpArr);
out["currentWaypointIndex"] = currentWaypointIndex;
out["navigationOutcome"] = static_cast<int>(navigationOutcome);
out["homeDriftCheckTimer"] = static_cast<double>(homeDriftCheckTimer);
out["movementBlockedTicks"] = movementBlockedTicks;
out["navigationRetryTicks"] = navigationRetryTicks;
@@ -573,6 +588,8 @@ void CharacterState::load(const nlohmann::json& in)
}
}
currentWaypointIndex = in.value("currentWaypointIndex", currentWaypointIndex);
navigationOutcome = static_cast<PathFinder::PathOutcome>(
in.value("navigationOutcome", static_cast<int>(navigationOutcome)));
homeDriftCheckTimer = static_cast<fp>(in.value("homeDriftCheckTimer", static_cast<double>(homeDriftCheckTimer)));
movementBlockedTicks = in.value("movementBlockedTicks", movementBlockedTicks);
navigationRetryTicks = in.value("navigationRetryTicks", navigationRetryTicks);
+3
View File
@@ -132,6 +132,8 @@ public:
Vec3fp requestedWalkTarget;
std::vector<Vec3fp> pathWaypoints;
size_t currentWaypointIndex = 0;
PathFinder::PathOutcome navigationOutcome =
PathFinder::PathOutcome::ReachedExactGoal;
// Internal drift-check timer (serializable so it survives save/load).
fp homeDriftCheckTimer = static_cast<fp>(5.0f);
@@ -154,6 +156,7 @@ public:
std::vector<int> cooldownTicks = {});
bool isMoving() const;
const Vec3fp& getRequestedWalkTarget() const { return requestedWalkTarget; }
PathFinder::PathOutcome getNavigationOutcome() const { return navigationOutcome; }
Vec3fp getCurrentNavigationTarget() const;
void stopInPlace();
void setTarget(const Vec3fp& target,
+2 -2
View File
@@ -560,8 +560,8 @@ namespace FRG
// Use "ws://127.0.0.1:8080/" for a local development server.
static const char* const kMultiplayerServerUrl = "wss://api.shadowoverbishkek.com/server001/";
//static const char* const kMultiplayerServerUrl = "ws://127.0.0.1:8080/";
//static const char* const kMultiplayerServerUrl = "wss://api.shadowoverbishkek.com/server001/";
static const char* const kMultiplayerServerUrl = "ws://127.0.0.1:8080/";
WebsocketEndpoint endpoint;
if (!endpoint.parse(kMultiplayerServerUrl)) {
+29 -4
View File
@@ -140,6 +140,8 @@ namespace FRG
void Location::stopCharacter(Character& character)
{
if (player && character.entityId() == player->entityId())
pathVisualization.cancel();
gameServer_.submit(StopCharacterCommand{locationId_, character.entityId()});
}
@@ -2056,6 +2058,19 @@ namespace FRG
// Any new gameplay click invalidates the previous click feedback. Ground
// clicks and interactive-object clicks that require walking start a replacement.
pathVisualization.cancel();
auto findClickPath = [&](const Vec3fp& target) {
PathFinder::PathResult result;
result.endpoint = playerState->position;
result.waypoints = { playerState->position };
if (locationState->activeNavigationIndex >= 0 &&
locationState->activeNavigationIndex <
static_cast<int>(locationState->navigationMaps.size())) {
return locationState->navigationMaps[
locationState->activeNavigationIndex].findPathResult(
playerState->position, target);
}
return result;
};
//logger() << "[CLICK] Camera position: (" << camPos.x() << ", " << camPos.y() << ", " << camPos.z() << ")" << std::endl;
//logger() << "[CLICK] Ray direction: (" << rayDir.x() << ", " << rayDir.y() << ", " << rayDir.z() << ")" << std::endl;
@@ -2071,7 +2086,10 @@ namespace FRG
? clickedObject->state.interactionPosition
: Vec3fp::fromEigen(clickedObject->state.position);
setCharacterTarget(*player, interactionTarget);
pathVisualization.start(*player, interactionTarget.toEigen());
pathVisualization.start(
*player, interactionTarget.toEigen(),
findClickPath(interactionTarget),
PathVisualization::Style::InteractiveObject);
//logger() << "[CLICK] Player moving to object..." << std::endl;
}
else {
@@ -2111,6 +2129,7 @@ namespace FRG
pathVisualization.start(
*player,
clickedNpcState->position.toEigen(),
findClickPath(clickedNpcState->position),
PathVisualization::Style::Hostile);
}
// Must follow any destination: in lockstep the last order of
@@ -2142,7 +2161,10 @@ namespace FRG
//logger() << "[CLICK] NPC " << npcIndex << " out of talk range (distance " << distance
// << " > " << NPC_TALK_DISTANCE << "); walking to NPC..." << std::endl;
setCharacterTarget(*player, clickedNpcState->position);
pathVisualization.start(*player, clickedNpcState->position.toEigen());
pathVisualization.start(
*player, clickedNpcState->position.toEigen(),
findClickPath(clickedNpcState->position),
PathVisualization::Style::InteractiveObject);
gameServer_.submit(SetLocationTargetsCommand{
locationId_, std::string(), clickedNpc->entityId(),
std::string()});
@@ -2173,11 +2195,14 @@ namespace FRG
pathVisualization.start(
*player,
clickedTeleport->position,
findClickPath(Vec3fp::fromEigen(clickedTeleport->position)),
PathVisualization::Style::Teleport);
} else {
const Eigen::Vector3f clickedDestination(hit.x(), 0.f, hit.z());
setCharacterTarget(*player, Vec3fp::fromEigen(clickedDestination));
pathVisualization.start(*player, clickedDestination);
const Vec3fp destination = Vec3fp::fromEigen(clickedDestination);
setCharacterTarget(*player, destination);
pathVisualization.start(
*player, clickedDestination, findClickPath(destination));
gameServer_.submit(SetLocationTargetsCommand{
locationId_, std::string(), std::string(), std::string()});
if (onPlayerFloorWalk) onPlayerFloorWalk();
+8
View File
@@ -500,6 +500,14 @@ LocationSimulationEvents LocationGameState::update(
//Main player can interact with interactive objects
auto player = players.find("player1");
if (player != players.end() && player->second && player->second->enabled &&
!player->second->isMoving() &&
player->second->getNavigationOutcome() !=
PathFinder::PathOutcome::ReachedExactGoal) {
location->targetInteractiveObjectId.clear();
location->targetInteractNpcId.clear();
location->targetTeleportZoneId.clear();
}
if (!interactiveObjectsLocked &&
!location->targetInteractiveObjectId.empty() &&
player != players.end() && player->second && player->second->enabled) {
+1 -1
View File
@@ -216,7 +216,7 @@ FRG_AUTH_NOINLINE inline Bytes ppb()
return out;
}
FRG_AUTH_NOINLINE inline Bytes ppa()
FRG_AUTH_NOINLINE inline Bytes bba()
{
static const std::uint8_t masked[] = {0xc8, 0x09, 0x31, 0xf4, 0xf1, 0x80, 0xe5, 0x5b, 0x9d, 0x03};
Bytes out;
+1 -1
View File
@@ -28,7 +28,7 @@ struct InitialStateMessage {
};
// Server-side limit on client messages; exceeding it gets the player kicked.
inline constexpr std::size_t kMaxCommandsPerSecond = 20;
inline constexpr std::size_t kMaxCommandsPerSecond = 40;
struct DestinationInputMessage {
std::uint64_t clientSequence = 0;
+1 -1
View File
@@ -533,7 +533,7 @@ void WebsocketGameClient::update(std::int64_t)
std::string error;
InitialStateMessage initial;
if (parseInitialStateMessage(text, initial, error)) {
logger() << text << std::endl;
//logger() << text << std::endl;
if (!expectedCompatibilityFingerprint_.empty() &&
initial.compatibilityFingerprint !=
expectedCompatibilityFingerprint_) {
+41 -9
View File
@@ -257,8 +257,14 @@ namespace FRG {
ready = !navMesh.empty();
}
std::vector<Vec3fp> PathFinder::findPathToNearest(const Vec3fp& start3D, const Vec3fp& end3D) const {
if (!ready || !area.available) return { start3D };
PathFinder::PathResult PathFinder::findPathResult(
const Vec3fp& start3D, const Vec3fp& end3D) const {
PathResult result;
result.endpoint = start3D;
if (!ready || !area.available) {
result.waypoints = { start3D };
return result;
}
Vec2fp startPt(start3D.x, start3D.z);
Vec2fp targetPt(end3D.x, end3D.z);
@@ -268,7 +274,10 @@ namespace FRG {
if (startTri == -1) {
startPt = findClosestPointOnNavMesh(startPt, startTri, -1);
}
if (startTri == -1) return { start3D };
if (startTri == -1) {
result.waypoints = { start3D };
return result;
}
const int startComponent = navMesh[startTri].componentId;
@@ -276,36 +285,59 @@ namespace FRG {
// Если точка попала в препятствие ИЛИ в изолированную зону (другой остров),
// ищем ближайшую доступную точку именно на границе острова startComponent!
int endTri = findTriangleContaining(targetPt);
const bool exactTargetIsWalkable =
endTri != -1 && navMesh[endTri].componentId == startComponent;
if (endTri == -1 || navMesh[endTri].componentId != startComponent) {
targetPt = findClosestPointOnNavMesh(targetPt, endTri, startComponent);
}
if (endTri == -1) return { start3D };
if (endTri == -1) {
result.waypoints = { start3D };
return result;
}
// Если старт и конец оказались в одном треугольнике — идем по прямой
if (startTri == endTri) {
return {
result.waypoints = {
start3D,
Vec3fp(targetPt.x, floorY, targetPt.y)
};
result.endpoint = result.waypoints.back();
result.outcome = exactTargetIsWalkable
? PathOutcome::ReachedExactGoal
: PathOutcome::NearestReachable;
return result;
}
// 3. Поиск коридора из треугольников через A*
std::vector<int> triangleCorridor = runAStar(startTri, endTri, startPt, targetPt);
if (triangleCorridor.empty()) return { start3D };
if (triangleCorridor.empty()) {
result.waypoints = { start3D };
return result;
}
// 4. Сглаживание пути через Funnel Algorithm (Натянутая нить)
std::vector<Vec2fp> smoothPath2D = stringPullFunnel(startPt, targetPt, triangleCorridor);
// 5. Формируем выходной массив 3D точек
std::vector<Vec3fp> result;
result.reserve(smoothPath2D.size());
result.waypoints.reserve(smoothPath2D.size());
for (const auto& pt : smoothPath2D) {
result.emplace_back(pt.x, floorY, pt.y);
result.waypoints.emplace_back(pt.x, floorY, pt.y);
}
if (!result.waypoints.empty()) {
result.endpoint = result.waypoints.back();
result.outcome = exactTargetIsWalkable
? PathOutcome::ReachedExactGoal
: PathOutcome::NearestReachable;
}
return result;
}
std::vector<Vec3fp> PathFinder::findPathToNearest(
const Vec3fp& start3D, const Vec3fp& end3D) const {
return findPathResult(start3D, end3D).waypoints;
}
std::vector<Eigen::Vector3f> PathFinder::findPathToNearest(const Eigen::Vector3f& start, const Eigen::Vector3f& end) const {
auto pathFp = findPathToNearest(Vec3fp::fromEigen(start), Vec3fp::fromEigen(end));
std::vector<Eigen::Vector3f> out;
+17
View File
@@ -18,6 +18,22 @@ namespace FRG {
class PathFinder {
public:
enum class PathOutcome {
ReachedExactGoal,
NearestReachable,
NoPath
};
struct PathResult {
std::vector<Vec3fp> waypoints;
Vec3fp endpoint;
PathOutcome outcome = PathOutcome::NoPath;
bool reachedGoal() const {
return outcome == PathOutcome::ReachedExactGoal;
}
};
struct NavigationArea {
std::string name;
bool available = true;
@@ -52,6 +68,7 @@ namespace FRG {
void generateNavMesh();
// Основной метод поиска пути (плоскость XZ, Y — высота)
PathResult findPathResult(const Vec3fp& start3D, const Vec3fp& end3D) const;
std::vector<Vec3fp> findPathToNearest(const Vec3fp& start3D, const Vec3fp& end3D) const;
// Перегрузка для совместимости со старым Eigen-интерфейсом
+17 -17
View File
@@ -83,7 +83,7 @@ namespace FRG {
}
void PathVisualization::start(const Character& player, const Eigen::Vector3f& clickedDestination,
Style style)
const PathFinder::PathResult& pathResult, Style style)
{
cancel();
if (!enabled) return;
@@ -92,6 +92,9 @@ namespace FRG {
case Style::Hostile:
color = Eigen::Vector3f(1.0f, 0.20f, 0.03f);
break;
case Style::InteractiveObject:
color = Eigen::Vector3f(1.0f, 0.90f, 0.05f);
break;
case Style::Teleport:
color = Eigen::Vector3f(1.0f, 0.90f, 0.05f);
break;
@@ -99,33 +102,27 @@ namespace FRG {
color = Eigen::Vector3f(0.08f, 1.0f, 0.25f);
break;
}
destinationColor = color;
auto state = player.stateSnapshot();
if (!state) return;
std::vector<Eigen::Vector3f> route;
route.reserve(state->pathWaypoints.size() + 1);
route.reserve(pathResult.waypoints.size() + 1);
const Eigen::Vector3f renderPosition = player.renderPosition();
route.push_back(Eigen::Vector3f(renderPosition.x(), 0.0f, renderPosition.z()));
const size_t firstWaypoint = (std::min)(
state->currentWaypointIndex, state->pathWaypoints.size());
for (size_t i = firstWaypoint; i < state->pathWaypoints.size(); ++i) {
const Eigen::Vector3f& waypoint = state->pathWaypoints[i].toEigen();
for (const Vec3fp& waypointFp : pathResult.waypoints) {
const Eigen::Vector3f waypoint = waypointFp.toEigen();
route.push_back(Eigen::Vector3f(waypoint.x(), 0.0f, waypoint.z()));
}
const Eigen::Vector3f clickedPosition(
clickedDestination.x(), 0.0f, clickedDestination.z());
if (route.size() == 1 ||
(route.back() - clickedPosition).norm() > 0.5f) {
// A remote destination is not present in the replica yet, or the
// replica still contains the route for a previous click. Preview
// the new intent directly until authoritative waypoints catch up.
route.clear();
route.push_back(Eigen::Vector3f(
renderPosition.x(), 0.0f, renderPosition.z()));
route.push_back(clickedPosition);
}
destination = clickedPosition;
if (pathResult.outcome != PathFinder::PathOutcome::ReachedExactGoal &&
style != Style::Hostile &&
style != Style::InteractiveObject) {
destinationColor = Eigen::Vector3f(1.0f, 0.20f, 0.03f);
}
float totalLength = 0.0f;
for (size_t i = 1; i < route.size(); ++i) {
@@ -232,7 +229,10 @@ namespace FRG {
}
if (markerAlpha > 0.001f) {
const float markerScale = 0.72f + 0.28f * smoothStep(elapsedMs / kMarkerFadeInMs);
const float rgba[4] = { color.x(), color.y(), color.z(), markerAlpha * kMaxOpacity };
const float rgba[4] = {
destinationColor.x(), destinationColor.y(), destinationColor.z(),
markerAlpha * kMaxOpacity
};
renderer.RenderUniform4fv("uColor", rgba);
renderer.PushMatrix();
renderer.TranslateMatrix(destination + Eigen::Vector3f(0.0f, 0.05f, 0.0f));
+4
View File
@@ -1,5 +1,6 @@
#pragma once
#include "navigation/PathFinder.h"
#include "render/Renderer.h"
#include <cstdint>
@@ -15,6 +16,7 @@ namespace FRG {
enum class Style {
Movement,
Hostile,
InteractiveObject,
Teleport
};
@@ -23,6 +25,7 @@ namespace FRG {
bool isEnabled() const { return enabled; }
void start(const Character& player, const Eigen::Vector3f& clickedDestination,
const PathFinder::PathResult& pathResult,
Style style = Style::Movement);
void cancel();
void update(int64_t deltaMs);
@@ -41,6 +44,7 @@ namespace FRG {
float durationMs = 0.0f;
Eigen::Vector3f destination = Eigen::Vector3f::Zero();
Eigen::Vector3f color = Eigen::Vector3f(0.08f, 1.0f, 0.25f);
Eigen::Vector3f destinationColor = color;
std::vector<Dot> dots;
VertexRenderStruct dotMesh;
VertexRenderStruct destinationMesh;