Commit Graph
2 Commits
Author SHA1 Message Date
Raka HouriantoandGitHub 6dd9eb8323 Reuse cached TradeShip paths for motion plans (#4654)
**Approved and assigned issue:** #4643

Resolves #4643

## Description

`TradeShipExecution` currently calls `WaterPathFinder.next()` and then
performs a second one-shot `findPath()` for the same destination when it
records a motion plan. `next()` has already calculated and cached the
traversal route, so the second call repeats the expensive water-path
calculation solely to recreate the route for the client.

This change lets `PathFinderStepper` return a copy of the active path
after `next()` advances it. Numeric paths remain `Uint32Array`s,
matching the compact representation already used by the stepper and
supported by motion-plan packing.

`WaterPathFinder.pathForTraversal()` retains the existing second
water-graph freshness check. If the graph refresh replaces the stepper
between `next()` and motion-plan recording, it falls back to the
original one-shot query. Otherwise it returns the cached remainder. The
method also normalizes the result to begin at the tile returned by
`next()`, so `TradeShipExecution` does not need to mutate the path.

`findPath()` remains a stateless one-shot query. The change is limited
to TradeShip and the minimal pathfinder support; it includes no
TransportShip changes.

## Performance

Current upstream `main` (`da2e0918`) was compared with the same commit
plus only this change. Each variant was run once per replay on macOS
arm64 with CPU profiling disabled. The replay intents were identical
between variants, and the current-client final hash and hash tick
matched for every pair.

| Game ID | Workload | Whole replay | TradeShip execution | Throughput |
| --- | --- | ---: | ---: | ---: |
| `DWmULj4H` | Antarctica, TradeShip-heavy | 68.960 s → 60.271 s
(**-12.60%**) | 18.981 s → 11.844 s (**-37.60%**) | 446 → 510 ticks/s |
| `efA7EZv9` | Australia | 14.660 s → 14.346 s (**-2.14%**) | 1.216 s →
0.920 s (**-24.34%**) | 441 → 450 ticks/s |
| `waxvMCue` | Svalmel | 16.666 s → 16.537 s (**-0.77%**) | 1.169 s →
0.931 s (**-20.36%**) | 551 → 555 ticks/s |

Matched current-client final hashes:

- `DWmULj4H`: `49212092378184090` at tick 31,060
- `efA7EZv9`: `82334231069422620` at tick 6,760
- `waxvMCue`: `34697926985435590` at tick 9,480

## Validation

- `npm run build-prod`
- Full Node 24 coverage suite: 174 test files and 2,091 tests passed
- Full ESLint check
- Full Prettier check
- Current-main baseline/patched replay hashes matched for all three
benchmark games

## Checklist

- [x] No UI updates; screenshots are not applicable.
- [x] No user-facing text was added or changed.
- [x] Relevant tests were added.

## LLM disclosure

This change, PR description, and benchmark analysis were authored by
**GPT-5.6 Sol**, an LLM, under human direction.
2026-07-21 15:57:19 -07:00
Arkadiusz SygulskiandGitHub 0e3ced3bfa Pathfinding Refactor pt. 2 (#2866)
## Playtest

https://pf-pt-2.openfront.dev/

## Pathfinding Refactor pt. 2

<img width="1536" height="1024" alt="image"
src="https://github.com/user-attachments/assets/9477958e-54b7-4c83-b317-ba789e809e9e"
/>


This is a follow-up to a previous PR introducing pathfinding changes.
This time, it introduces a complete refactor of `pathfinding` directory
and breakdown into composable pieces.

### Unified PathFinder interface

`PathFinder<T>` and `SteppingPathFinder<T>` are introduced to unify
**all** pathfinding across the application. First one exposes complete
path, while stepping variant allows the callee to iterate over the path
by calling `.next`. All pathfinders share this one common interface,
which makes them easy to use in any scenario -
`PathFinding.Water(game).search(from, to)`.

`SteppingPathFinder<T>` extends `PathFinder<T>` with an ability to
iterate over the path. It handles caching, storing current index and
invalidation. This allows the units to not care about the inner workings
of the pathfinder and just call `pf.next(current, target)` and receive
instructions on what to do next.

### Common entry point

All pathfinders are now exposed from common `PathFinding` entrypoint:

- `PathFinding.Water`
- `PathFinding.Rail`
- `PathFinding.Stations`
- `PathFinding.Rail`

Additional entry point is introduced for pathfinders which need to work
both in the worker, but also on the frontend, which lacks `Game`
interface. Currently only `UniversalPathFinding.Parabola` is available.

### Spatial Query

New module has been introduced close to `pathfinding` - `SpatialQuery`.
It aims to resolve any questions game may have about finding tiles
meeting criteria. Currently `SpatialQuery.closestShore(player, target)`
and `SpatialQuery.closestShoreByWater(player, target)` are available -
they help answering questions about naval invasion: "What is the best
landing location from user's click?" and "Which our tile should be used
to launch the transport ship?". Under the hood they use very similar
mechanics to pathfinding, so it felt right to put them close by.

### Modular architecture

Pathfinders now support transformers: `MiniMapTransformer`,
`ShoreCoercingTransformer`, `ComponentCheckTransformer`,
`SmoothingTransformer`. Transformers functions like a middleware in the
pathfinding chain. They wrap around the pathfinder and provide
additional functionality. This allows the pathfinder to focus on
actually finding the path instead of doing unrelated things.

Example chain for simple (A*) water pathfinding:
```ts
static WaterSimple(game: Game): SteppingPathFinder<TileRef> {
  const miniMap = game.miniMap();
  const pf = new AStarWater(miniMap);

  return PathFinderBuilder.create(pf)
    .wrap((pf) => new ShoreCoercingTransformer(pf, miniMap))
    .wrap((pf) => new MiniMapTransformer(pf, game.map(), miniMap))
    .buildWithStepper(tileStepperConfig(game));
}
```

The Pathfinder - here `AStarWater` - does not care about the conversion
between minimap and main map tiles. It also does not care if the source
or destination is a land tile. The transformers take care of that. The
pathfinder gets a set of valid coordinates and produces the path -
that's it.

Modular approach makes working on a particular set of utilities much
easier - for example map upscaling is handled consistently across all
pathfinders. Additionally, the pathfinders are not tied to the
particular map resolution used. Pass them a different map and they will
work the same.

### Algorithms

Algorithms used are neatly organized inside
`src/core/pathfinding/algorithms`. They are prefixed with the algorithm
name and suffixed with the use case. File without suffix exposes generic
version ready to traverse any graph with adapters. Specialized versions
either use an adapter or inline logic when performance is critical -
using adapters leads to 20-30% performance loss.

The directory includes `A*` and `BFS` but also other useful utils, such
as `AbstractGraph` used to generate... an abstract graph on top of the
tile map and `ConnectedComponents` helping to identify whether two tiles
are connected by a path without actually computing the path.

### Playground

The playground have been updated with new algorithms, including tweaked
very greedy `A*`.

<img width="2175" height="1424" alt="image"
src="https://github.com/user-attachments/assets/1f833651-0024-4299-bf86-882f5368358c"
/>

### Tests

Yeah, there are some, a little too many if I say so myself. But there
are no useless tests. I had to ensure refactored code works somehow
reliably. This PR comes with trust me bro guarantee, but I would
appreciate someone confirming **naval invasions, nukes (esp. MIRV) and
warships**.

### Discord
`moleole`

GL & HF
2026-01-11 20:11:14 -08:00