mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-01 10:13:24 +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
302 lines
8.6 KiB
TypeScript
302 lines
8.6 KiB
TypeScript
import {
|
|
Execution,
|
|
Game,
|
|
isUnit,
|
|
OwnerComp,
|
|
Unit,
|
|
UnitParams,
|
|
UnitType,
|
|
} from "../game/Game";
|
|
import { TileRef } from "../game/GameMap";
|
|
import { PathFinding } from "../pathfinding/PathFinder";
|
|
import { PathStatus, SteppingPathFinder } from "../pathfinding/types";
|
|
import { PseudoRandom } from "../PseudoRandom";
|
|
import { ShellExecution } from "./ShellExecution";
|
|
|
|
export class WarshipExecution implements Execution {
|
|
private random: PseudoRandom;
|
|
private warship: Unit;
|
|
private mg: Game;
|
|
private pathfinder: SteppingPathFinder<TileRef>;
|
|
private lastShellAttack = 0;
|
|
private alreadySentShell = new Set<Unit>();
|
|
|
|
constructor(
|
|
private input: (UnitParams<UnitType.Warship> & OwnerComp) | Unit,
|
|
) {}
|
|
|
|
init(mg: Game, ticks: number): void {
|
|
this.mg = mg;
|
|
this.pathfinder = PathFinding.Water(mg);
|
|
this.random = new PseudoRandom(mg.ticks());
|
|
if (isUnit(this.input)) {
|
|
this.warship = this.input;
|
|
} else {
|
|
const spawn = this.input.owner.canBuild(
|
|
UnitType.Warship,
|
|
this.input.patrolTile,
|
|
);
|
|
if (spawn === false) {
|
|
console.warn(
|
|
`Failed to spawn warship for ${this.input.owner.name()} at ${this.input.patrolTile}`,
|
|
);
|
|
return;
|
|
}
|
|
this.warship = this.input.owner.buildUnit(
|
|
UnitType.Warship,
|
|
spawn,
|
|
this.input,
|
|
);
|
|
}
|
|
}
|
|
|
|
tick(ticks: number): void {
|
|
if (this.warship.health() <= 0) {
|
|
this.warship.delete();
|
|
return;
|
|
}
|
|
|
|
const hasPort = this.warship.owner().unitCount(UnitType.Port) > 0;
|
|
if (hasPort) {
|
|
this.warship.modifyHealth(1);
|
|
}
|
|
|
|
this.warship.setTargetUnit(this.findTargetUnit());
|
|
if (this.warship.targetUnit()?.type() === UnitType.TradeShip) {
|
|
this.huntDownTradeShip();
|
|
return;
|
|
}
|
|
|
|
this.patrol();
|
|
|
|
if (this.warship.targetUnit() !== undefined) {
|
|
this.shootTarget();
|
|
return;
|
|
}
|
|
}
|
|
|
|
private findTargetUnit(): Unit | undefined {
|
|
const hasPort = this.warship.owner().unitCount(UnitType.Port) > 0;
|
|
const patrolRangeSquared = this.mg.config().warshipPatrolRange() ** 2;
|
|
|
|
const ships = this.mg.nearbyUnits(
|
|
this.warship.tile()!,
|
|
this.mg.config().warshipTargettingRange(),
|
|
[UnitType.TransportShip, UnitType.Warship, UnitType.TradeShip],
|
|
);
|
|
const potentialTargets: { unit: Unit; distSquared: number }[] = [];
|
|
for (const { unit, distSquared } of ships) {
|
|
if (
|
|
unit.owner() === this.warship.owner() ||
|
|
unit === this.warship ||
|
|
!this.warship.owner().canAttackPlayer(unit.owner(), true) ||
|
|
this.alreadySentShell.has(unit)
|
|
) {
|
|
continue;
|
|
}
|
|
if (unit.type() === UnitType.TradeShip) {
|
|
if (
|
|
!hasPort ||
|
|
unit.isSafeFromPirates() ||
|
|
unit.targetUnit()?.owner() === this.warship.owner() || // trade ship is coming to my port
|
|
unit.targetUnit()?.owner().isFriendly(this.warship.owner()) // trade ship is coming to my ally
|
|
) {
|
|
continue;
|
|
}
|
|
if (
|
|
this.mg.euclideanDistSquared(
|
|
this.warship.patrolTile()!,
|
|
unit.tile(),
|
|
) > patrolRangeSquared
|
|
) {
|
|
// Prevent warship from chasing trade ship that is too far away from
|
|
// the patrol tile to prevent warships from wandering around the map.
|
|
continue;
|
|
}
|
|
}
|
|
potentialTargets.push({ unit: unit, distSquared });
|
|
}
|
|
|
|
return potentialTargets.sort((a, b) => {
|
|
const { unit: unitA, distSquared: distA } = a;
|
|
const { unit: unitB, distSquared: distB } = b;
|
|
|
|
// Prioritize Transport Ships above all other units
|
|
if (
|
|
unitA.type() === UnitType.TransportShip &&
|
|
unitB.type() !== UnitType.TransportShip
|
|
)
|
|
return -1;
|
|
if (
|
|
unitA.type() !== UnitType.TransportShip &&
|
|
unitB.type() === UnitType.TransportShip
|
|
)
|
|
return 1;
|
|
|
|
// Then prioritize Warships.
|
|
if (
|
|
unitA.type() === UnitType.Warship &&
|
|
unitB.type() !== UnitType.Warship
|
|
)
|
|
return -1;
|
|
if (
|
|
unitA.type() !== UnitType.Warship &&
|
|
unitB.type() === UnitType.Warship
|
|
)
|
|
return 1;
|
|
|
|
// If both are the same type, sort by distance (lower `distSquared` means closer)
|
|
return distA - distB;
|
|
})[0]?.unit;
|
|
}
|
|
|
|
private shootTarget() {
|
|
const shellAttackRate = this.mg.config().warshipShellAttackRate();
|
|
if (this.mg.ticks() - this.lastShellAttack > shellAttackRate) {
|
|
if (this.warship.targetUnit()?.type() !== UnitType.TransportShip) {
|
|
// Warships don't need to reload when attacking transport ships.
|
|
this.lastShellAttack = this.mg.ticks();
|
|
}
|
|
this.mg.addExecution(
|
|
new ShellExecution(
|
|
this.warship.tile(),
|
|
this.warship.owner(),
|
|
this.warship,
|
|
this.warship.targetUnit()!,
|
|
),
|
|
);
|
|
if (!this.warship.targetUnit()!.hasHealth()) {
|
|
// Don't send multiple shells to target that can be oneshotted
|
|
this.alreadySentShell.add(this.warship.targetUnit()!);
|
|
this.warship.setTargetUnit(undefined);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
private huntDownTradeShip() {
|
|
for (let i = 0; i < 2; i++) {
|
|
// target is trade ship so capture it.
|
|
const result = this.pathfinder.next(
|
|
this.warship.tile(),
|
|
this.warship.targetUnit()!.tile(),
|
|
5,
|
|
);
|
|
switch (result.status) {
|
|
case PathStatus.COMPLETE:
|
|
this.warship.owner().captureUnit(this.warship.targetUnit()!);
|
|
this.warship.setTargetUnit(undefined);
|
|
this.warship.move(this.warship.tile());
|
|
return;
|
|
case PathStatus.NEXT:
|
|
this.warship.move(result.node);
|
|
break;
|
|
case PathStatus.PENDING:
|
|
this.warship.touch();
|
|
break;
|
|
case PathStatus.NOT_FOUND: {
|
|
console.log(`path not found to target`);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private patrol() {
|
|
if (this.warship.targetTile() === undefined) {
|
|
this.warship.setTargetTile(this.randomTile());
|
|
if (this.warship.targetTile() === undefined) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
const result = this.pathfinder.next(
|
|
this.warship.tile(),
|
|
this.warship.targetTile()!,
|
|
);
|
|
switch (result.status) {
|
|
case PathStatus.COMPLETE:
|
|
this.warship.setTargetTile(undefined);
|
|
this.warship.move(result.node);
|
|
break;
|
|
case PathStatus.NEXT:
|
|
this.warship.move(result.node);
|
|
break;
|
|
case PathStatus.PENDING:
|
|
this.warship.touch();
|
|
return;
|
|
case PathStatus.NOT_FOUND: {
|
|
console.log(`path not found to target`);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
isActive(): boolean {
|
|
return this.warship?.isActive();
|
|
}
|
|
|
|
activeDuringSpawnPhase(): boolean {
|
|
return false;
|
|
}
|
|
|
|
randomTile(allowShoreline: boolean = false): TileRef | undefined {
|
|
let warshipPatrolRange = this.mg.config().warshipPatrolRange();
|
|
const maxAttemptBeforeExpand: number = 500;
|
|
let attempts: number = 0;
|
|
let expandCount: number = 0;
|
|
|
|
// Get warship's water component for connectivity check
|
|
const warshipComponent = this.mg.getWaterComponent(this.warship.tile());
|
|
|
|
while (expandCount < 3) {
|
|
const x =
|
|
this.mg.x(this.warship.patrolTile()!) +
|
|
this.random.nextInt(-warshipPatrolRange / 2, warshipPatrolRange / 2);
|
|
const y =
|
|
this.mg.y(this.warship.patrolTile()!) +
|
|
this.random.nextInt(-warshipPatrolRange / 2, warshipPatrolRange / 2);
|
|
if (!this.mg.isValidCoord(x, y)) {
|
|
continue;
|
|
}
|
|
const tile = this.mg.ref(x, y);
|
|
if (
|
|
!this.mg.isOcean(tile) ||
|
|
(!allowShoreline && this.mg.isShoreline(tile))
|
|
) {
|
|
attempts++;
|
|
if (attempts === maxAttemptBeforeExpand) {
|
|
expandCount++;
|
|
attempts = 0;
|
|
warshipPatrolRange =
|
|
warshipPatrolRange + Math.floor(warshipPatrolRange / 2);
|
|
}
|
|
continue;
|
|
}
|
|
// Check water component connectivity
|
|
if (
|
|
warshipComponent !== null &&
|
|
!this.mg.hasWaterComponent(tile, warshipComponent)
|
|
) {
|
|
attempts++;
|
|
if (attempts === maxAttemptBeforeExpand) {
|
|
expandCount++;
|
|
attempts = 0;
|
|
warshipPatrolRange =
|
|
warshipPatrolRange + Math.floor(warshipPatrolRange / 2);
|
|
}
|
|
continue;
|
|
}
|
|
return tile;
|
|
}
|
|
console.warn(
|
|
`Failed to find random tile for warship for ${this.warship.owner().name()}`,
|
|
);
|
|
if (!allowShoreline) {
|
|
// If we failed to find a tile on the ocean, try again but allow shoreline
|
|
return this.randomTile(true);
|
|
}
|
|
return undefined;
|
|
}
|
|
}
|