Pathfinding - optimize naval invasions (#2932)

# Pathfinding pt. 4

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

## Description:

Hello again! Pathfinding. It's fast, but inaccurate. This PR makes it
more accurate and actually faster. Sadly it is _faster_ because of a
blunder in previous PR (using BucketQueue where MinHeap would be
better), not because of a new tech. More importantly, it is more
accurate. And that's what people apparently want.

## What changed?

Most of the functional changes relate to `SpatialQuery` module. This is
the thingy that answers "we know the target, which tile of my territory
is the best to launch an invasion". To make it compute a path from South
America to the deep inland China river, it has to work on a coerced map,
one with a very small resolution, so small in fact, that every 4096 map
tiles gets compressed to just one pixel. I hope you see where this is
going.

Previously we selected a random coastal tile within this big pixel
(honestly it wasn't random at all, but could very well be for the
illustrative purposes). Now, we try to be a bit more deliberate. Since
we already know the rough location of the probably best tile, we can
exclude all other tiles from the computation. Imagine a player's
territory spans both Americas on global map - that's a lot of shores.
But since we already know the best tile is somewhere close to Miami, the
problem space was greatly reduced, no need to consider all other shores.
But pathing to the target in China from Miami is still crazy expensive.

This is where second trick comes to play - instead of pathing all the
way to China, we select a _waypoint_ in the rough direction of China,
about 100 to 200 tiles away. This way we fairly cheaply select best tile
to launch an invasion towards this abstract point. And chances are, this
point is far enough, the newly computed path is very close to being
optimal. When you throw a dart from far away, the difference between
scoring 10 and missing is very small. This is why aiming in the general
direction of the board - as opposed to the ceiling - is usually good
enough.

## Okay, but what about the crazy paths when I send invasion to the
opposed bank of a river?!

Well, pathing from America to China is cool, but most players wouldn't
notice the difference on such long paths, what about the short ones? We
now try more accurate pathing first and defer to hierarchy only if it
fails. This produces much better paths for short invasions. While the
fix described above ensures the accuracy is improved also on
medium-to-long routes.

## Playground

Yes.


https://github.com/user-attachments/assets/9cf9586f-c99a-416d-b856-8cf0a21c35ed

## CodeRabbit

Grab a 🥕. Remember `tests/pathfinding/playground` is mostly generated
code and go easy on it. It's enough for it to work and do it's job of
visualizing the paths. No need for throughout review of these files.

## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file
- [x] I have added relevant tests to the test directory
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced

## Please put your Discord username so you can be contacted if a bug or
regression is found:

moleole
This commit is contained in:
Arkadiusz Sygulski
2026-01-17 00:10:55 +01:00
committed by GitHub
parent 3cdbb5651a
commit 6bd95d4884
11 changed files with 1171 additions and 64 deletions
+128 -15
View File
@@ -1,12 +1,27 @@
import { Game, Player, TerraNullius } from "../../game/Game";
import { TileRef } from "../../game/GameMap";
import { DebugSpan } from "../../utilities/DebugSpan";
import { PathFinding } from "../PathFinder";
import { AStarWaterBounded } from "../algorithms/AStar.WaterBounded";
type Owner = Player | TerraNullius;
const REFINE_MAX_SEARCH_AREA = 100 * 100;
export class SpatialQuery {
private boundedAStar: AStarWaterBounded | null = null;
constructor(private game: Game) {}
private getBoundedAStar(): AStarWaterBounded {
this.boundedAStar ??= new AStarWaterBounded(
this.game.map(),
REFINE_MAX_SEARCH_AREA,
);
return this.boundedAStar;
}
/**
* Find nearest tile matching predicate using BFS traversal.
* Uses Manhattan distance filter, ignores terrain barriers.
@@ -64,27 +79,125 @@ export class SpatialQuery {
* Returns null for terra nullius (no borderTiles).
*/
closestShoreByWater(owner: Owner, target: TileRef): TileRef | null {
if (!owner.isPlayer()) return null;
return DebugSpan.wrap("SpatialQuery.closestShoreByWater", () => {
if (!owner.isPlayer()) return null;
const gm = this.game;
const player = owner as Player;
const gm = this.game;
const player = owner as Player;
// Target must be water or shore (land adjacent to water)
if (!gm.isWater(target) && !gm.isShore(target)) return null;
// Target must be water or shore (land adjacent to water)
if (!gm.isWater(target) && !gm.isShore(target)) return null;
const targetComponent = gm.getWaterComponent(target);
if (targetComponent === null) return null;
const targetComponent = gm.getWaterComponent(target);
if (targetComponent === null) return null;
const isValidTile = (t: TileRef) => {
if (!gm.isShore(t) || !gm.isLand(t)) return false;
const tComponent = gm.getWaterComponent(t);
return tComponent === targetComponent;
const isValidTile = (t: TileRef) => {
if (!gm.isShore(t) || !gm.isLand(t)) return false;
const tComponent = gm.getWaterComponent(t);
return tComponent === targetComponent;
};
const shores = Array.from(player.borderTiles()).filter(isValidTile);
if (shores.length === 0) return null;
const path = PathFinding.Water(gm).findPath(shores, target);
if (!path || path.length === 0) return null;
return DebugSpan.wrap("SpatialQuery.refineStartTile", () =>
this.refineStartTile(path, shores, gm),
);
});
}
private refineStartTile(
path: TileRef[],
shores: TileRef[],
gm: Game,
): TileRef {
const CANDIDATE_RADIUS = 20;
const MIN_WAYPOINT_DIST = 50;
const MAX_WAYPOINT_DIST = 200;
const PADDING = 10;
if (path.length <= MIN_WAYPOINT_DIST) {
return path[0];
}
const bestTile = path[0];
const map = gm.map();
const candidates = shores.filter(
(s) => map.manhattanDist(s, bestTile) <= CANDIDATE_RADIUS,
);
if (candidates.length <= 1) return bestTile;
// Precompute candidate bounds
let candMinX = map.x(candidates[0]);
let candMaxX = candMinX;
let candMinY = map.y(candidates[0]);
let candMaxY = candMinY;
for (let i = 1; i < candidates.length; i++) {
const sx = map.x(candidates[i]);
const sy = map.y(candidates[i]);
candMinX = Math.min(candMinX, sx);
candMaxX = Math.max(candMaxX, sx);
candMinY = Math.min(candMinY, sy);
candMaxY = Math.max(candMaxY, sy);
}
// Binary search for furthest waypoint that keeps bounds within limit
let lo = MIN_WAYPOINT_DIST;
let hi = Math.min(MAX_WAYPOINT_DIST, path.length - 1);
let bestWaypointIdx = lo;
for (let i = 0; i < 5 && lo <= hi; i++) {
const mid = (lo + hi) >> 1;
const wp = path[mid];
const wpX = map.x(wp);
const wpY = map.y(wp);
const minX = Math.min(candMinX, wpX) - PADDING;
const maxX = Math.max(candMaxX, wpX) + PADDING;
const minY = Math.min(candMinY, wpY) - PADDING;
const maxY = Math.max(candMaxY, wpY) + PADDING;
const area = (maxX - minX + 1) * (maxY - minY + 1);
if (area <= REFINE_MAX_SEARCH_AREA) {
bestWaypointIdx = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
const waypoint = path[bestWaypointIdx];
const wpX = map.x(waypoint);
const wpY = map.y(waypoint);
const bounds = {
minX: Math.max(0, Math.min(candMinX, wpX) - PADDING),
maxX: Math.min(map.width() - 1, Math.max(candMaxX, wpX) + PADDING),
minY: Math.max(0, Math.min(candMinY, wpY) - PADDING),
maxY: Math.min(map.height() - 1, Math.max(candMaxY, wpY) + PADDING),
};
const shores = Array.from(player.borderTiles()).filter(isValidTile);
if (shores.length === 0) return null;
const boundsArea =
(bounds.maxX - bounds.minX + 1) * (bounds.maxY - bounds.minY + 1);
if (boundsArea > REFINE_MAX_SEARCH_AREA) return bestTile;
const path = PathFinding.Water(gm).findPath(shores, target);
return path?.[0] ?? null;
const refinedPath = this.getBoundedAStar().searchBounded(
candidates,
waypoint,
bounds,
);
DebugSpan.set("$candidates", () => candidates);
DebugSpan.set("$refinedPath", () => refinedPath);
DebugSpan.set("$originalBestTile", () => bestTile);
DebugSpan.set("$newBestTile", () => refinedPath?.[0] ?? bestTile);
return refinedPath?.[0] ?? bestTile;
}
}