A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(nav): an agent is a body, not a point
esengine33b88e744369
diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdxindex a785beb2f..61df315dc 100644--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx@@ -65,7 +65,7 @@ stopNavAgent(world, entity);| `NavAgent` field | Default | Description ||---|---|---|| `speed` | `120` | Movement speed in world pixels per second. |-| `radius` | `12` | Agent radius (arrival tolerance / collision size). |+| `radius` | `0` | How wide the body is, in pixels. Planning routes it around anything it would not fit through; `0` routes it as a point. || `arriveRadius` | `6` | Stop distance from the final goal. || `repathInterval` | `0.5` | Seconds between replans while moving; `0` = replan only when the target changes. || `hasTarget` | `false` | Whether a destination is set (managed for you). |@@ -75,3 +75,15 @@ stopNavAgent(world, entity);`setNavDestination` is safe to call every frame to chase a moving target — the agentonly replans when the target actually moves or `repathInterval` elapses. Read`agent.arrived` (or `Perception`) to know when to switch behavior.++## Agents have width++Set `radius` to the body's actual half-width and planning keeps it out of gaps+it cannot fit through. Left at `0` an agent is routed as a point, which is what+you want for something that has no collider — and what produces the classic+sight of an enemy walking confidently into a doorway and stopping there, because+the cell it was routed to is walkable and the half of it hanging over the next+one is not.++A goal the body cannot stand on (a pickup in a corner) is still reached: the+plan ends as close as the body fits, and `arriveRadius` covers the rest.diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdxindex a42438016..3048a2d55 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai/navigation.mdx@@ -62,7 +62,7 @@ stopNavAgent(world, entity);| `NavAgent` 字段 | 默认 | 说明 ||---|---|---|| `speed` | `120` | 移动速度(世界像素/秒)。 |-| `radius` | `12` | agent 半径(到达容差 / 碰撞尺寸)。 |+| `radius` | `0` | 身体有多宽(像素)。寻路会绕开它挤不过去的地方;`0` 按质点寻路。 || `arriveRadius` | `6` | 距最终目标的停止距离。 || `repathInterval` | `0.5` | 移动中两次重规划的间隔秒数;`0` = 只在目标改变时重规划。 || `hasTarget` | `false` | 是否已设目的地(自动管理)。 |@@ -72,3 +72,12 @@ stopNavAgent(world, entity);`setNavDestination` 每帧调用都安全,可用于追一个移动的目标——只有当目标真的移动、或`repathInterval` 到点时,agent 才重新规划。读 `agent.arrived`(或 `Perception`)来判断何时切换行为。++## agent 是有宽度的++把 `radius` 设成身体的实际半宽,寻路就会绕开它挤不过去的缝隙。留在 `0` 表示按质点寻路——+没有碰撞体的东西就该这样;而这也正是那个经典画面的成因:敌人信心十足地走进门洞然后+永远停在那里,因为它被规划到的那一格是可走的,而挂在隔壁那一格上的半个身子不是。++身体站不下的目标(墙角里的拾取物)依然到得了:路径规划到身体站得下的最近处为止,+剩下的交给 `arriveRadius`。diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex daed2ff21..2c0d98973 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1445,8 +1445,8 @@{"key": "radius","type": "number",- "default": "12",- "range": "≥ 1"+ "default": "0",+ "range": "≥ 0"},{"key": "arriveRadius",diff --git a/examples/celestial-heights/assets/prefabs/wisp.esprefab b/examples/celestial-heights/assets/prefabs/wisp.esprefabindex b01d57718..bdbf4f669 100644--- a/examples/celestial-heights/assets/prefabs/wisp.esprefab+++ b/examples/celestial-heights/assets/prefabs/wisp.esprefab@@ -83,7 +83,8 @@"data": {"speed": 165,"arriveRadius": 48,- "repathInterval": 0.4+ "repathInterval": 0.4,+ "radius": 26}},{diff --git a/examples/celestial-heights/assets/scenes/spire.esscene b/examples/celestial-heights/assets/scenes/spire.essceneindex 37db4110f..1b3f15957 100644--- a/examples/celestial-heights/assets/scenes/spire.esscene+++ b/examples/celestial-heights/assets/scenes/spire.esscene@@ -487,7 +487,8 @@"data": {"speed": 175,"arriveRadius": 96,- "repathInterval": 0.35+ "repathInterval": 0.35,+ "radius": 42}},{diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex a9eebc4e4..b1398b9bb 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4551,11 +4551,12 @@ targetY: number```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec2+clearanceAt: (gx: number, gy: number) => numberheight: numberinBounds: (gx: number, gy: number) => booleanindex: (gx: number, gy: number) => numberisWalkable: (gx: number, gy: number) => boolean-nearestWalkable: (gx: number, gy: number, maxRadius?: number) => Cell | null+nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | nulloriginX: numberoriginY: numbersetWalkable: (gx: number, gy: number, walkable: boolean) => void@@ -4585,7 +4586,7 @@ static prototype: NavPlugin## Navigation — class```-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions) => Vec2[] | null+findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | nullgrid: NavGrid | nullhasGrid: () => booleansetGrid: (grid: NavGrid | null) => void@@ -4879,6 +4880,7 @@ static prototype: ParticlePlugin## PathfindOptions — interface```+clearance: number | undefineddiagonal: boolean | undefinedsnapRadius: number | undefined```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex decc71795..a7b3bd894 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -4729,11 +4729,12 @@ targetY: number```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec2+clearanceAt: (gx: number, gy: number) => numberheight: numberinBounds: (gx: number, gy: number) => booleanindex: (gx: number, gy: number) => numberisWalkable: (gx: number, gy: number) => boolean-nearestWalkable: (gx: number, gy: number, maxRadius?: number) => Cell | null+nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | nulloriginX: numberoriginY: numbersetWalkable: (gx: number, gy: number, walkable: boolean) => void@@ -4763,7 +4764,7 @@ static prototype: NavPlugin## Navigation — class```-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions) => Vec2[] | null+findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | nullgrid: NavGrid | nullhasGrid: () => booleansetGrid: (grid: NavGrid | null) => void@@ -5062,6 +5063,7 @@ static prototype: ParticlePlugin## PathfindOptions — interface```+clearance: number | undefineddiagonal: boolean | undefinedsnapRadius: number | undefined```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex c3db4bb09..d7b3f35de 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4546,11 +4546,12 @@ targetY: number```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec2+clearanceAt: (gx: number, gy: number) => numberheight: numberinBounds: (gx: number, gy: number) => booleanindex: (gx: number, gy: number) => numberisWalkable: (gx: number, gy: number) => boolean-nearestWalkable: (gx: number, gy: number, maxRadius?: number) => Cell | null+nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | nulloriginX: numberoriginY: numbersetWalkable: (gx: number, gy: number, walkable: boolean) => void@@ -4580,7 +4581,7 @@ static prototype: NavPlugin## Navigation — class```-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions) => Vec2[] | null+findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | nullgrid: NavGrid | nullhasGrid: () => booleansetGrid: (grid: NavGrid | null) => void@@ -4874,6 +4875,7 @@ static prototype: ParticlePlugin## PathfindOptions — interface```+clearance: number | undefineddiagonal: boolean | undefinedsnapRadius: number | undefined```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 7c1b1244b..807835ace 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -4791,11 +4791,12 @@ targetY: number```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec2+clearanceAt: (gx: number, gy: number) => numberheight: numberinBounds: (gx: number, gy: number) => booleanindex: (gx: number, gy: number) => numberisWalkable: (gx: number, gy: number) => boolean-nearestWalkable: (gx: number, gy: number, maxRadius?: number) => Cell | null+nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | nulloriginX: numberoriginY: numbersetWalkable: (gx: number, gy: number, walkable: boolean) => void@@ -4825,7 +4826,7 @@ static prototype: NavPlugin## Navigation — class```-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions) => Vec2[] | null+findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | nullgrid: NavGrid | nullhasGrid: () => booleansetGrid: (grid: NavGrid | null) => void@@ -5119,6 +5120,7 @@ static prototype: ParticlePlugin## PathfindOptions — interface```+clearance: number | undefineddiagonal: boolean | undefinedsnapRadius: number | undefined```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 47a4a1162..38ed6b8ad 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4553,11 +4553,12 @@ targetY: number```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec2+clearanceAt: (gx: number, gy: number) => numberheight: numberinBounds: (gx: number, gy: number) => booleanindex: (gx: number, gy: number) => numberisWalkable: (gx: number, gy: number) => boolean-nearestWalkable: (gx: number, gy: number, maxRadius?: number) => Cell | null+nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | nulloriginX: numberoriginY: numbersetWalkable: (gx: number, gy: number, walkable: boolean) => void@@ -4587,7 +4588,7 @@ static prototype: NavPlugin## Navigation — class```-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions) => Vec2[] | null+findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | nullgrid: NavGrid | nullhasGrid: () => booleansetGrid: (grid: NavGrid | null) => void@@ -4881,6 +4882,7 @@ static prototype: ParticlePlugin## PathfindOptions — interface```+clearance: number | undefineddiagonal: boolean | undefinedsnapRadius: number | undefined```diff --git a/sdk/src/ai/nav/NavAgent.ts b/sdk/src/ai/nav/NavAgent.tsindex 9cc9efdaa..4229484db 100644--- a/sdk/src/ai/nav/NavAgent.ts+++ b/sdk/src/ai/nav/NavAgent.ts@@ -18,7 +18,12 @@ import type { Entity, Vec2 } from '../../types';export interface NavAgentData {/** Movement speed in world pixels per second. */speed: number;- /** Agent radius in pixels (arrival tolerance + future collision size). */+ /**+ * How wide the body is, in pixels. Planning routes it around anything it+ * would not fit through. 0 routes it as a point, which is what every agent+ * did before this was honoured — so it stays the default, rather than+ * silently re-routing every project that already shipped.+ */radius: number;/** Stop distance from the final goal, in pixels. */arriveRadius: number;@@ -35,7 +40,7 @@ export interface NavAgentData {export const NavAgent = defineComponent<NavAgentData>('NavAgent', {speed: 120,- radius: 12,+ radius: 0,arriveRadius: 6,repathInterval: 0.5,hasTarget: false,@@ -45,7 +50,7 @@ export const NavAgent = defineComponent<NavAgentData>('NavAgent', {}, {fields: {speed: { min: 0, unit: 'px/s', category: 'Navigation' },- radius: { min: 1, unit: 'px', category: 'Navigation' },+ radius: { min: 0, unit: 'px', category: 'Navigation' },arriveRadius: { min: 0, unit: 'px', category: 'Navigation' },repathInterval: {min: 0, unit: 's', category: 'Navigation',diff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.tsindex 2d40049f0..70d3af79d 100644--- a/sdk/src/ai/nav/NavGrid.ts+++ b/sdk/src/ai/nav/NavGrid.ts@@ -77,9 +77,25 @@ export class NavGrid {}setWalkable(gx: number, gy: number, walkable: boolean): void {- if (this.inBounds(gx, gy)) this.walkable[gy * this.width + gx] = walkable ? 1 : 0;+ if (!this.inBounds(gx, gy)) return;+ this.walkable[gy * this.width + gx] = walkable ? 1 : 0;+ this.clearance_ = null;}+ /**+ * Cells from here to the nearest thing that blocks — off the grid counts as+ * blocked. An agent is a body: a path hugging a wall is walkable for the+ * cell it was planned through and a wall for the half hanging over the next.+ * Computed on first ask, dropped when walkability changes.+ */+ clearanceAt(gx: number, gy: number): number {+ if (!this.inBounds(gx, gy)) return 0;+ if (!this.clearance_) this.clearance_ = buildClearance(this.width, this.height, this.walkable);+ return this.clearance_[gy * this.width + gx];+ }++ private clearance_: Uint8Array | null = null;+/** Center of cell `(gx, gy)` in world pixels. */cellToWorld(gx: number, gy: number): Vec2 {return { x: this.originX + gx * this.cellSize, y: this.originY + gy * this.cellSize };@@ -98,19 +114,53 @@ export class NavGrid {* whole grid is blocked. Used to snap a start/goal that lands on a wall onto* a usable cell before searching.*/- nearestWalkable(gx: number, gy: number, maxRadius = 8): Cell | null {- if (this.isWalkable(gx, gy)) return { x: gx, y: gy };+ nearestWalkable(gx: number, gy: number, maxRadius = 8, clearance = 0): Cell | null {+ const fits = (cx: number, cy: number): boolean =>+ this.isWalkable(cx, cy) && (clearance <= 0 || this.clearanceAt(cx, cy) >= clearance);+ if (fits(gx, gy)) return { x: gx, y: gy };for (let r = 1; r <= maxRadius; r++) {for (let dy = -r; dy <= r; dy++) {for (let dx = -r; dx <= r; dx++) {// Only the ring perimeter at radius r (interior already checked).if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;- const cx = gx + dx;- const cy = gy + dy;- if (this.isWalkable(cx, cy)) return { x: cx, y: cy };+ if (fits(gx + dx, gy + dy)) return { x: gx + dx, y: gy + dy };}}}return null;}}++/**+ * Chamfer distance transform, 3-4 weighted, in two sweeps: a cheap and close+ * approximation of the euclidean distance to the nearest blocked cell. Reported+ * in whole cells (the 3 is the orthogonal step's weight), capped at 255 —+ * nothing needs to know it is standing 300 cells from a wall.+ */+function buildClearance(width: number, height: number, walkable: Uint8Array): Uint8Array {+ const FAR = 0x7fff;+ const d = new Int32Array(width * height);+ const at = (x: number, y: number): number =>+ (x < 0 || y < 0 || x >= width || y >= height ? 0 : d[y * width + x]);++ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const i = y * width + x;+ if (walkable[i] !== 1) { d[i] = 0; continue; }+ d[i] = Math.min(FAR, at(x - 1, y) + 3, at(x, y - 1) + 3,+ at(x - 1, y - 1) + 4, at(x + 1, y - 1) + 4);+ }+ }+ for (let y = height - 1; y >= 0; y--) {+ for (let x = width - 1; x >= 0; x--) {+ const i = y * width + x;+ if (walkable[i] !== 1) continue;+ d[i] = Math.min(d[i], at(x + 1, y) + 3, at(x, y + 1) + 3,+ at(x + 1, y + 1) + 4, at(x - 1, y + 1) + 4);+ }+ }++ const out = new Uint8Array(width * height);+ for (let i = 0; i < out.length; i++) out[i] = Math.min(255, Math.round(d[i] / 3));+ return out;+}diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.tsindex f2bf866a9..6f764690a 100644--- a/sdk/src/ai/nav/NavPlugin.ts+++ b/sdk/src/ai/nav/NavPlugin.ts@@ -72,6 +72,7 @@ export function stepNavigation(const path = nav.findWorldPath({ x: tf.position.x, y: tf.position.y },{ x: agent.targetX, y: agent.targetY },+ { radius: agent.radius },);rt = {waypoints: path ?? [],diff --git a/sdk/src/ai/nav/Navigation.ts b/sdk/src/ai/nav/Navigation.tsindex 19136ede1..89e40240f 100644--- a/sdk/src/ai/nav/Navigation.ts+++ b/sdk/src/ai/nav/Navigation.ts@@ -27,14 +27,18 @@ export class Navigation {/*** Plan a world-space path (cell-center waypoints) between two world points,- * or null if there is no grid or no route.+ * or null if there is no grid or no route. `radius` is the body being+ * routed, in world units: a path planned for a point is a path only the+ * centre of an agent fits through.*/- findWorldPath(from: Vec2, to: Vec2, opts?: PathfindOptions): Vec2[] | null {+ findWorldPath(from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number }): Vec2[] | null {const grid = this.grid;if (!grid) return null;const start = grid.worldToCell(from.x, from.y);const goal = grid.worldToCell(to.x, to.y);- const cells = findPath(grid, start, goal, opts);+ const radius = opts?.radius ?? 0;+ const clearance = opts?.clearance ?? (radius > 0 ? Math.ceil(radius / grid.cellSize) : 0);+ const cells = findPath(grid, start, goal, { ...opts, clearance });return cells ? pathToWorld(grid, cells) : null;}}diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.tsindex 17dffc389..0183fb706 100644--- a/sdk/src/ai/nav/pathfind.ts+++ b/sdk/src/ai/nav/pathfind.ts@@ -21,6 +21,12 @@ export interface PathfindOptions {* within this ring radius before searching. 0 disables snapping. Default 8.*/snapRadius?: number;+ /**+ * Cells of room the agent needs on every step — a body has width, and a+ * path planned for a point hands it one that only its centre fits through.+ * 0 (default) plans for a point.+ */+ clearance?: number;}const SQRT2 = Math.SQRT2;@@ -47,9 +53,10 @@ export function findPath(): Cell[] | null {const diagonal = opts.diagonal ?? true;const snapRadius = opts.snapRadius ?? 8;+ const clearance = Math.max(0, opts.clearance ?? 0);- const s = resolveEndpoint(grid, start, snapRadius);- const g = resolveEndpoint(grid, goal, snapRadius);+ const s = resolveEndpoint(grid, start, snapRadius, clearance);+ const g = resolveEndpoint(grid, goal, snapRadius, clearance);if (!s || !g) return null;const { width, height } = grid;@@ -80,9 +87,9 @@ export function findPath(const [dx, dy] = i < 4 ? ORTHO[i] : DIAG[i - 4];const nx = cx + dx;const ny = cy + dy;- if (!grid.isWalkable(nx, ny)) continue;+ if (!fits(grid, nx, ny, clearance)) continue;// No corner-cutting: a diagonal needs both shared orthogonals open.- if (i >= 4 && (!grid.isWalkable(cx + dx, cy) || !grid.isWalkable(cx, cy + dy))) continue;+ if (i >= 4 && (!fits(grid, cx + dx, cy, clearance) || !fits(grid, cx, cy + dy, clearance))) continue;const nIdx = ny * width + nx;if (closed[nIdx]) continue;@@ -105,10 +112,19 @@ export function pathToWorld(grid: NavGrid, path: Cell[]): Vec2[] {return path.map(c => grid.cellToWorld(c.x, c.y));}-function resolveEndpoint(grid: NavGrid, c: Cell, snapRadius: number): Cell | null {- if (grid.isWalkable(c.x, c.y)) return c;+/** Walkable, and with enough room around it for a body of this size. */+function fits(grid: NavGrid, gx: number, gy: number, clearance: number): boolean {+ if (!grid.isWalkable(gx, gy)) return false;+ return clearance <= 0 || grid.clearanceAt(gx, gy) >= clearance;+}++function resolveEndpoint(grid: NavGrid, c: Cell, snapRadius: number, clearance: number): Cell | null {+ if (fits(grid, c.x, c.y, clearance)) return c;if (snapRadius <= 0) return null;- return grid.nearestWalkable(c.x, c.y, snapRadius);+ // An agent already jammed against a wall must still be given a way out, so+ // a start that fits nowhere falls back to merely walkable.+ return grid.nearestWalkable(c.x, c.y, snapRadius, clearance)+ ?? grid.nearestWalkable(c.x, c.y, snapRadius);}function heuristic(ax: number, ay: number, bx: number, by: number, diagonal: boolean): number {diff --git a/sdk/tests/nav-clearance.test.ts b/sdk/tests/nav-clearance.test.tsnew file mode 100644index 000000000..5c2b2b33f--- /dev/null+++ b/sdk/tests/nav-clearance.test.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Room to walk: an agent is a body, not a point.+ *+ * A path planned for a point is a path only the centre of an agent fits+ * through. What that looks like in a game is an enemy that walks confidently+ * into a doorway and stops there forever, because the cell it was routed to is+ * walkable and the half of it hanging over the next one is not.+ */+import { describe, it, expect } from 'vitest';+import { NavGrid } from '../src/ai/nav/NavGrid';+import { findPath } from '../src/ai/nav/pathfind';++/** `#` blocks, `.` is open. Row 0 is the TOP row of the string. */+function gridOf(rows: string[]): NavGrid {+ const height = rows.length;+ const width = rows[0].length;+ const walkable = new Uint8Array(width * height);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) walkable[y * width + x] = rows[y][x] === '#' ? 0 : 1;+ }+ return new NavGrid({ width, height, cellSize: 1, walkable });+}++describe('clearance', () => {+ it('is zero on a wall and grows with distance from one', () => {+ const g = gridOf([+ '#####',+ '#...#',+ '#...#',+ '#...#',+ '#####',+ ]);+ expect(g.clearanceAt(0, 0)).toBe(0);+ expect(g.clearanceAt(1, 1)).toBe(1);+ expect(g.clearanceAt(2, 2)).toBe(2);+ });++ // Off the grid is not somewhere to stand: half an agent outside the world+ // is no better than half of it inside a rock.+ it('counts the edge of the grid as a wall', () => {+ const g = gridOf(['...', '...', '...']);+ expect(g.clearanceAt(0, 1)).toBe(1);+ expect(g.clearanceAt(1, 1)).toBe(2);+ });++ it('is recomputed after walkability changes', () => {+ const g = gridOf(['.....', '.....', '.....']);+ expect(g.clearanceAt(2, 1)).toBe(2);+ g.setWalkable(2, 0, false);+ expect(g.clearanceAt(2, 1)).toBe(1);+ });+});++describe('findPath with clearance', () => {+ // A one-cell gap: a point goes through, a body does not.+ const pinch = gridOf([+ '.......',+ '.......',+ '###.###',+ '.......',+ '.......',+ ]);++ it('takes the pinch when planning for a point', () => {+ expect(findPath(pinch, { x: 3, y: 0 }, { x: 3, y: 4 })).not.toBeNull();+ });++ it('refuses the pinch for a body that does not fit', () => {+ expect(findPath(pinch, { x: 3, y: 0 }, { x: 3, y: 4 }, { clearance: 2 })).toBeNull();+ });++ it('routes a body the long way round when there is one', () => {+ const room = gridOf([+ '..........',+ '..........',+ '..........',+ '####.#####',+ '..........',+ '..........',+ '..........',+ ]);+ const point = findPath(room, { x: 1, y: 1 }, { x: 1, y: 5 });+ const body = findPath(room, { x: 1, y: 1 }, { x: 1, y: 5 }, { clearance: 2 });+ expect(point).not.toBeNull();+ // The only gap is one cell wide, so a two-cell body has nowhere to go.+ expect(body).toBeNull();+ });++ // Goals are where the game put them, which is often against a wall. A body+ // that cannot stand there is walked as close as it can stand instead — the+ // rest is the agent's arrival tolerance, not the planner's business.+ it('walks a goal against a wall as close as the body can stand', () => {+ const g = gridOf([+ '#####',+ '#...#',+ '#...#',+ '#...#',+ '#####',+ ]);+ const path = findPath(g, { x: 3, y: 3 }, { x: 1, y: 1 }, { clearance: 2 });+ expect(path).not.toBeNull();+ const end = path!.at(-1)!;+ expect(Math.max(Math.abs(end.x - 1), Math.abs(end.y - 1))).toBeLessThanOrEqual(1);+ });+});