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): diagnose partial routes and reuse disconnected grid topology
yhh3437eb7f71bc
diff --git a/.github/workflows/navigation-cpu.yml b/.github/workflows/navigation-cpu.ymlnew file mode 100644index 000000000..0045c13d0--- /dev/null+++ b/.github/workflows/navigation-cpu.yml@@ -0,0 +1,38 @@+name: Navigation CPU evidence+on:+ workflow_dispatch:+ inputs:+ search-reference:+ description: Commit supplying the reference grid search; current obstacle clearance is used on both sides+ type: string+ required: true+ default: 48631844c53113825a15493afeb8e6e2b972900c+permissions:+ contents: read+jobs:+ navigation:+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v7+ with:+ fetch-depth: 0+ - uses: ./.github/actions/setup+ - run: pnpm exec playwright install --with-deps chromium+ - name: Check navigation contracts+ run: |+ mkdir -p output/navigation-cpu-ci+ pnpm --filter ./sdk exec vitest run nav --maxWorkers=4 --minWorkers=1 | tee output/navigation-cpu-ci/tests.log+ - name: Measure identical building maps with reference and current searches+ env:+ SEARCH_REFERENCE: ${{ inputs.search-reference }}+ run: |+ node tools/navigation-rebuild-benchmark.mjs output/navigation-cpu-ci/reference.json --search-reference="$SEARCH_REFERENCE"+ node tools/navigation-rebuild-benchmark.mjs output/navigation-cpu-ci/current.json+ - uses: actions/upload-artifact@v7+ if: always()+ with:+ name: navigation-cpu-evidence+ path: output/navigation-cpu-ci+ if-no-files-found: error+ retention-days: 7diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 598b636ce..dee8cfec4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ published separately; it ships inside the editor.### Added+- **Navigation queries distinguish complete routes from best-effort paths.** `queryWorldPath` reports missing surfaces or endpoints, disconnected regions, grid clearance failures and mesh radius mismatches; custom surfaces without diagnostics report unknown. Grid searches reuse revision-scoped connectivity after a failed search, while walkability and dynamic obstacles invalidate it. Dynamic blockers now contribute to body clearance; the legacy path API keeps returning partial approaches.+- **Spatial transform handles fade behind scene geometry.** A persistent Viewport setting can restore always-visible handles; flat 2D widgets retain their appearance. Scoped immediate-draw depth state disables overlay depth writes and restores the previous state, including when drawing throws. Older cores keep their existing overlay fallback.- **Spatial rotation adds a view-axis outer ring.** The outer ring remains a screen circle and uses the presented camera axis captured at the press, with absolute twist snapping and the same undo/cancel path. Local inner rings use their rotated world axis; rotation writes, including Alt copies, convert through each target's parent frame. Flat 2D retains its existing Z ring.diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdxindex 1e4507f64..76e18d7f0 100644--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx@@ -232,6 +232,47 @@ big world.world at all.</Aside>+### Explaining a route++Use `nav.queryWorldPath(from, to, { radius })` when a best-effort path must be+distinguished from reaching the destination. It returns `{ path, status, reason }`:++| Status / reason | Meaning |+|---|---|+| `complete` / `none` | Reaches the surface's resolved destination, including normal endpoint snapping. |+| `partial` / `disconnected` | Stops on the reachable side of a disconnected region or closed passage. |+| `partial` / `insufficient-clearance` | A point can get through the grid, but the requested body cannot. |+| `unavailable` / `no-surface` | No navigation surface is installed. |+| `unavailable` / `start-unavailable` | No usable starting point was found. |+| `target-unavailable` | No usable destination was found; a mesh may still return a partial approach. |+| `unavailable` / `radius-mismatch` | The requested body is wider than the mesh's baked radius. |+| `unknown` / `diagnostics-unavailable` | A custom surface implements only the legacy path API. |++```typescript+const result = nav.queryWorldPath(from, target, { radius: 20 });+if (result.status !== 'complete') console.info(result.reason);+// result.path can still describe a useful partial approach.+```++`findWorldPath` retains its existing best-effort behavior. The diagnostic query+describes the currently installed surface; it does not start a rebuild. Change+grid walkability through `setWalkable`, `setObstructed` and `clearObstructions` so+clearance and cached connectivity are invalidated together. Dynamic blockers+contribute to body clearance. Area prices remain live without rebuilding connectivity.++The reproducible CPU corpus runs in headless Chromium with door and building+changes on 32/64/128-cell maps and 64 simultaneous replans:++```sh+node tools/navigation-rebuild-benchmark.mjs output/navigation-current.json+node tools/navigation-rebuild-benchmark.mjs output/navigation-reference.json --search-reference=48631844c53113825a15493afeb8e6e2b972900c+```++The reference substitutes only the previous search; both sides use current+obstacle clearance. Reports record source and bundle identity, raw rebuild and+query times, and frame gaps. They measure navigation CPU work, excluding physics+geometry collection, avoidance, rendering and the rest of the game frame.+### Moving an agentAttach a `NavAgent`, then point it at a destination. The built-in nav plugin plansdiff --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 056873702..c59c7b26c 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@@ -196,6 +196,43 @@ app.getResource(NavDebugDraw).enabled = true;只有一种意思——**agent 自己不在任何地方**,一个不在可走世界上的点没有任何路线可言。</Aside>+### 解释路径结果++需要区分“尽量靠近”与真正到达时,调用 `nav.queryWorldPath(from, to, { radius })`。+它返回 `{ path, status, reason }`:++| 状态 / 原因 | 含义 |+|---|---|+| `complete` / `none` | 到达导航面解析后的目标,包括原有端点吸附。 |+| `partial` / `disconnected` | 路线止于断开的区域或关闭通道的可达一侧。 |+| `partial` / `insufficient-clearance` | 点能通过格子,但指定宽度的角色无法通过。 |+| `unavailable` / `no-surface` | 尚未安装导航面。 |+| `unavailable` / `start-unavailable` | 找不到可用起点。 |+| `target-unavailable` | 找不到可用终点;网格仍可能给出靠近它的部分路线。 |+| `unavailable` / `radius-mismatch` | 角色半径超过导航网格烘焙时的半径。 |+| `unknown` / `diagnostics-unavailable` | 自定义导航面仅实现了原有路径接口。 |++```typescript+const result = nav.queryWorldPath(from, target, { radius: 20 });+if (result.status !== 'complete') console.info(result.reason);+// result.path 仍可能包含一条有用的靠近路线。+```++`findWorldPath` 保留原有的尽量靠近行为。诊断查询只描述当前已安装的导航面,不触发重建。+格子通行状态通过 `setWalkable`、`setObstructed` 和 `clearObstructions` 修改,确保净空和连通性+缓存一起失效。动态障碍也计入角色宽度所需净空;区域价格变化无需重建连通性。++可复现的 CPU 语料使用无头 Chromium,在 32/64/128 格地图中开关门、放置建筑并同时重算+64 个代理的路径:++```sh+node tools/navigation-rebuild-benchmark.mjs output/navigation-current.json+node tools/navigation-rebuild-benchmark.mjs output/navigation-reference.json --search-reference=48631844c53113825a15493afeb8e6e2b972900c+```++对照只替换旧寻路实现,两侧均使用当前的动态障碍净空。报告包含源码与 bundle 标识、原始+构建/查询耗时和帧间隔。该计时不含物理几何收集、避让、渲染及完整游戏帧的其余工作。+### 移动 agent加一个 `NavAgent`,然后给它指一个目的地。内置的导航插件会规划路径并每帧沿路径推进 agent——diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 783c83a59..9a5d7d87c 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 103,- "experimental": 2197,+ "experimental": 2198,"deprecated": 3},- "total": 2415,+ "total": 2416,"subsystems": [{"id": "mobile-controls",diff --git a/sdk/etc/ai.api.md b/sdk/etc/ai.api.mdindex 18108cec4..8f03ab705 100644--- a/sdk/etc/ai.api.md+++ b/sdk/etc/ai.api.md@@ -1,7 +1,7 @@# API surface — esengine/ai<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 159 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 160 experimental · 0 deprecated## AiAction — type @experimental```@@ -418,6 +418,7 @@ verts: Float32Array<ArrayBufferLike>## NavGrid — class @experimental```+@internal topologyRevision: numbercellSize: numbercellToWorld: (gx: number, gy: number) => Vec3clearCosts: () => void@@ -435,6 +436,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: numberoriginX: numberoriginY: numberoriginZ: number+queryWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => NavPathResultsetCost: (gx: number, gy: number, cost: number) => voidsetObstructed: (gx: number, gy: number, obstructed: boolean) => voidsetWalkable: (gx: number, gy: number, walkable: boolean) => void@@ -495,6 +497,7 @@ maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: numberpolys: Int32Array<ArrayBufferLike>+queryWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => NavPathResultsetAreaCost: (area: number, cost: number) => voidsnapDistance: numberup: Vec3@@ -536,6 +539,13 @@ enabled: booleanhalfExtents: Vec3```+## NavPathResult — interface @experimental+```+path: Vec3[] | null+reason: "none" | "no-surface" | "start-unavailable" | "target-unavailable" | "disconnected" | "insufficient-clearance" | "radius-mismatch" | "diagnostics-unavailable"+status: "unknown" | "unavailable" | "complete" | "partial"+```+## NavPlugin — class @experimental```build: (app: App) => void@@ -561,6 +571,7 @@ radius: number | undefineddescribe: (sink: NavSurfaceSink) => voidfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullisNavigable: (p: NavPoint) => boolean+queryWorldPath: ((from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => NavPathResult) | undefinedup: Vec3```@@ -592,6 +603,7 @@ stepHeight: number```findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullhasSurface: () => boolean+queryWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => NavPathResultsetSurface: (surface: NavSurface | null) => voidsurface: NavSurface | nullstatic new (): Navigationdiff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.tsindex c15c0a808..779626338 100644--- a/sdk/src/ai/nav/NavGrid.ts+++ b/sdk/src/ai/nav/NavGrid.ts@@ -17,8 +17,8 @@*/import type { Vec3 } from '../../types';-import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink } from './NavSurface';-import { findPath, pathToWorld, shortenPath } from './pathfind';+import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink, NavPathResult } from './NavSurface';+import { findPath, pathToWorld, shortenPath, resolveEndpoint } from './pathfind';/** Integer grid coordinate. Its own type rather than a world vector, so a cell* coordinate cannot be passed where world pixels are expected. */@@ -67,6 +67,10 @@ export class NavGrid implements NavSurface {private obstructed_: Uint8Array | null = null;/** What crossing each cell costs, or null while it all costs the same. */private cost_: Float32Array | null = null;+ private topologyRevision_ = 0;++ /** @internal Invalidates derived connectivity after walkability changes. */+ get topologyRevision(): number { return this.topologyRevision_; }constructor(opts: NavGridOptions) {this.width = opts.width;@@ -101,7 +105,9 @@ export class NavGrid implements NavSurface {setWalkable(gx: number, gy: number, walkable: boolean): void {if (!this.inBounds(gx, gy)) return;+ if (this.walkable[gy * this.width + gx] === (walkable ? 1 : 0)) return;this.walkable[gy * this.width + gx] = walkable ? 1 : 0;+ this.topologyRevision_++;this.clearance_ = null;}@@ -116,7 +122,9 @@ export class NavGrid implements NavSurface {if (!obstructed) return;this.obstructed_ = new Uint8Array(this.width * this.height);}+ if (this.obstructed_[gy * this.width + gx] === (obstructed ? 1 : 0)) return;this.obstructed_[gy * this.width + gx] = obstructed ? 1 : 0;+ this.topologyRevision_++;this.clearance_ = null;}@@ -124,6 +132,7 @@ export class NavGrid implements NavSurface {clearObstructions(): void {if (!this.obstructed_) return;this.obstructed_.fill(0);+ this.topologyRevision_++;this.clearance_ = null;}@@ -160,7 +169,12 @@ export class NavGrid implements NavSurface {*/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);+ if (!this.clearance_) {+ const mask = this.obstructed_+ ? this.walkable.map((v, i) => this.obstructed_![i] ? 0 : v)+ : this.walkable;+ this.clearance_ = buildClearance(this.width, this.height, mask);+ }return this.clearance_[gy * this.width + gx];}@@ -216,6 +230,26 @@ export class NavGrid implements NavSurface {return this.isWalkable(cell.x, cell.y);}+ /** Diagnose a route without treating a best-effort partial path as arrival. */+ queryWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): NavPathResult {+ const clearance = Math.max(0, Math.ceil((opts?.radius ?? 0) / this.cellSize));+ const start = resolveEndpoint(this, this.worldToCell(from), 8, clearance);+ if (!start) return { path: null, status: 'unavailable', reason: 'start-unavailable' };+ const target = resolveEndpoint(this, this.worldToCell(to), 8, clearance);+ if (!target) return { path: null, status: 'unavailable', reason: 'target-unavailable' };+ const path = this.findWorldPath(from, to, opts);+ const reaches = (p: Vec3[] | null, cell: Cell | null) => {+ if (!p?.length || !cell) return false;+ const end = this.worldToCell(p[p.length - 1]!);+ return end.x === cell.x && end.y === cell.y;+ };+ if (reaches(path, target)) return { path, status: 'complete', reason: 'none' };+ if (clearance > 0 && reaches(this.findWorldPath(from, to), resolveEndpoint(this, this.worldToCell(to), 8, 0))) {+ return { path, status: path ? 'partial' : 'unavailable', reason: 'insufficient-clearance' };+ }+ return { path, status: path ? 'partial' : 'unavailable', reason: 'disconnected' };+ }+/*** Every walkable cell as a quad, and every edge where the walkable world* stops. The corner array is reused between calls — see {@link NavSurfaceSink}.diff --git a/sdk/src/ai/nav/NavMesh.ts b/sdk/src/ai/nav/NavMesh.tsindex d4391d01c..c8dc995e6 100644--- a/sdk/src/ai/nav/NavMesh.ts+++ b/sdk/src/ai/nav/NavMesh.ts@@ -15,7 +15,7 @@*/import type { Vec3 } from '../../types';-import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink } from './NavSurface';+import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink, NavPathResult } from './NavSurface';import { MinHeap } from './minHeap';import { log } from '../../util/logger';@@ -352,6 +352,18 @@ export class NavMesh implements NavSurface {}findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null {+ return this.planWorldPath(from, to, opts).path;+ }++ /** Refuse an undersized bake explicitly instead of returning an unsafe body route. */+ queryWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): NavPathResult {+ if ((opts?.radius ?? 0) > this.agentRadius + 1e-3) {+ return { path: null, status: 'unavailable', reason: 'radius-mismatch' };+ }+ return this.planWorldPath(from, to, opts);+ }++ private planWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): NavPathResult {const radius = opts?.radius ?? 0;if (radius > this.agentRadius + 1e-3) warnRadius(radius, this.agentRadius);@@ -361,12 +373,14 @@ export class NavMesh implements NavSurface {// A goal off the mesh is still a direction to walk in. Only an agent that// is itself nowhere has no route at all.const endPoly = this.findPoly(to, end);- if (startPoly < 0) return null;+ if (startPoly < 0) return { path: null, status: 'unavailable', reason: 'start-unavailable' };if (endPoly < 0) { end.x = to.x; end.y = to.y; end.z = to.z ?? 0; }- if (startPoly === endPoly) return [start, end];+ if (startPoly === endPoly) return { path: [start, end], status: 'complete', reason: 'none' };const polyPath = this.findPolyPath(startPoly, endPoly, start, end);- return this.routeThroughLinks(polyPath, start, polyPath.end);+ return { path: this.routeThroughLinks(polyPath, start, polyPath.end),+ status: polyPath.reached ? 'complete' : 'partial',+ reason: polyPath.reached ? 'none' : endPoly < 0 ? 'target-unavailable' : 'disconnected' };}/**@@ -493,7 +507,7 @@ export class NavMesh implements NavSurface {// Shift by one: `links[i]` is now the step from `polys[i]` to `polys[i+1]`.links.shift();links.push(-1);- return { polys, links, end: finish };+ return { polys, links, end: finish, reached };}/**@@ -610,6 +624,7 @@ export class NavMesh implements NavSurface {/** A route as the search found it: the polygons walked, and for each step the* link that made it, or -1 where the two polygons share an edge. */interface PolyPath {+ reached: boolean;polys: number[];links: number[];/** Where the route finishes, which is the goal only when it was reached. */diff --git a/sdk/src/ai/nav/NavSurface.ts b/sdk/src/ai/nav/NavSurface.tsindex 51876a92a..318893ed4 100644--- a/sdk/src/ai/nav/NavSurface.ts+++ b/sdk/src/ai/nav/NavSurface.ts@@ -35,6 +35,14 @@ export interface NavQueryOptions {radius?: number;}+/** Completeness refers to the surface's resolved (possibly snapped) destination. */+export interface NavPathResult {+ path: Vec3[] | null;+ status: 'complete' | 'partial' | 'unavailable' | 'unknown';+ reason: 'none' | 'no-surface' | 'start-unavailable' | 'target-unavailable'+ | 'disconnected' | 'insufficient-clearance' | 'radius-mismatch' | 'diagnostics-unavailable';+}+/*** Where a surface hands out its shape, for a drawer to turn into lines. A* visitor rather than a returned array because the caller is a per-frame overlay@@ -69,6 +77,9 @@ export interface NavSurface {*/findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null;+ /** Optional for custom surfaces; built-ins distinguish partial routes from arrival. */+ queryWorldPath?(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): NavPathResult;+/*** Whether an agent may stand at a world point. Asked of a place the agent has* not been routed to — a step sideways to get round another body — which isdiff --git a/sdk/src/ai/nav/Navigation.ts b/sdk/src/ai/nav/Navigation.tsindex d6c67a4bb..e7dcf079d 100644--- a/sdk/src/ai/nav/Navigation.ts+++ b/sdk/src/ai/nav/Navigation.ts@@ -12,7 +12,7 @@import { defineResource } from '../../ecs/resource';import type { Vec3 } from '../../types';-import type { NavPoint, NavQueryOptions, NavSurface } from './NavSurface';+import type { NavPoint, NavQueryOptions, NavSurface, NavPathResult } from './NavSurface';export class Navigation {/** Where agents may walk, or null until something builds and installs it. */@@ -33,6 +33,13 @@ export class Navigation {findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null {return this.surface ? this.surface.findWorldPath(from, to, opts) : null;}++ /** Explain a built-in route; custom surfaces without diagnostics report unknown. */+ queryWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): NavPathResult {+ if (!this.surface) return { path: null, status: 'unavailable', reason: 'no-surface' };+ if (this.surface.queryWorldPath) return this.surface.queryWorldPath(from, to, opts);+ return { path: this.surface.findWorldPath(from, to, opts), status: 'unknown', reason: 'diagnostics-unavailable' };+ }}export const Nav = defineResource<Navigation>(null!, 'Nav');diff --git a/sdk/src/ai/nav/gridConnectivity.ts b/sdk/src/ai/nav/gridConnectivity.tsnew file mode 100644index 000000000..95fffb453--- /dev/null+++ b/sdk/src/ai/nav/gridConnectivity.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { NavGrid, Cell } from './NavGrid';++interface Components { labels: Int32Array; cells: number[][] }+interface Cache { revision: number; radii: Map<number, Components> }+const caches = new WeakMap<NavGrid, Cache>();+const fits = (grid: NavGrid, x: number, y: number, radius: number) =>+ grid.isWalkable(x, y) && (radius <= 0 || grid.clearanceAt(x, y) >= radius);++/** A failed search establishes connectivity once for subsequent requests on this map. */+export function rememberGridComponents(grid: NavGrid, radius: number): void {+ let cache = caches.get(grid);+ if (!cache || cache.revision !== grid.topologyRevision) {+ cache = { revision: grid.topologyRevision, radii: new Map() };+ caches.set(grid, cache);+ }+ if (cache.radii.has(radius)) return;+ // Bound storage when a game asks for many different body sizes.+ if (cache.radii.size >= 4) cache.radii.delete(cache.radii.keys().next().value!);+ const { width, height } = grid;+ const labels = new Int32Array(width * height), cells: number[][] = [];+ for (let i = 0; i < labels.length; i++) {+ if (labels[i] || !fits(grid, i % width, Math.floor(i / width), radius)) continue;+ const group = [i], label = cells.length + 1;+ cells.push(group); labels[i] = label;+ for (let head = 0; head < group.length; head++) {+ const at = group[head]!, x = at % width, y = Math.floor(at / width);+ for (const next of [x > 0 ? at - 1 : -1, x + 1 < width ? at + 1 : -1,+ y > 0 ? at - width : -1, y + 1 < height ? at + width : -1]) {+ if (next < 0 || labels[next] || !fits(grid, next % width, Math.floor(next / width), radius)) continue;+ labels[next] = label; group.push(next);+ }+ }+ }+ cache.radii.set(radius, { labels, cells });+}++/** Retarget a disconnected query to its nearest reachable cell; preserve partial routes. */+export function cachedGridGoal(+ grid: NavGrid, start: Cell, goal: Cell, radius: number,+ distance: (x: number, y: number) => number,+): Cell | null {+ const cache = caches.get(grid);+ if (!cache || cache.revision !== grid.topologyRevision) return null;+ const components = cache.radii.get(radius);+ if (!components) return null;+ const label = components.labels[grid.index(start.x, start.y)]!;+ // A cramped starting cell may escape into an adjacent component; use the search.+ if (!label || !components.labels[grid.index(goal.x, goal.y)]+ || label === components.labels[grid.index(goal.x, goal.y)]) return null;+ let best = grid.index(start.x, start.y), nearest = distance(start.x, start.y);+ for (const cell of components.cells[label - 1]!) {+ const score = distance(cell % grid.width, Math.floor(cell / grid.width));+ if (score < nearest) { nearest = score; best = cell; }+ }+ return { x: best % grid.width, y: Math.floor(best / grid.width) };+}diff --git a/sdk/src/ai/nav/index.ts b/sdk/src/ai/nav/index.tsindex 5fe58ed9d..47ac4029a 100644--- a/sdk/src/ai/nav/index.ts+++ b/sdk/src/ai/nav/index.ts@@ -6,7 +6,7 @@*/export type {- NavSurface, NavSurfaceSink, NavQueryOptions, NavPoint,+ NavSurface, NavSurfaceSink, NavQueryOptions, NavPoint, NavPathResult,} from './NavSurface';export { NavGrid, type NavGridOptions, type Cell } from './NavGrid';export { findPath, pathToWorld, type PathfindOptions } from './pathfind';diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.tsindex 77e913c39..488ad37a3 100644--- a/sdk/src/ai/nav/pathfind.ts+++ b/sdk/src/ai/nav/pathfind.ts@@ -12,6 +12,7 @@import type { NavGrid, Cell } from './NavGrid';import { MinHeap } from './minHeap';+import { cachedGridGoal, rememberGridComponents } from './gridConnectivity';import type { Vec3 } from '../../types';export interface PathfindOptions {@@ -58,8 +59,10 @@ export function findPath(const clearance = Math.max(0, opts.clearance ?? 0);const s = resolveEndpoint(grid, start, snapRadius, clearance);- const g = resolveEndpoint(grid, goal, snapRadius, clearance);+ let g = resolveEndpoint(grid, goal, snapRadius, clearance);if (!s || !g) return null;+ const requestedGoal = g;+ g = cachedGridGoal(grid, s, g, clearance, (x, y) => heuristic(x, y, requestedGoal.x, requestedGoal.y, diagonal)) ?? g;const { width, height } = grid;const n = width * height;@@ -115,6 +118,7 @@ export function findPath(}}+ rememberGridComponents(grid, clearance);return reconstruct(cameFrom, nearestIdx, width);}@@ -174,7 +178,8 @@ function fits(grid: NavGrid, gx: number, gy: number, clearance: number): booleanreturn clearance <= 0 || grid.clearanceAt(gx, gy) >= clearance;}-function resolveEndpoint(grid: NavGrid, c: Cell, snapRadius: number, clearance: number): Cell | null {+/** @internal Shared endpoint policy for routes and their diagnostics. */+export 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;// An agent already jammed against a wall must still be given a way out, sodiff --git a/sdk/tests/nav-query-diagnostics.test.ts b/sdk/tests/nav-query-diagnostics.test.tsnew file mode 100644index 000000000..b9ed83e7e--- /dev/null+++ b/sdk/tests/nav-query-diagnostics.test.ts@@ -0,0 +1,131 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { Navigation } from '../src/ai/nav/Navigation';+import { NavGrid } from '../src/ai/nav/NavGrid';+import { NavMesh } from '../src/ai/nav/NavMesh';+import { findPath } from '../src/ai/nav/pathfind';++const islands = () => new NavMesh({+ verts: new Float32Array([0,0,0,10,0,0,10,0,10,0,0,10,20,0,0,30,0,0,30,0,10,20,0,10]),+ polys: new Int32Array([0,1,2,3,4,5,6,7]), neis: new Int32Array(8).fill(-1),+ polyCount: 2, maxVertsPerPoly: 4, agentRadius: 1, snapDistance: 0.1,+ verticalReach: 5, areas: new Uint8Array([1,1]),+});++describe('route diagnostics', () => {+ it('reports no surface and does not guess completeness for custom surfaces', () => {+ const nav = new Navigation(), p = { x: 0, y: 0 };+ expect(nav.queryWorldPath(p, p)).toEqual({ path: null, status: 'unavailable', reason: 'no-surface' });+ nav.setSurface({ up: { x: 0, y: 0, z: 1 }, findWorldPath: () => [], isNavigable: () => true, describe: () => {} });+ expect(nav.queryWorldPath(p, p)).toEqual({ path: [], status: 'unknown', reason: 'diagnostics-unavailable' });+ });++ it('distinguishes a complete grid path from a disconnected best-effort path', () => {+ const grid = new NavGrid({ width: 11, height: 9, cellSize: 1 });+ const start = { x: 2, y: 4 }, target = { x: 8, y: 4 };+ expect(grid.queryWorldPath(start, target).status).toBe('complete');+ for (let y = 0; y < 9; y++) grid.setWalkable(5, y, false);+ for (let i = 0; i < 3; i++) {+ const query = grid.queryWorldPath(start, target);+ expect(query.status).toBe('partial'); expect(query.reason).toBe('disconnected');+ expect(query.path?.at(-1)?.x).toBe(4);+ }+ grid.setWalkable(5, 4, true);+ expect(grid.queryWorldPath(start, target).status).toBe('complete');+ });++ it('explains radius-dependent failure through a one-cell door', () => {+ const grid = new NavGrid({ width: 11, height: 9, cellSize: 1 });+ for (let y = 0; y < 9; y++) if (y !== 4) grid.setWalkable(5, y, false);+ const start = { x: 2, y: 4 }, goal = { x: 8, y: 4 };+ expect(grid.queryWorldPath(start, goal).status).toBe('complete');+ expect(grid.queryWorldPath(start, goal, { radius: 2 })).toMatchObject({ status: 'partial', reason: 'insufficient-clearance' });+ });++ it('keeps endpoint snapping and explains endpoints outside its reach', () => {+ const grid = new NavGrid({ width: 10, height: 10, cellSize: 1 });+ grid.setWalkable(5, 5, false);+ expect(grid.queryWorldPath({ x: 2, y: 2 }, { x: 5, y: 5 }).status).toBe('complete');+ expect(grid.queryWorldPath({ x: -50, y: 0 }, { x: 2, y: 2 }).reason).toBe('start-unavailable');+ expect(grid.queryWorldPath({ x: 2, y: 2 }, { x: 50, y: 50 }).reason).toBe('target-unavailable');+ });++ it('mesh diagnostics retain actual search completeness and reject an undersized bake', () => {+ const mesh = islands(), from = { x: 5, y: 0, z: 5 };+ expect(mesh.queryWorldPath(from, { x: 8, y: 0, z: 8 }).status).toBe('complete');+ expect(mesh.queryWorldPath(from, { x: 25, y: 0, z: 5 })).toMatchObject({ status: 'partial', reason: 'disconnected' });+ expect(mesh.queryWorldPath(from, { x: 100, y: 0, z: 5 })).toMatchObject({ status: 'partial', reason: 'target-unavailable' });+ expect(mesh.queryWorldPath({ x: -100, y: 0, z: 5 }, from).reason).toBe('start-unavailable');+ expect(mesh.queryWorldPath(from, from, { radius: 2 })).toEqual({ path: null, status: 'unavailable', reason: 'radius-mismatch' });+ });+});++describe('cached disconnected grid searches', () => {+ it('retains the first search nearest-endpoint distance across deterministic maps', () => {+ let seed = 17;+ const random = () => ((seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 0x100000000);+ const distance = (p: { x: number; y: number }) => {+ const x = 8 - p.x, y = 8 - p.y;+ return x + y + (Math.SQRT2 - 2) * Math.min(x, y);+ };+ for (let sample = 0; sample < 40; sample++) {+ const mask = Uint8Array.from({ length: 81 }, () => random() > 0.25 ? 1 : 0);+ mask[0] = mask[80] = 1;+ if (sample % 2) for (let y = 0; y < 9; y++) mask[y * 9 + 4] = 0;+ const grid = new NavGrid({ width: 9, height: 9, cellSize: 1, walkable: mask });+ const first = findPath(grid, { x: 0, y: 0 }, { x: 8, y: 8 })!;+ const repeated = findPath(grid, { x: 0, y: 0 }, { x: 8, y: 8 })!;+ expect(distance(repeated.at(-1)!)).toBeCloseTo(distance(first.at(-1)!));+ for (let i = 1; i < repeated.length; i++) {+ const a = repeated[i - 1]!, b = repeated[i]!;+ expect(grid.isWalkable(b.x, b.y)).toBe(true);+ expect(Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y))).toBe(1);+ if (a.x !== b.x && a.y !== b.y) {+ expect(grid.isWalkable(a.x, b.y) && grid.isWalkable(b.x, a.y)).toBe(true);+ }+ }+ }+ });+ it('invalidates after obstacle removal and still routes around newly placed blockers', () => {+ const grid = new NavGrid({ width: 11, height: 9, cellSize: 1 });+ for (let y = 0; y < 9; y++) grid.setObstructed(5, y, true);+ const a = { x: 2, y: 4 }, b = { x: 8, y: 4 };+ expect(findPath(grid, a, b)?.at(-1)?.x).toBe(4);+ expect(findPath(grid, a, b)?.at(-1)?.x).toBe(4);+ grid.clearObstructions();+ expect(findPath(grid, a, b)?.at(-1)).toEqual(b);+ grid.setObstructed(4, 4, true);+ expect(findPath(grid, a, b)?.some(p => p.x === 4 && p.y === 4)).toBe(false);+ });++ it('includes dynamic blockers in clearance and restores room after removal', () => {+ const grid = new NavGrid({ width: 11, height: 9, cellSize: 1 });+ expect(grid.clearanceAt(4, 4)).toBeGreaterThan(1);+ grid.setObstructed(5, 4, true);+ expect(grid.clearanceAt(4, 4)).toBe(1);+ grid.clearObstructions();+ expect(grid.clearanceAt(4, 4)).toBeGreaterThan(1);+ });++ it('keeps weighted routing live after connectivity is remembered', () => {+ const grid = new NavGrid({ width: 9, height: 5, cellSize: 1 });+ for (let y = 0; y < 5; y++) grid.setWalkable(4, y, false);+ const a = { x: 0, y: 2 }, b = { x: 8, y: 2 };+ findPath(grid, a, b);+ grid.setCost(2, 2, 100);+ const path = findPath(grid, a, b)!;+ expect(path.at(-1)).toEqual({ x: 3, y: 2 });+ expect(path.some(p => p.x === 2 && p.y === 2)).toBe(false);+ });++ it('does not connect diagonal corners or reuse clearance for another body size', () => {+ const pinched = new NavGrid({ width: 2, height: 2, cellSize: 1, walkable: [1,0,0,1] });+ for (let i = 0; i < 2; i++) expect(findPath(pinched, { x: 0, y: 0 }, { x: 1, y: 1 })).toEqual([{ x: 0, y: 0 }]);+ const grid = new NavGrid({ width: 11, height: 9, cellSize: 1 });+ for (let y = 0; y < 9; y++) if (y !== 4) grid.setWalkable(5, y, false);+ const a = { x: 2, y: 4 }, b = { x: 8, y: 4 };+ for (let i = 0; i < 2; i++) expect(grid.queryWorldPath(a, b, { radius: 2 }).reason).toBe('insufficient-clearance');+ expect(grid.queryWorldPath(a, b).status).toBe('complete');+ });+});diff --git a/tools/fixtures/navigation-build-corpus.ts b/tools/fixtures/navigation-build-corpus.tsnew file mode 100644index 000000000..9bb50b816--- /dev/null+++ b/tools/fixtures/navigation-build-corpus.ts@@ -0,0 +1,102 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { buildNavMesh } from '../../sdk/src/ai/nav/navmesh/build';+import { NavGrid } from '../../sdk/src/ai/nav/NavGrid';+import { applyObstaclesToGrid, type NavObstacleBox } from '../../sdk/src/ai/nav/navObstacles';++const cellSize = 10;+const rotation = { x: 0, y: 0, z: 0, w: 1 };+const percentile = (a: number[], q: number) => [...a].sort((x, y) => x - y)[Math.ceil(q * a.length) - 1]!;+const frame = () => new Promise<number>(resolve => requestAnimationFrame(() => resolve(performance.now())));++/** Deterministic building footprints and a wall with a six-cell door. */+function obstacles(size: number, closed: boolean, placed: boolean): NavObstacleBox[] {+ const span = size * cellSize, mid = span / 2, gap = cellSize * 3;+ const boxes: NavObstacleBox[] = [];+ const add = (x: number, z: number, hx: number, hz: number) => boxes.push({+ center: { x, y: 15, z }, halfExtents: { x: hx, y: 20, z: hz }, rotation,+ });+ add(mid, (mid - gap) / 2, cellSize, (mid - gap) / 2);+ add(mid, (span + mid + gap) / 2, cellSize, (span - mid - gap) / 2);+ if (closed) add(mid, mid, cellSize, gap);+ for (let z = 8; z < size - 5; z += 12) for (let x = 7; x < size - 5; x += 12) {+ if (Math.abs(x - size / 2) < 7 || Math.abs(z - size / 2) < 5) continue;+ add(x * cellSize, z * cellSize, cellSize * 2, cellSize * 2);+ }+ if (placed) add(span * 0.25, mid - cellSize * 4, cellSize * 2, cellSize * 2);+ return boxes;+}++export async function runNavigationBuildCorpus() {+ const records = [];+ for (const size of [32, 64, 128]) {+ const span = size * cellSize;+ const verts = new Float32Array([0, 0, 0, span, 0, 0, span, 0, span, 0, 0, span]);+ const indices = new Uint32Array([0, 2, 1, 0, 3, 2]);+ for (const mode of ['mesh-full-bake', 'grid-obstacle-update'] as const) {+ const grid = new NavGrid({ width: size, height: size, cellSize });+ const samples = [], queries = [], totals = [], frameGaps = [], shapes = [];+ for (let iteration = -3; iteration < 16; iteration++) {+ const closed = iteration % 2 === 0, placed = iteration % 3 === 0;+ const boxes = obstacles(size, closed, placed);+ const beforeFrame = await frame();+ const start = performance.now();+ let route: { x: number; y: number; z: number }[] | null;+ let polygons = 0;+ let surface: NavGrid | ReturnType<typeof buildNavMesh>;+ if (mode === 'mesh-full-bake') {+ const mesh = buildNavMesh(verts, indices, {+ min: { x: 0, y: -20, z: 0 }, max: { x: span, y: 80, z: span },+ cellSize, cellHeight: 2, agentRadius: 5, agentHeight: 20, stepHeight: 4,+ minRegionArea: 0, obstacles: boxes,+ });+ const elapsed = performance.now() - start;+ surface = mesh;+ polygons = mesh.polyCount;+ if (iteration >= 0) samples.push(elapsed);+ } else {+ applyObstaclesToGrid(grid, boxes.map(b => ({+ ...b, center: { x: b.center.x, y: b.center.z, z: 0 },+ halfExtents: { x: b.halfExtents.x, y: b.halfExtents.z, z: 20 },+ })));+ if (iteration >= 0) samples.push(performance.now() - start);+ surface = grid;+ }+ const queryStart = performance.now();+ route = mode === 'mesh-full-bake'+ ? surface.findWorldPath({ x: span * 0.2, y: 2, z: span / 2 }, { x: span * 0.8, y: 2, z: span / 2 }, { radius: 5 })+ : surface.findWorldPath({ x: span * 0.2, y: span / 2 }, { x: span * 0.8, y: span / 2 }, { radius: 5 });+ for (let agent = 1; agent < 64; agent++) {+ const a = span * (0.15 + 0.7 * (agent % 16) / 15);+ const b = span * (0.15 + 0.7 * ((agent * 7) % 16) / 15);+ surface.findWorldPath(mode === 'mesh-full-bake' ? { x: span * 0.2, y: 2, z: a } : { x: span * 0.2, y: a },+ mode === 'mesh-full-bake' ? { x: span * 0.8, y: 2, z: b } : { x: span * 0.8, y: b }, { radius: 5 });+ }+ const queryMs = performance.now() - queryStart;+ const totalMs = performance.now() - start;+ const nextFrame = await frame();+ if (nextFrame - beforeFrame + 1 < totalMs) throw Error('Frame interval does not cover the measured CPU work');+ if (iteration >= 0) {+ frameGaps.push(nextFrame - beforeFrame);+ queries.push(queryMs); totals.push(totalMs);+ shapes.push({ closed, placed, obstacleCount: boxes.length, polygons, waypoints: route?.length ?? 0,+ end: route?.at(-1) ?? null });+ }+ }+ const target = span * 0.8;+ for (const [i, shape] of shapes.entries()) {+ if (!shape.end) throw Error('No route in corpus ' + mode + '/' + size + '/' + i);+ const complete = mode === 'mesh-full-bake' ? shape.end.x >= target - cellSize * 2 : shape.end.x >= target - cellSize;+ if (complete === shape.closed) throw Error('Door did not change reachability: ' + JSON.stringify(shape));+ }+ records.push({ mode, size, cellSize, triangles: 2, agents: 64,+ samplesMs: samples, querySamplesMs: queries, totalSamplesMs: totals, frameGapsMs: frameGaps,+ medianMs: percentile(samples, 0.5), p95Ms: percentile(samples, 0.95),+ queryP95Ms: percentile(queries, 0.95), updateP95Ms: percentile(totals, 0.95),+ overFrameBudget: samples.filter(ms => ms > 1000 / 60).length,+ updatesOverFrameBudget: totals.filter(ms => ms > 1000 / 60).length,+ frameGapP95Ms: percentile(frameGaps, 0.95), shapes });+ }+ }+ return { frameBudgetMs: 1000 / 60, warmup: 3, samples: 16, records };+}diff --git a/tools/navigation-rebuild-benchmark.mjs b/tools/navigation-rebuild-benchmark.mjsnew file mode 100644index 000000000..93af3bde1--- /dev/null+++ b/tools/navigation-rebuild-benchmark.mjs@@ -0,0 +1,51 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { build } from 'esbuild';+import { chromium } from 'playwright';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const source = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', windowsHide: true }).trim();+const args = process.argv.slice(2);+const referenceArg = args.find(a => a.startsWith('--search-reference='))?.slice('--search-reference='.length);+const reference = referenceArg ? execFileSync('git', ['rev-parse', '--verify', referenceArg + '^{commit}'],+ { cwd: root, encoding: 'utf8', windowsHide: true }).trim() : null;+const plugins = reference ? [{ name: 'reference-grid-search', setup(builder) {+ builder.onLoad({ filter: /[\\/]nav[\\/]pathfind\.ts$/ }, () => {+ let contents = execFileSync('git', ['show', reference + ':sdk/src/ai/nav/pathfind.ts'],+ { cwd: root, encoding: 'utf8', windowsHide: true });+ if (!contents.includes('export function resolveEndpoint')) contents += '\nexport { resolveEndpoint };\n';+ return { contents, loader: 'ts', resolveDir: path.join(root, 'sdk/src/ai/nav') };+ });+} }] : [];+const bundle = await build({ entryPoints: [path.join(root, 'tools/fixtures/navigation-build-corpus.ts')],+ bundle: true, platform: 'browser', format: 'iife', globalName: 'NavBuildCorpus', write: false, plugins });+const code = bundle.outputFiles[0].text;+const browser = await chromium.launch({ headless: true });+try {+ const page = await browser.newPage();+ await page.addScriptTag({ content: code });+ const result = await page.evaluate(() => window.NavBuildCorpus.runNavigationBuildCorpus());+ const report = { recordedAt: new Date().toISOString(),+ source,+ bundleSha256: createHash('sha256').update(code).digest('hex'),+ searchReference: reference,+ searchReferenceScope: reference ? 'Only pathfind.ts comes from the reference; all other code, including dynamic-obstacle clearance, is current.' : null,+ sourceDirtyFiles: execFileSync('git', ['status', '--porcelain=1', '--untracked-files=all', '--', 'sdk/src/ai/nav'],+ { cwd: root, encoding: 'utf8', windowsHide: true }).split('\n').filter(Boolean).map(line => line.slice(3)),+ platform: process.platform, cpu: os.cpus()[0]?.model, browser: browser.version(),+ scope: 'Main-thread mesh rebuild or 2D grid obstacle marking plus 64 agent replans. Frame gaps include both. No editor, rendering, physics collection, avoidance or full game frame.',+ ...result };+ const destination = path.resolve(root, args.find(a => !a.startsWith('--')) ?? 'output/navigation-rebuild-baseline.json');+ fs.mkdirSync(path.dirname(destination), { recursive: true });+ fs.writeFileSync(destination, JSON.stringify(report, null, 2));+ for (const r of result.records) console.log(`${r.mode} ${r.size}x${r.size}: rebuild-p95=${r.p95Ms.toFixed(2)}ms replan64-p95=${r.queryP95Ms.toFixed(2)}ms total-p95=${r.updateP95Ms.toFixed(2)}ms over-budget=${r.updatesOverFrameBudget}/16 frame-gap-p95=${r.frameGapP95Ms.toFixed(2)}ms`);+ console.log(destination);+} finally {+ await browser.close();+}diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex c1eb4c9cb..aadaf6a77 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(nav): diagnose partial routes and reuse disconnected grid topology':+ { note: 'Navigation queries distinguish complete routes from best-effort paths.' },'perf(text): wrap native measurements with ordered advances':{ note: 'Native text measurement wraps without rescanning growing prefixes.' },'fix(text): bound native measurement advance history':