Files
shadow-over-bishkek001/PATHFINDING.md
T

296 lines
11 KiB
Markdown

# Pathfinding and Character Avoidance
This document describes the current authoritative navigation and movement
system. The old grid-based implementation is no longer used. Static routes are
computed on a triangulated navigation mesh, while moving characters avoid each
other with a fixed-point ORCA solver.
## 1. Authoritative update flow
Navigation belongs to the game state, not the renderer:
1. A destination command is applied before a fixed 100 ms simulation tick.
2. `CharacterState::setTarget()` asks the active `PathFinder` for a route.
3. `CharacterState::update()` follows the current waypoint and computes
`preferredVelocity`.
4. `LocationGameState::update()` gathers all enabled characters in stable ID
order and runs one ORCA step.
5. ORCA writes the accepted position and velocity back to each
`CharacterState`.
6. Navigation requests produced by NPC logic are applied by
`InternalGameServer` as deterministic simulation consequences.
7. A new immutable snapshot is published for rendering.
Rendering interpolates between completed snapshots in `Character.cpp`. That
interpolation uses each client's wall clock and can look slightly different
between clients; it never changes authoritative positions.
## 2. Fixed-point math
Gameplay navigation uses:
```cpp
using fp = fpm::fixed<std::int32_t, std::int64_t, 12>;
```
`Vec2fp` is used for XZ navigation and velocity. `Vec3fp` is used for world
positions and waypoints. With 12 fractional bits, one raw unit is 1/4096.
Path following, waypoint tests, ORCA constraints, collision correction,
movement displacement, and facing calculations use fixed-point operations.
Floating-point conversions remain at content and presentation boundaries.
The navigation-mesh build is not fully fixed-point:
- Input JSON numbers are converted to fixed point.
- Polygon clipping uses scaled `int64_t` coordinates.
- CDT triangulation temporarily uses `double`.
- Triangle vertices and centers are converted back to fixed point before path
queries.
Multiplayer therefore requires matching executable and content builds.
## 3. Navigation configuration
Each navigation JSON contains:
```json
{
"areas": [
{
"name": "main",
"available": true,
"polygon": [[-10, -10], [10, -10], [10, 10], [-10, 10]]
}
],
"obstacles": [
{
"name": "wall",
"polygon": [[1, 1], [2, 1], [2, 4], [1, 4]]
}
],
"floorY": 0
}
```
Only the first navigation area is currently loaded. A location may list
multiple navigation JSON files; `LocationNetworkState::activeNavigationIndex`
selects the active map.
The shared character radius is:
```cpp
kCharacterAgentRadius = 0.42f
```
## 4. Building the navigation mesh
`PathFinder::generateNavMesh()` performs these steps:
1. Convert area and obstacle vertices to Clipper2 `int64_t` coordinates using
`CLIPPER_SCALE = 10000`.
2. Subtract obstacle polygons from the outer walkable polygon.
3. Erode the result inward by `kCharacterAgentRadius`.
4. Rebuild polygon and hole hierarchy with `PolyTree64`.
5. Run constrained Delaunay triangulation with CDT.
6. Convert generated triangles to fixed-point `NavTriangle` records.
7. Store edge neighbors and mark connected components with deterministic BFS.
Each triangle contains three vertices, a fixed-point center, three neighbor
indices, and a connected-component ID.
## 5. Route queries
`PathFinder::findPathToNearest(start, end)`:
1. Finds the triangle containing the start.
2. If necessary, clamps the start to the closest navigation-mesh boundary.
3. Finds the destination triangle.
4. If the destination is outside the mesh or on another connected component,
clamps it to the closest boundary of the start component.
5. Runs A* through adjacent triangles.
6. Applies the funnel algorithm to the triangle corridor.
7. Returns fixed-point 3D waypoints at `floorY`.
If start and destination are in the same triangle, the route is a direct
segment. If no valid start or corridor exists, the result keeps the character
at its current position.
### A* ordering
A* uses fixed-point distances between triangle centers. Queue records compare:
1. total estimated cost (`fScore`);
2. triangle ID.
Neighbor edges are visited in stored edge order. The explicit triangle-ID tie
break prevents priority-queue ordering from depending on allocation addresses.
### Funnel smoothing
The corridor's shared edges become left/right portals. The Simple Stupid
Funnel Algorithm emits only the corners needed to stay inside the corridor,
plus the exact clamped destination.
## 6. Path following
`CharacterState` stores:
- `requestedWalkTarget`: the original destination intent;
- `walkTarget`: the reachable route endpoint;
- `pathWaypoints`: the current smoothed route;
- `currentWaypointIndex`: the active waypoint;
- `velocity`: the previous accepted ORCA velocity;
- `preferredVelocity`: the velocity requested for the current tick.
`CharacterState::update()` advances waypoints within
`kWalkThreshold = 0.05 m`. The desired speed is the smaller of `walkSpeed` and
the speed needed to reach the waypoint in the current tick. Reaching the final
waypoint clears the path and produces the optional arrival event.
Destination requests within 0.25 m of the existing request are deduplicated.
NPC navigation retries use a stable-ID-shuffled sequence of cooldown ticks.
`stopInPlace()` clears the route and callback, targets the current position,
resets blockage and retry state, and clears both movement velocities.
## 7. Character avoidance with ORCA
Static routing does not insert moving characters into the navigation mesh.
Instead, `LocationGameState` creates one `OrcaAgent` per enabled, living
character after every character has computed its preferred velocity.
Agents are sorted by stable character ID before solving. Each agent stores:
- current XZ position;
- previous accepted velocity;
- preferred velocity;
- collision radius and maximum speed;
- stationary/combat state;
- player/hostile avoidance policy.
Current ORCA constants:
| Setting | Value |
|---|---:|
| Simulation step | 0.1 s |
| Time horizon | 0.6 s |
| Neighbor distance | 4.0 m |
| Avoidance radius factor | 0.85 |
| Parallel-line tolerance | 0.001 |
| Constant-speed validity tolerance | 0.1 m/s |
For each nearby character, ORCA constructs a permitted velocity half-plane.
Constraints are solved with the standard three-stage linear program. Exact
overlap uses the agents' stable sorted indices to choose a fallback direction.
### Character policies
- Hostile attacking NPCs are treated as ghosts for avoidance policy.
- Non-ghost characters do not add braking constraints for ghosts.
- Ghosts take 95% of avoidance responsibility around non-ghost characters.
- A moving character takes full responsibility around a stationary character.
- Non-ghost characters try deterministic candidate angles from 0 through
±90 degrees while preserving preferred speed; if none is valid, they stop.
### Hard-overlap correction
After applying velocities, `resolveHardCollisions()` runs two stable pairwise
passes. Overlapping characters are separated along their fixed-point normal.
Non-ghost characters push ghosts completely; other pairs split correction
according to stationary weights.
Finally, any character outside the active navigation mesh is clamped back to
its closest boundary.
## 8. Movement and animation state
After ORCA:
- accepted position and `newVel` become authoritative state;
- `movedLastTick` is set from actual displacement;
- `movementBlockedTicks` is reset after movement or incremented when a desired
move produced no displacement;
- walking/standing animation state follows actual movement;
- facing follows the accepted ORCA velocity.
`facingAngle` and `targetFacingAngle` are explicitly initialized. This is
important because the underlying fixed-point library's default constructor does
not initialize its raw integer.
## 9. Deterministic lockstep requirements
All clients must begin a tick with identical state. The following movement
history is serialized in schema version 6:
- exact raw fixed-point `velocity` components;
- path targets, waypoints, and waypoint index;
- `movedLastTick` and blocked/retry counters;
- deterministic retry sequence and cursor;
- animation frame, state, `resetAnim`, and attack phase;
- facing and target-facing angles.
Velocity is stored as raw fixed-point integers rather than decimal floats. It
must be present in late-join and reconnect snapshots because the next ORCA step
uses previous velocity directly. `resetAnim` and `attack` are also persisted
because they affect the next animation/combat update after a snapshot.
Character and interactive-object maps may use `unordered_map`, but simulation
collects and sorts stable IDs before order-sensitive updates. ORCA sorts agents
again defensively.
## 10. Compatibility and divergence diagnostics
The manual campaign compatibility label is combined with:
- deterministic simulation version;
- campaign and multiplayer slot metadata;
- ordered location/navigation configuration;
- authoritative configuration and start-state bytes;
- referenced animation bytes.
The resulting fingerprint is logged by server and client. Connections are
rejected when fingerprints differ, preventing two Release directories with
different navigation resources from entering lockstep.
After every server tick, the server sends a canonical authoritative-state hash.
Each client computes the same hash after applying that tick and logs:
```text
[network] Lockstep divergence at tick N: server=..., client=...
```
The hash excludes the persistence timestamp but includes serialized movement
history. Compare authoritative raw positions at the same completed tick ID;
do not compare interpolated render-frame positions.
## 11. Known constraints
- Navigation-mesh generation still depends on Clipper2/CDT and temporary
`double` values, so cross-toolchain identity is not guaranteed.
- Triangle IDs are taken from CDT output and are used as A* tie breakers.
- Only one navigation area from each JSON file is currently loaded.
- ORCA is local collision avoidance, not cooperative space-time planning.
Dense opposing traffic can still stop temporarily.
- Runtime area and obstacle changes rebuild or mutate local navigation state
and must be applied identically on every lockstep replica.
## 12. Main files and tests
- `src/navigation/PathFinder.h/.cpp`: navmesh generation, A*, clamping, funnel.
- `src/navigation/fpmutils.h/.cpp`: fixed-point vectors and conversions.
- `src/CharacterState.h/.cpp`: path state, waypoint following, serialization.
- `src/OrcaSolver.h`: deterministic local avoidance and overlap correction.
- `src/LocationGameState.h/.cpp`: stable character collection and ORCA update.
- `src/game_server/InternalGameServer.cpp`: authoritative tick consequences.
- `src/game_server/NetworkProtocol.cpp`: tick messages and canonical hashes.
- `src/game_server/WebsocketGameClient.cpp`: replica advancement and hash check.
Release regression coverage includes:
- fixed-point velocity round-trip;
- compatibility fingerprint sensitivity to navigation-map order;
- two-client late join after ORCA movement has already started;
- exact raw position and velocity equality across server and both replicas;
- pathfinder, state, protocol, lockstep, and server smoke tests.