mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-06-25 13:14:38 +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
261 lines
7.6 KiB
TypeScript
261 lines
7.6 KiB
TypeScript
import { RailroadExecution } from "../execution/RailroadExecution";
|
|
import { PathFinding } from "../pathfinding/PathFinder";
|
|
import { Game, Unit, UnitType } from "./Game";
|
|
import { TileRef } from "./GameMap";
|
|
import { RailNetwork } from "./RailNetwork";
|
|
import { Railroad } from "./Railroad";
|
|
import { Cluster, TrainStation } from "./TrainStation";
|
|
|
|
/**
|
|
* The Stations handle their own neighbors so the graph is naturally traversable,
|
|
* but it would be expensive to look through the graph to find a station.
|
|
* This class stores the existing stations for quick access
|
|
*/
|
|
export interface StationManager {
|
|
addStation(station: TrainStation): void;
|
|
removeStation(station: TrainStation): void;
|
|
findStation(unit: Unit): TrainStation | null;
|
|
getAll(): Set<TrainStation>;
|
|
getById(id: number): TrainStation | undefined;
|
|
count(): number;
|
|
}
|
|
|
|
export class StationManagerImpl implements StationManager {
|
|
private stations: Set<TrainStation> = new Set();
|
|
private stationsById: (TrainStation | undefined)[] = [];
|
|
private nextId = 0;
|
|
|
|
addStation(station: TrainStation) {
|
|
station.id = this.nextId++;
|
|
this.stationsById[station.id] = station;
|
|
this.stations.add(station);
|
|
}
|
|
|
|
removeStation(station: TrainStation) {
|
|
this.stationsById[station.id] = undefined;
|
|
this.stations.delete(station);
|
|
}
|
|
|
|
findStation(unit: Unit): TrainStation | null {
|
|
for (const station of this.stations) {
|
|
if (station.unit === unit) return station;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
getAll(): Set<TrainStation> {
|
|
return this.stations;
|
|
}
|
|
|
|
getById(id: number): TrainStation | undefined {
|
|
return this.stationsById[id];
|
|
}
|
|
|
|
count(): number {
|
|
return this.nextId;
|
|
}
|
|
}
|
|
|
|
export interface RailPathFinderService {
|
|
findTilePath(from: TileRef, to: TileRef): TileRef[];
|
|
findStationsPath(from: TrainStation, to: TrainStation): TrainStation[];
|
|
}
|
|
|
|
class RailPathFinderServiceImpl implements RailPathFinderService {
|
|
constructor(private game: Game) {}
|
|
|
|
findTilePath(from: TileRef, to: TileRef): TileRef[] {
|
|
return PathFinding.Rail(this.game).findPath(from, to) ?? [];
|
|
}
|
|
|
|
findStationsPath(from: TrainStation, to: TrainStation): TrainStation[] {
|
|
return PathFinding.Stations(this.game).findPath(from, to) ?? [];
|
|
}
|
|
}
|
|
|
|
export function createRailNetwork(game: Game): RailNetwork {
|
|
const stationManager = new StationManagerImpl();
|
|
const pathService = new RailPathFinderServiceImpl(game);
|
|
return new RailNetworkImpl(game, stationManager, pathService);
|
|
}
|
|
|
|
export class RailNetworkImpl implements RailNetwork {
|
|
private maxConnectionDistance: number = 4;
|
|
|
|
constructor(
|
|
private game: Game,
|
|
private _stationManager: StationManager,
|
|
private pathService: RailPathFinderService,
|
|
) {}
|
|
|
|
stationManager(): StationManager {
|
|
return this._stationManager;
|
|
}
|
|
|
|
connectStation(station: TrainStation) {
|
|
this._stationManager.addStation(station);
|
|
this.connectToNearbyStations(station);
|
|
}
|
|
|
|
removeStation(unit: Unit): void {
|
|
const station = this._stationManager.findStation(unit);
|
|
if (!station) return;
|
|
|
|
const neighbors = station.neighbors();
|
|
this.disconnectFromNetwork(station);
|
|
this._stationManager.removeStation(station);
|
|
|
|
const cluster = station.getCluster();
|
|
if (!cluster) return;
|
|
if (neighbors.length === 1) {
|
|
cluster.removeStation(station);
|
|
} else if (neighbors.length > 1) {
|
|
for (const neighbor of neighbors) {
|
|
const stations = this.computeCluster(neighbor);
|
|
const newCluster = new Cluster();
|
|
newCluster.addStations(stations);
|
|
}
|
|
}
|
|
station.unit.setTrainStation(false);
|
|
}
|
|
|
|
/**
|
|
* Return the intermediary stations connecting two stations
|
|
*/
|
|
findStationsPath(from: TrainStation, to: TrainStation): TrainStation[] {
|
|
return this.pathService.findStationsPath(from, to);
|
|
}
|
|
|
|
private connectToNearbyStations(station: TrainStation) {
|
|
const neighbors = this.game.nearbyUnits(
|
|
station.tile(),
|
|
this.game.config().trainStationMaxRange(),
|
|
[UnitType.City, UnitType.Factory, UnitType.Port],
|
|
);
|
|
|
|
const editedClusters = new Set<Cluster>();
|
|
neighbors.sort((a, b) => a.distSquared - b.distSquared);
|
|
|
|
for (const neighbor of neighbors) {
|
|
if (neighbor.unit === station.unit) continue;
|
|
const neighborStation = this._stationManager.findStation(neighbor.unit);
|
|
if (!neighborStation) continue;
|
|
|
|
const distanceToStation = this.distanceFrom(
|
|
neighborStation,
|
|
station,
|
|
this.maxConnectionDistance,
|
|
);
|
|
|
|
const neighborCluster = neighborStation.getCluster();
|
|
if (neighborCluster === null) continue;
|
|
const connectionAvailable =
|
|
distanceToStation > this.maxConnectionDistance ||
|
|
distanceToStation === -1;
|
|
if (
|
|
connectionAvailable &&
|
|
neighbor.distSquared > this.game.config().trainStationMinRange() ** 2
|
|
) {
|
|
if (this.connect(station, neighborStation)) {
|
|
neighborCluster.addStation(station);
|
|
editedClusters.add(neighborCluster);
|
|
}
|
|
}
|
|
}
|
|
|
|
// If multiple clusters own the new station, merge them into a single cluster
|
|
if (editedClusters.size > 1) {
|
|
this.mergeClusters(editedClusters);
|
|
} else if (editedClusters.size === 0) {
|
|
// If no cluster owns the station, creates a new one for it
|
|
const newCluster = new Cluster();
|
|
newCluster.addStation(station);
|
|
}
|
|
}
|
|
|
|
private disconnectFromNetwork(station: TrainStation) {
|
|
for (const rail of station.getRailroads()) {
|
|
rail.delete(this.game);
|
|
}
|
|
station.clearRailroads();
|
|
const cluster = station.getCluster();
|
|
if (cluster !== null && cluster.size() === 1) {
|
|
this.deleteCluster(cluster);
|
|
}
|
|
}
|
|
|
|
private deleteCluster(cluster: Cluster) {
|
|
for (const station of cluster.stations) {
|
|
station.setCluster(null);
|
|
}
|
|
cluster.clear();
|
|
}
|
|
|
|
private connect(from: TrainStation, to: TrainStation) {
|
|
const path = this.pathService.findTilePath(from.tile(), to.tile());
|
|
if (path.length > 0 && path.length < this.game.config().railroadMaxSize()) {
|
|
const railRoad = new Railroad(from, to, path);
|
|
this.game.addExecution(new RailroadExecution(railRoad));
|
|
from.addRailroad(railRoad);
|
|
to.addRailroad(railRoad);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private distanceFrom(
|
|
start: TrainStation,
|
|
dest: TrainStation,
|
|
maxDistance: number,
|
|
): number {
|
|
if (start === dest) return 0;
|
|
|
|
const visited = new Set<TrainStation>();
|
|
const queue: Array<{ station: TrainStation; distance: number }> = [
|
|
{ station: start, distance: 0 },
|
|
];
|
|
|
|
while (queue.length > 0) {
|
|
const { station, distance } = queue.shift()!;
|
|
if (visited.has(station)) continue;
|
|
visited.add(station);
|
|
|
|
if (distance >= maxDistance) continue;
|
|
|
|
for (const neighbor of station.neighbors()) {
|
|
if (neighbor === dest) return distance + 1;
|
|
if (!visited.has(neighbor)) {
|
|
queue.push({ station: neighbor, distance: distance + 1 });
|
|
}
|
|
}
|
|
}
|
|
|
|
// If destination not found within maxDistance
|
|
return -1;
|
|
}
|
|
|
|
private computeCluster(start: TrainStation): Set<TrainStation> {
|
|
const visited = new Set<TrainStation>();
|
|
const queue = [start];
|
|
|
|
while (queue.length > 0) {
|
|
const current = queue.shift()!;
|
|
if (visited.has(current)) continue;
|
|
visited.add(current);
|
|
|
|
for (const neighbor of current.neighbors()) {
|
|
if (!visited.has(neighbor)) queue.push(neighbor);
|
|
}
|
|
}
|
|
|
|
return visited;
|
|
}
|
|
|
|
private mergeClusters(clustersToMerge: Set<Cluster>) {
|
|
const merged = new Cluster();
|
|
for (const cluster of clustersToMerge) {
|
|
merged.merge(cluster);
|
|
}
|
|
}
|
|
}
|