mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-21 18:06:44 +00:00
0e3ced3bfa
## 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
180 lines
5.9 KiB
TypeScript
180 lines
5.9 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import { PathFinderStepper } from "../../../src/core/pathfinding/PathFinderStepper";
|
|
import { PathFinder, PathStatus } from "../../../src/core/pathfinding/types";
|
|
|
|
describe("PathFinderStepper", () => {
|
|
function createMockFinder(
|
|
pathMap: Map<string, number[]>,
|
|
): PathFinder<number> {
|
|
return {
|
|
findPath(from: number | number[], to: number): number[] | null {
|
|
const fromTile = Array.isArray(from) ? from[0] : from;
|
|
const key = `${fromTile}->${to}`;
|
|
return pathMap.get(key) ?? null;
|
|
},
|
|
};
|
|
}
|
|
|
|
describe("next", () => {
|
|
it("returns COMPLETE when at destination", () => {
|
|
const pathMap = new Map<string, number[]>();
|
|
const stepper = new PathFinderStepper(createMockFinder(pathMap));
|
|
|
|
const result = stepper.next(5, 5);
|
|
|
|
expect(result.status).toBe(PathStatus.COMPLETE);
|
|
expect((result as { node: number }).node).toBe(5);
|
|
});
|
|
|
|
it("returns NEXT with path nodes sequentially", () => {
|
|
const pathMap = new Map<string, number[]>([["1->4", [1, 2, 3, 4]]]);
|
|
const stepper = new PathFinderStepper(createMockFinder(pathMap));
|
|
|
|
// First step: 1 -> 4, returns 2
|
|
const result1 = stepper.next(1, 4);
|
|
expect(result1.status).toBe(PathStatus.NEXT);
|
|
expect((result1 as { node: number }).node).toBe(2);
|
|
|
|
// Second step: from 2, returns 3
|
|
const result2 = stepper.next(2, 4);
|
|
expect(result2.status).toBe(PathStatus.NEXT);
|
|
expect((result2 as { node: number }).node).toBe(3);
|
|
|
|
// Third step: from 3, returns 4
|
|
const result3 = stepper.next(3, 4);
|
|
expect(result3.status).toBe(PathStatus.NEXT);
|
|
expect((result3 as { node: number }).node).toBe(4);
|
|
|
|
// Fourth step: at destination
|
|
const result4 = stepper.next(4, 4);
|
|
expect(result4.status).toBe(PathStatus.COMPLETE);
|
|
});
|
|
|
|
it("returns NOT_FOUND when no path exists", () => {
|
|
const pathMap = new Map<string, number[]>();
|
|
const stepper = new PathFinderStepper(createMockFinder(pathMap));
|
|
|
|
const result = stepper.next(1, 99);
|
|
|
|
expect(result.status).toBe(PathStatus.NOT_FOUND);
|
|
});
|
|
|
|
it("recomputes path when moved off-path", () => {
|
|
// Path from 1->5 goes through 2,3,4
|
|
// Path from 10->5 goes through 9,8,7,6
|
|
const pathMap = new Map<string, number[]>([
|
|
["1->5", [1, 2, 3, 4, 5]],
|
|
["10->5", [10, 9, 8, 7, 6, 5]],
|
|
]);
|
|
const stepper = new PathFinderStepper(createMockFinder(pathMap));
|
|
|
|
// Start on path 1->5
|
|
const result1 = stepper.next(1, 5);
|
|
expect(result1.status).toBe(PathStatus.NEXT);
|
|
expect((result1 as { node: number }).node).toBe(2);
|
|
|
|
// Move off-path to tile 10 (not on original path)
|
|
// Should recompute using path from 10->5
|
|
const result2 = stepper.next(10, 5);
|
|
expect(result2.status).toBe(PathStatus.NEXT);
|
|
expect((result2 as { node: number }).node).toBe(9);
|
|
});
|
|
|
|
it("recomputes path when destination changes", () => {
|
|
const pathMap = new Map<string, number[]>([
|
|
["1->5", [1, 2, 3, 4, 5]],
|
|
["2->9", [2, 6, 7, 8, 9]],
|
|
]);
|
|
const stepper = new PathFinderStepper(createMockFinder(pathMap));
|
|
|
|
// Start on path 1->5
|
|
const result1 = stepper.next(1, 5);
|
|
expect(result1.status).toBe(PathStatus.NEXT);
|
|
expect((result1 as { node: number }).node).toBe(2);
|
|
|
|
// Change destination to 9 (from current position 2)
|
|
const result2 = stepper.next(2, 9);
|
|
expect(result2.status).toBe(PathStatus.NEXT);
|
|
expect((result2 as { node: number }).node).toBe(6);
|
|
});
|
|
});
|
|
|
|
describe("invalidate", () => {
|
|
it("clears cached path so next recomputes", () => {
|
|
let callCount = 0;
|
|
const finder: PathFinder<number> = {
|
|
findPath(from, to): number[] | null {
|
|
callCount++;
|
|
const fromTile = Array.isArray(from) ? from[0] : from;
|
|
return [fromTile, to];
|
|
},
|
|
};
|
|
const stepper = new PathFinderStepper(finder);
|
|
|
|
stepper.next(1, 5);
|
|
stepper.next(5, 5);
|
|
|
|
// Second call follows path without recomputing
|
|
expect(callCount).toBe(1);
|
|
|
|
stepper.invalidate();
|
|
stepper.next(1, 5);
|
|
|
|
// Recomputed path after invalidation
|
|
expect(callCount).toBe(2);
|
|
});
|
|
});
|
|
|
|
describe("findPath", () => {
|
|
it("delegates to inner finder", () => {
|
|
const pathMap = new Map<string, number[]>([["1->5", [1, 2, 3, 4, 5]]]);
|
|
const stepper = new PathFinderStepper(createMockFinder(pathMap));
|
|
|
|
const path = stepper.findPath(1, 5);
|
|
|
|
expect(path).toEqual([1, 2, 3, 4, 5]);
|
|
});
|
|
|
|
it("supports multi-source", () => {
|
|
const finder: PathFinder<number> = {
|
|
findPath(from, to): number[] | null {
|
|
const firstFrom = Array.isArray(from) ? from[0] : from;
|
|
return [firstFrom, to];
|
|
},
|
|
};
|
|
const stepper = new PathFinderStepper(finder);
|
|
|
|
const path = stepper.findPath([1, 2, 3], 5);
|
|
|
|
expect(path).toEqual([1, 5]);
|
|
});
|
|
});
|
|
|
|
describe("custom equals", () => {
|
|
it("uses custom equals function for position comparison", () => {
|
|
type Pos = { x: number; y: number };
|
|
const posEquals = (a: Pos, b: Pos) => a.x === b.x && a.y === b.y;
|
|
|
|
const finder: PathFinder<Pos> = {
|
|
findPath(from, to): Pos[] | null {
|
|
const f = Array.isArray(from) ? from[0] : from;
|
|
return [f, { x: 2, y: 0 }, to];
|
|
},
|
|
};
|
|
|
|
const stepper = new PathFinderStepper(finder, { equals: posEquals });
|
|
|
|
const from1 = { x: 1, y: 0 };
|
|
const to = { x: 3, y: 0 };
|
|
|
|
const result1 = stepper.next(from1, to);
|
|
expect(result1.status).toBe(PathStatus.NEXT);
|
|
|
|
// Use equivalent but different object (a !== b), still on track
|
|
const result2 = stepper.next({ x: 2, y: 0 }, to);
|
|
expect(result2.status).toBe(PathStatus.NEXT);
|
|
expect((result2 as { node: Pos }).node).toEqual({ x: 3, y: 0 });
|
|
});
|
|
});
|
|
});
|