import type { Position } from '../../../sdk/types.js'; import { COST_DIAG, COST_STRAIGHT, FieldCalculator, PX_PER_UNIT, UNITS_PER_PX, type FieldResult } from './distance-field.js'; import { loadWalkableGrid, type WalkableGrid } from './walkable-grid.js'; // Escape planning against pure-pursuit crabs, in lockstep time steps where // every crab walks its shortest walkable path toward the shrimp's position at // the start of each step (same speed as the shrimp): // - planEscape: beam-search the shrimp move that stays uncaught and maximizes // the final geodesic distance to the nearest crab. // - assessEscapeTarget: rate an already-committed target by rolling out the // fixed walk toward it, so callers can keep a target until it turns bad // instead of re-targeting every tick. // // Model approximations: octile 5/7 geodesics overestimate the server's // smoothed paths by up to ~8% (symmetrically for both sides), and the // pure-pursuit crab is more pessimistic than real crabs with vision limits. export interface EscapeOptions { /** Planning horizon in time steps. Default 6. */ steps?: number; /** Distance each side covers per step, px. Default 144 (120px/s x 1.2s tick). */ stepDist?: number; /** Geodesic distance at or under which the shrimp counts as caught, px. Default 80 (server kill_range). */ killRange?: number; /** Beam width. Default 8. */ beamWidth?: number; /** Distance field radius, px; crabs beyond it are frozen and scored as this far. Default 900. */ fieldRadius?: number; /** Number of angle buckets for shrimp move candidates. Default 16. */ directions?: number; } export interface EscapePlan { /** Position after the final step (best struggle endpoint when caught). */ target: Position; /** Geodesic distance from target to the nearest simulated crab, px; capped at fieldRadius; Infinity with no crabs. */ minCrabDistance: number; /** One waypoint per survived step (tile centers in world coords). */ path: Position[]; /** True when every branch gets caught within the horizon. */ caught: boolean; survivedSteps: number; } export interface TargetAssessment { /** Geodesic distance from the shrimp's current position to the target, px; Infinity if unreachable. */ distanceToTarget: number; /** Geodesic distance to the nearest crab when the rollout ends (arrival, horizon, or last safe step when caught), px; capped at fieldRadius; Infinity with no crabs. */ minCrabDistance: number; /** True when walking the fixed path to the target gets caught within the horizon. */ caught: boolean; survivedSteps: number; } interface Node { cell: number; crabCells: number[]; depth: number; parent: Node | null; /** Lower bound on the min crab distance, px (beam ranking only). */ proxy: number; } interface ResolvedOptions { steps: number; killRange: number; beamWidth: number; directions: number; stepUnits: number; killUnits: number; radiusUnits: number; } function resolveOptions(opts: EscapeOptions): ResolvedOptions { const steps = opts.steps ?? 6; const stepDist = opts.stepDist ?? 144; const killRange = opts.killRange ?? 80; const beamWidth = opts.beamWidth ?? 8; const fieldRadius = opts.fieldRadius ?? 900; const directions = opts.directions ?? 16; return { steps, killRange, beamWidth, directions, stepUnits: Math.round(stepDist * UNITS_PER_PX), killUnits: Math.round(killRange * UNITS_PER_PX), radiusUnits: Math.round(fieldRadius * UNITS_PER_PX), }; } interface Planner { grid: WalkableGrid; calc: FieldCalculator; } let planner: Planner | null = null; function getPlanner(): Planner { if (!planner) { const grid = loadWalkableGrid(); planner = { grid, calc: new FieldCalculator(grid) }; } return planner; } function snapCell(grid: WalkableGrid, pos: Position): number { return grid.snapToWalkable(grid.worldToCell(pos.x, pos.y)); } function snapCrabCells(grid: WalkableGrid, crabs: Position[]): number[] { return crabs.map(crab => snapCell(grid, crab)).filter(cell => cell >= 0); } function euclidPx(grid: WalkableGrid, a: number, b: number): number { const pa = grid.cellToWorld(a); const pb = grid.cellToWorld(b); return Math.hypot(pa.x - pb.x, pa.y - pb.y); } // Both sides traverse their step path in the same time window; sample // matching fractions and flag any moment within kill range (euclidean, // ignoring walls — slightly conservative). Catches head-on swaps that the // endpoint check misses. t=0 is skipped: step-start safety is already // established geodesically, and a thin wall can make it euclid-close. function pathsCross(grid: WalkableGrid, killRange: number, shrimpPath: number[], crabPath: number[]): boolean { for (let k = 1; k <= 8; k++) { const t = k / 8; const a = shrimpPath[Math.round(t * (shrimpPath.length - 1))]; const b = crabPath[Math.round(t * (crabPath.length - 1))]; if (euclidPx(grid, a, b) <= killRange) return true; } return false; } /** One pursuit step: every crab descends the latest field (source = shrimp) by stepUnits. */ function pursuitStep(calc: FieldCalculator, crabCells: number[], stepUnits: number): { end: number; cells: number[] }[] { return crabCells.map(cell => calc.descend(cell, stepUnits)); } export function planEscape(shrimp: Position, crabs: Position[], opts: EscapeOptions = {}): EscapePlan { const { grid, calc } = getPlanner(); const o = resolveOptions(opts); const start = snapCell(grid, shrimp); if (start < 0) { return { target: shrimp, minCrabDistance: Infinity, path: [], caught: false, survivedSteps: 0 }; } const crabCells = snapCrabCells(grid, crabs); let frontier: Node[] = [{ cell: start, crabCells, depth: 0, parent: null, proxy: 0 }]; let bestLeaf: { node: Node; minUnits: number } | null = null; let struggle: { node: Node; minUnits: number } | null = null; while (frontier.length > 0) { const children: Node[] = []; for (const node of frontier) { const field: FieldResult = calc.compute(node.cell, o.radiusUnits, o.stepUnits, o.directions); const crabDists = node.crabCells.map(cell => Math.min(field.distOf(cell), o.radiusUnits)); const minUnits = crabDists.length > 0 ? Math.min(...crabDists) : Infinity; // End-of-step catch check, deferred to expansion: this field's source is // the shrimp position and the crabs have already taken last step's move. if (node.depth > 0 && minUnits <= o.killUnits) continue; if ( !struggle || node.depth > struggle.node.depth || (node.depth === struggle.node.depth && minUnits > struggle.minUnits) ) { struggle = { node, minUnits }; } if (node.depth === o.steps) { if (!bestLeaf || minUnits > bestLeaf.minUnits) bestLeaf = { node, minUnits }; continue; } // Pure pursuit: each crab descends this field toward the shrimp's // step-start position. const crabMoves = pursuitStep(calc, node.crabCells, o.stepUnits); const newCrabCells = crabMoves.map(move => move.end); const dangerous: number[] = []; crabDists.forEach((d, i) => { if (d <= o.killUnits + 2 * o.stepUnits) dangerous.push(i); }); const candidates: number[] = [node.cell]; for (const cell of field.ringCandidates) if (cell >= 0) candidates.push(cell); for (const cand of candidates) { const shrimpPath = cand === node.cell ? [node.cell] : calc.pathToSource(cand); if (dangerous.some(i => pathsCross(grid, o.killRange, shrimpPath, crabMoves[i].cells))) continue; const candUnits = field.distOf(cand); let proxy = Infinity; for (const crab of newCrabCells) { const crabUnits = field.distOf(crab); const triangle = crabUnits === Infinity ? o.radiusUnits : crabUnits - candUnits; proxy = Math.min(proxy, Math.max(euclidPx(grid, cand, crab), triangle * PX_PER_UNIT)); } children.push({ cell: cand, crabCells: newCrabCells, depth: node.depth + 1, parent: node, proxy }); } } if (children.length === 0) break; const byCell = new Map(); for (const child of children) { const seen = byCell.get(child.cell); if (!seen || child.proxy > seen.proxy) byCell.set(child.cell, child); } frontier = [...byCell.values()].sort((a, b) => b.proxy - a.proxy).slice(0, o.beamWidth); } const result = bestLeaf ?? struggle!; const path: Position[] = []; for (let n: Node | null = result.node; n && n.depth > 0; n = n.parent) { path.unshift(grid.cellToWorld(n.cell)); } return { target: result.node.depth > 0 ? grid.cellToWorld(result.node.cell) : grid.cellToWorld(start), minCrabDistance: result.minUnits * PX_PER_UNIT, path, caught: !bestLeaf, survivedSteps: result.node.depth, }; } /** * Fixed-policy rollout: the shrimp walks its initial geodesic path toward the * target (mirroring the server's single A* at move submission) while the crabs * pure-pursue each step, with the same catch semantics as planEscape. The * rollout ends on arrival, at the horizon, or when caught. */ export function assessEscapeTarget(shrimp: Position, crabs: Position[], target: Position, opts: EscapeOptions = {}): TargetAssessment { const { grid, calc } = getPlanner(); const o = resolveOptions(opts); const start = snapCell(grid, shrimp); const targetCell = start >= 0 ? snapCell(grid, target) : -1; if (start < 0 || targetCell < 0) { return { distanceToTarget: Infinity, minCrabDistance: Infinity, caught: false, survivedSteps: 0 }; } let crabCells = snapCrabCells(grid, crabs); // The walk path is fixed up front; extract it (and the target distance) // before the per-step fields invalidate this one. const reach = calc.compute(start, o.radiusUnits + o.steps * o.stepUnits, 0); const targetUnits = reach.distOf(targetCell); if (targetUnits === Infinity) { return { distanceToTarget: Infinity, minCrabDistance: Infinity, caught: false, survivedSteps: 0 }; } const walkPath = calc.pathToSource(targetCell); const W = grid.width; const cumUnits = new Array(walkPath.length); cumUnits[0] = 0; for (let i = 1; i < walkPath.length; i++) { const a = walkPath[i - 1]; const b = walkPath[i]; const diagonal = a % W !== b % W && Math.floor(a / W) !== Math.floor(b / W); cumUnits[i] = cumUnits[i - 1] + (diagonal ? COST_DIAG : COST_STRAIGHT); } let shrimpIdx = 0; let caught = false; let survivedSteps = 0; let minUnitsAtEnd = Infinity; for (let depth = 0; ; depth++) { const cell = walkPath[shrimpIdx]; const field = calc.compute(cell, o.radiusUnits, 0); const crabDists = crabCells.map(c => Math.min(field.distOf(c), o.radiusUnits)); const minUnits = crabDists.length > 0 ? Math.min(...crabDists) : Infinity; // Same end-of-step semantics as planEscape: at depth > 0 the crabs have // already taken last step's move toward the previous shrimp position. if (depth > 0 && minUnits <= o.killUnits) { caught = true; break; } survivedSteps = depth; minUnitsAtEnd = minUnits; if (depth === o.steps || shrimpIdx >= walkPath.length - 1) break; const crabMoves = pursuitStep(calc, crabCells, o.stepUnits); let nextIdx = shrimpIdx; while (nextIdx < walkPath.length - 1 && cumUnits[nextIdx + 1] - cumUnits[shrimpIdx] <= o.stepUnits) nextIdx++; const dangerous: number[] = []; crabDists.forEach((d, i) => { if (d <= o.killUnits + 2 * o.stepUnits) dangerous.push(i); }); const segment = walkPath.slice(shrimpIdx, nextIdx + 1); if (dangerous.some(i => pathsCross(grid, o.killRange, segment, crabMoves[i].cells))) { caught = true; break; } crabCells = crabMoves.map(move => move.end); shrimpIdx = nextIdx; } return { distanceToTarget: targetUnits * PX_PER_UNIT, minCrabDistance: minUnitsAtEnd * PX_PER_UNIT, caught, survivedSteps, }; } export interface RouteInfo { /** 测地距离 px;maxRadiusPx 之外或不可达 = Infinity。 */ distancePx: number; /** 测地路径是否经过任一威胁点 threatRadiusPx 内(不可达时恒为 false)。 */ nearThreat: boolean; } /** * Immutable, serializable route projection produced by a parallel analyzer. * It contains only distances and the same 4-cell path samples used by * `assessRoutes`; the ordered Goal reducer can therefore apply its own current * threat set without rebuilding a distance field on the Owner thread. */ export interface RouteEvidence { readonly from: Readonly; readonly maxRadiusPx: number; readonly routes: readonly Readonly<{ readonly point: Readonly; readonly distancePx: number; readonly pathSamples: readonly Readonly[]; }>[]; } /** * 沿路径每 4 格(16px)采样一次离威胁点的欧氏距离,含末端格;半径 ~200px 下足够密。 * 豁免起点 from 的 radiusPx 邻域:逃跑那刻起点必然紧贴威胁,这一采样点不该把 * 「背向威胁、越走越远」的整条路线判危;真正夹在你与目的地之间、离起点超过 * radiusPx 的威胁仍会命中。对齐同文件 pathsCross 跳过 step 起点的语义。 */ function pathNearAny(grid: WalkableGrid, path: number[], threats: Position[], radiusPx: number, from: Position): boolean { for (let i = 0; i < path.length; i += 4) { const idx = Math.min(i, path.length - 1); const w = grid.cellToWorld(path[idx]); if (Math.hypot(w.x - from.x, w.y - from.y) <= radiusPx) continue; if (threats.some(t => Math.hypot(w.x - t.x, w.y - t.y) <= radiusPx)) return true; } const end = grid.cellToWorld(path[path.length - 1]); if (Math.hypot(end.x - from.x, end.y - from.y) <= radiusPx) return false; return threats.some(t => Math.hypot(end.x - t.x, end.y - t.y) <= radiusPx); } function sampledWorldPath(grid: WalkableGrid, path: number[]): Position[] { const samples: Position[] = []; for (let i = 0; i < path.length; i += 4) { samples.push(grid.cellToWorld(path[i])); } const end = grid.cellToWorld(path[path.length - 1]); const last = samples[samples.length - 1]; if (!last || last.x !== end.x || last.y !== end.y) samples.push(end); return samples; } function routePointKey(point: Position): string { return `${point.x}\u0000${point.y}`; } function samplesNearAny( samples: readonly Readonly[], threats: Position[], radiusPx: number, from: Position, ): boolean { for (const sample of samples) { if (Math.hypot(sample.x - from.x, sample.y - from.y) <= radiusPx) continue; if (threats.some(threat => Math.hypot(sample.x - threat.x, sample.y - threat.y) <= radiusPx)) { return true; } } return false; } /** * Build reusable route evidence with one distance-field scan. Duplicate target * points are collapsed because consumers restore their requested order. */ export function buildRouteEvidence( from: Position, points: readonly Position[], maxRadiusPx = 3000, ): RouteEvidence | null { const { grid, calc } = getPlanner(); const start = snapCell(grid, from); if (start < 0) return null; const field = calc.compute(start, Math.round(maxRadiusPx * UNITS_PER_PX), 0); const seen = new Set(); const routes: RouteEvidence['routes'][number][] = []; for (const point of points) { const key = routePointKey(point); if (seen.has(key)) continue; seen.add(key); const cell = snapCell(grid, point); const units = cell >= 0 ? field.distOf(cell) : Infinity; routes.push({ point: { x: point.x, y: point.y }, distancePx: units * PX_PER_UNIT, pathSamples: units === Infinity ? [] : sampledWorldPath(grid, calc.pathToSource(cell)), }); } return { from: { x: from.x, y: from.y }, maxRadiusPx, routes, }; } /** * Apply a reducer-owned threat set to precomputed route evidence. Returns null * when the evidence belongs to another origin or does not cover every target, * allowing existing callers to fall back without ever using stale data. */ export function assessRoutesFromEvidence( evidence: Readonly | null | undefined, from: Position, points: readonly Position[], threats: Position[], threatRadiusPx: number, ): RouteInfo[] | null { if (!evidence || evidence.from.x !== from.x || evidence.from.y !== from.y) return null; const byPoint = new Map(evidence.routes.map(route => [routePointKey(route.point), route])); const routes: RouteInfo[] = []; for (const point of points) { const route = byPoint.get(routePointKey(point)); if (!route) return null; routes.push({ distancePx: route.distancePx, nearThreat: route.distancePx !== Infinity && threats.length > 0 && samplesNearAny(route.pathSamples, threats, threatRadiusPx, from), }); } return routes; } /** * 从 from 到各点的测地距离与「必经之路是否有危险」,一次距离场扫描 + 逐点回溯 * 梯度路径查表。threats 为空时只算距离不查路径。from 无法吸附到可走网格时返回 * null,调用方退回欧氏距离(且无路径信息)。 */ export function assessRoutes( from: Position, points: Position[], threats: Position[], threatRadiusPx: number, maxRadiusPx = 3000, ): RouteInfo[] | null { const { grid, calc } = getPlanner(); const start = snapCell(grid, from); if (start < 0) return null; const field = calc.compute(start, Math.round(maxRadiusPx * UNITS_PER_PX), 0); return points.map(p => { const cell = snapCell(grid, p); const units = cell >= 0 ? field.distOf(cell) : Infinity; if (units === Infinity) return { distancePx: Infinity, nearThreat: false }; return { distancePx: units * PX_PER_UNIT, nearThreat: threats.length > 0 && pathNearAny(grid, calc.pathToSource(cell), threats, threatRadiusPx, from), }; }); }