Skip to content

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.

feat(nav): budget agent replans fairly across frames

yhh32a095931e3f
diff --git a/.github/workflows/navigation-cpu.yml b/.github/workflows/navigation-cpu.yml
index c9bc55837..c32409bc8 100644
--- a/.github/workflows/navigation-cpu.yml
+++ b/.github/workflows/navigation-cpu.yml
@@ -34,6 +34,8 @@ jobs:
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
+ - name: Measure agent planning budgets on the same building maps
+ run: node tools/navigation-planning-benchmark.mjs output/navigation-cpu-ci/planning.json
- uses: actions/upload-artifact@v7
if: always()
with:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 410555c7a..664dc3b0a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,8 @@ published separately; it ships inside the editor.
### Added
+- **Agent replans share a fair per-frame budget.** Navigation defaults to a FIFO queue with 16 plans and a 2 ms soft planning budget per tick; limits and last-tick counters are exposed on Nav and sampled in the Play inspector. Queued edits coalesce, agents without valid routes pause safely, periodic refreshes keep valid movement, and surface/grid/radius invalidation retires stale routes. Direct queries remain synchronous. A single query may exceed the budget, and spreading work adds route latency.
+
- **Inspect a live agent's current route on demand.** The Play inspector reports partial routes, disconnected regions, insufficient clearance and baked-radius mismatches, with sampled world endpoints, radius and query cost. It queries only on request, discards results across selection/session changes, and identifies unsupported device sessions or custom implementations explicitly.
- **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.
diff --git a/desktop b/desktop
index af5b633f9..bb3c8b564 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit af5b633f9739abd1dcf4bbae555727b008529823
+Subproject commit bb3c8b564150d2b388038a10dbf2f1f143571fb4
diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
index 3b29e2389..e537afd5f 100644
--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
@@ -288,6 +288,46 @@ geometry collection, avoidance, rendering and the rest of the game frame.
### Moving an agent
+`NavAgentSystem` serves planning requests in FIFO order across frames. By default
+it allows **16 plans** and a **2 ms soft planning budget** per tick. At least one
+query can run; the time check happens between synchronous queries, so one query
+can exceed the budget. This spreads bursts by adding route latency, rather than
+making the same work free. Direct `findWorldPath` / `queryWorldPath` calls remain
+synchronous and are outside this queue.
+
+```typescript
+const nav = app.getResource(Nav);
+nav.planningBudgetMs = 2;
+nav.maxPlansPerFrame = 16;
+// Set either limit to 0 to disable that limit.
+console.info(nav.planningStats); // completed, pending, elapsedMs from the last tick
+```
+
+Queued requests read the latest position, target and radius when served. Agents
+without a valid route pause; periodic refreshes keep following valid cached routes.
+When paused, character steering stops horizontally while gravity
+remains active. Replacing the surface, editing built-in grid topology, or changing
+an agent's radius retires stale routes, including agents whose periodic replanning
+is disabled. After changing a custom surface or its costs/links in place, call
+`nav.invalidatePaths()`. A transient failed query on an unchanged surface can keep
+an existing route while an agent crosses a link; an invalidated route is discarded.
+
+The editor's **Inspect current route** also samples the last planning tick's
+completed/pending counts, time and configured limits. This is a queue snapshot,
+not the time taken by the manual diagnostic query or by a navigation rebuild.
+
+To compare unlimited planning with the defaults on identical building maps:
+
+```sh
+node tools/navigation-planning-benchmark.mjs output/navigation-planning.json
+```
+
+The headless report keeps all 64 route shapes, per-frame CPU and callback gaps,
+batch completion latency and total CPU. It includes obstacle marking and the
+agent step over an in-memory World with zero movement speed; it excludes actual
+rendering, physics and the rest of an application frame. Lower peak CPU does not
+prove a full game reaches 60 FPS.
+
Attach a `NavAgent`, then point it at a destination. The built-in nav plugin plans
the path and steps the agent along it each frame — you just set the goal.
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.mdx
index b23199dc1..1addaa521 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
@@ -244,6 +244,37 @@ node tools/navigation-rebuild-benchmark.mjs output/navigation-reference.json --s
### 移动 agent
+`NavAgentSystem` 按先进先出顺序,跨帧处理规划请求。默认每帧最多 **16 次查询**,
+规划时间采用 **2 毫秒软预算**。至少允许一次查询;时间只在同步查询之间检查,单次查询
+仍可能超时。这通过增加路线等待时间来分摊峰值,不会消除总工作量。
+直接调用 `findWorldPath` / `queryWorldPath` 仍是同步查询,不经过该队列。
+
+```typescript
+const nav = app.getResource(Nav);
+nav.planningBudgetMs = 2;
+nav.maxPlansPerFrame = 16;
+// 某项限制设为 0,表示关闭该项限制。
+console.info(nav.planningStats); // 上一帧的 completed、pending、elapsedMs
+```
+
+排队期间的目标修改会合并,实际处理时读取最新位置、目标和半径。没有有效路线的代理暂停;
+普通周期刷新排队时继续沿有效缓存路线移动。暂停时角色控制器停止水平操舵,但保留重力速度。
+更换导航表面、修改内置格子拓扑或代理半径后,
+旧路线会失效,包括关闭周期重规划的代理。原地修改自定义表面、区域价格或连接后,
+请调用 `nav.invalidatePaths()`。未改变的表面临时查询失败时,可保留跨连接中的既有路线;
+已失效的路线不会恢复使用。
+
+编辑器的**诊断当前路线**会同时采样上一帧规划完成量、待处理数、耗时和预算。
+这是队列快照,不是手动诊断查询或导航重建的耗时。
+
+```sh
+node tools/navigation-planning-benchmark.mjs output/navigation-planning.json
+```
+
+该无头对照在相同建造地图上比较不限量和默认预算,保留所有 64 条路线、逐帧 CPU 与回调间隔、
+整批等待时间和总 CPU。包含障碍重标记以及零移动速度的内存 World 代理更新,
+不包含实际渲染、物理和应用其余帧工作,峰值降低不能证明完整游戏达到 60 FPS。
+
加一个 `NavAgent`,然后给它指一个目的地。内置的导航插件会规划路径并每帧沿路径推进 agent——
你只管设目标。
diff --git a/sdk/etc/ai.api.md b/sdk/etc/ai.api.md
index 8f03ab705..c9ab94899 100644
--- a/sdk/etc/ai.api.md
+++ b/sdk/etc/ai.api.md
@@ -603,6 +603,11 @@ stepHeight: number
```
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
hasSurface: () => boolean
+invalidatePaths: () => void
+maxPlansPerFrame: number
+pathRevision: number
+planningBudgetMs: number
+planningStats: { completed: number; pending: number; elapsedMs: number; }
queryWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => NavPathResult
setSurface: (surface: NavSurface | null) => void
surface: NavSurface | null
diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.ts
index d804fef31..a13218255 100644
--- a/sdk/src/ai/nav/NavPlugin.ts
+++ b/sdk/src/ai/nav/NavPlugin.ts
@@ -43,6 +43,7 @@ import { NavArea } from './NavArea';
import { setupNavDebugDraw } from './NavDebugDraw';
import { advanceAlongPath } from './follow';
import { avoidVelocity, type AvoidanceNeighbour } from './avoidance';
+import { planNavigation } from './navPlanning';
/** Per-entity runtime path state, owned by the driving system (not serialized). */
export interface AgentRuntime {
@@ -51,6 +52,7 @@ export interface AgentRuntime {
plannedX: number;
plannedY: number;
plannedZ: number;
+ plannedRadius?: number;
repathTimer: number;
reachable: boolean;
/** What it travelled at last frame, on the two axes it steers on. Everyone
@@ -176,7 +178,7 @@ export function updateLinks(
if (digest === state.digest && mesh === state.mesh) return;
state.digest = digest;
state.mesh = mesh;
- if (mesh) mesh.connect(links);
+ if (mesh) { mesh.connect(links); nav.invalidatePaths(); }
}
/** What the obstacles were when the world was last built for them. */
@@ -250,57 +252,34 @@ export function stepNavigation(
// A flat scene is walked in x/y; ground with height in it, in x/z.
const flat = Math.abs(nav.surface?.up.z ?? 0) > Math.abs(nav.surface?.up.y ?? 1);
const entities = world.getEntitiesWithComponents([NavAgent, Transform]);
+ const blocked = planNavigation(world, nav, dt, runtimes, entities);
+ // Agents awaiting a valid route must not retain old steering velocity. Keep
+ // vertical velocity: gravity and the character solver still own that axis.
+ for (const entity of entities) {
+ const active = world.get(entity, NavAgent).hasTarget;
+ if (!blocked.has(entity) && (!active || runtimes.get(entity)?.reachable)) continue;
+ const rt = runtimes.get(entity);
+ if (rt) { rt.velocityA = 0; rt.velocityB = 0; }
+ if (world.has(entity, CharacterController3D)) {
+ const character = world.get(entity, CharacterController3D);
+ if (character.enabled !== false) {
+ character.velocity.x = 0; character.velocity.z = 0;
+ world.set(entity, CharacterController3D, character);
+ }
+ }
+ }
const crowd = gatherCrowd(world, entities, runtimes, flat);
for (const entity of entities) {
const agent = world.get(entity, NavAgent);
- if (!agent.hasTarget) {
- runtimes.delete(entity);
- continue;
- }
+ if (!agent.hasTarget || blocked.has(entity)) continue;
const tf = world.get(entity, Transform);
- let rt = runtimes.get(entity);
-
- const targetMoved = !rt || rt.plannedX !== agent.targetX || rt.plannedY !== agent.targetY
- || rt.plannedZ !== agent.targetZ;
- const timerElapsed = rt ? (rt.repathTimer -= dt) <= 0 : false;
- if (!rt || targetMoved || (agent.repathInterval > 0 && timerElapsed)) {
- const path = nav.findWorldPath(
- tf.position,
- { x: agent.targetX, y: agent.targetY, z: agent.targetZ },
- { radius: agent.radius },
- );
- // A plan that cannot be replaced beats no plan: an agent crossing a
- // link is not standing on the navigable world, so the replan it asks
- // for there has no answer and dropping the route strands it mid-air.
- const keep = path === null && rt !== undefined && rt.reachable
- && rt.index < rt.waypoints.length;
- if (keep && rt) {
- rt.plannedX = agent.targetX;
- rt.plannedY = agent.targetY;
- rt.plannedZ = agent.targetZ;
- rt.repathTimer = agent.repathInterval;
- } else {
- rt = {
- waypoints: path ?? [],
- // Skip the start point to avoid stepping back toward it.
- index: path && path.length > 1 ? 1 : 0,
- plannedX: agent.targetX,
- plannedY: agent.targetY,
- plannedZ: agent.targetZ,
- repathTimer: agent.repathInterval,
- reachable: path !== null,
- velocityA: rt?.velocityA ?? 0,
- velocityB: rt?.velocityB ?? 0,
- };
- }
- runtimes.set(entity, rt);
- }
+ const rt = runtimes.get(entity);
// Keep an unreachable agent's runtime for throttled retry (next target
// change or repath timer) rather than churning it every frame.
- if (!rt.reachable) continue;
+ if (!rt?.reachable) continue;
// A body walks; anything else is moved, and which one an entity is, is
// what it CARRIES. A character has a solver that collides, steps up and
diff --git a/sdk/src/ai/nav/Navigation.ts b/sdk/src/ai/nav/Navigation.ts
index e7dcf079d..a09ccefe3 100644
--- a/sdk/src/ai/nav/Navigation.ts
+++ b/sdk/src/ai/nav/Navigation.ts
@@ -18,6 +18,22 @@ export class Navigation {
/** Where agents may walk, or null until something builds and installs it. */
surface: NavSurface | null = null;
+ /** Soft planning time budget per NavAgentSystem tick, in ms. At least one
+ * query may run; a synchronous query cannot be interrupted. <=0 disables it. */
+ planningBudgetMs = 2;
+ /** Maximum agent plans per tick; <=0 disables the count limit. */
+ maxPlansPerFrame = 16;
+ /** Last agent-planning tick only; excludes movement, avoidance and baking. */
+ readonly planningStats = { completed: 0, pending: 0, elapsedMs: 0 };
+ private pathRevision_ = 0;
+
+ /** Revision used by agents to retire cached plans after an explicit update. */
+ get pathRevision(): number { return this.pathRevision_; }
+
+ /** Replan agents after editing a custom surface or its links/costs in place.
+ * Built-in grid topology and replacing the surface are detected automatically. */
+ invalidatePaths(): void { this.pathRevision_++; }
+
setSurface(surface: NavSurface | null): void {
this.surface = surface;
}
diff --git a/sdk/src/ai/nav/navPlanning.ts b/sdk/src/ai/nav/navPlanning.ts
new file mode 100644
index 000000000..15c3c2bdb
--- /dev/null
+++ b/sdk/src/ai/nav/navPlanning.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+import type { Entity } from '../../types';
+import { Transform } from '../../ecs/component';
+import { NavAgent } from './NavAgent';
+import { NavGrid } from './NavGrid';
+import type { Navigation } from './Navigation';
+import type { NavSurface } from './NavSurface';
+import type { AgentRuntime, NavWorldView } from './NavPlugin';
+
+interface PlanningState {
+ surface: NavSurface | null;
+ revision: number;
+ gridRevision: number;
+ pending: Set<Entity>;
+ invalidated: Set<Entity>;
+ blocked: Set<Entity>;
+}
+const states = new WeakMap<Map<Entity, AgentRuntime>, PlanningState>();
+const now = (): number => typeof performance !== 'undefined' ? performance.now() : Date.now();
+
+/** FIFO requests name entities, not captured targets: queued target edits coalesce
+ * and the eventual query reads the current position, target and body radius. */
+export function planNavigation(
+ world: NavWorldView, nav: Navigation, dt: number,
+ runtimes: Map<Entity, AgentRuntime>, entities: readonly Entity[],
+): ReadonlySet<Entity> {
+ const began = now();
+ let state = states.get(runtimes);
+ if (!state) {
+ state = { surface: null, revision: -1, gridRevision: -1, pending: new Set(), invalidated: new Set(), blocked: new Set() };
+ states.set(runtimes, state);
+ }
+ const gridRevision = nav.surface instanceof NavGrid ? nav.surface.topologyRevision : -1;
+ const changed = state.surface !== nav.surface || state.revision !== nav.pathRevision || state.gridRevision !== gridRevision;
+ state.surface = nav.surface; state.revision = nav.pathRevision; state.gridRevision = gridRevision;
+ const live = new Set(entities);
+ state.blocked.clear();
+ for (const entity of state.pending) if (!live.has(entity)) { state.pending.delete(entity); state.invalidated.delete(entity); }
+ for (const entity of state.invalidated) if (!live.has(entity)) state.invalidated.delete(entity);
+ for (const entity of runtimes.keys()) if (!live.has(entity)) runtimes.delete(entity);
+ for (const entity of entities) {
+ const agent = world.get(entity, NavAgent), rt = runtimes.get(entity);
+ if (!agent.hasTarget) {
+ if (rt || state.pending.has(entity)) state.blocked.add(entity);
+ runtimes.delete(entity); state.pending.delete(entity); state.invalidated.delete(entity);
+ continue;
+ }
+ if (rt) rt.repathTimer -= dt;
+ const radiusChanged = rt !== undefined && (rt.plannedRadius ?? 0) !== agent.radius;
+ const targetMoved = rt !== undefined && (rt.plannedX !== agent.targetX || rt.plannedY !== agent.targetY || rt.plannedZ !== agent.targetZ);
+ if (changed || radiusChanged) state.invalidated.add(entity);
+ if (!rt || changed || targetMoved || radiusChanged
+ || (agent.repathInterval > 0 && rt.repathTimer <= 0)) state.pending.add(entity);
+ // A periodic refresh may keep following its still-valid route. New or
+ // invalidated intent must wait instead of moving toward an old target.
+ if (state.pending.has(entity) && (!rt?.reachable || targetMoved || state.invalidated.has(entity))) state.blocked.add(entity);
+ }
+ let completed = 0;
+ const limit = nav.maxPlansPerFrame > 0 ? Math.max(1, Math.floor(nav.maxPlansPerFrame)) : Infinity;
+ const budget = nav.planningBudgetMs > 0 ? nav.planningBudgetMs : Infinity;
+ try {
+ for (const entity of state.pending) {
+ if (completed >= limit || (completed > 0 && now() - began >= budget)) break;
+ // Remove before querying: a custom query that throws must not pin the
+ // queue's head forever. Its due request is re-added next tick.
+ state.pending.delete(entity);
+ const agent = world.get(entity, NavAgent), tf = world.get(entity, Transform);
+ let rt = runtimes.get(entity);
+ const path = nav.findWorldPath(tf.position,
+ { x: agent.targetX, y: agent.targetY, z: agent.targetZ }, { radius: agent.radius });
+ // Preserve a valid route while crossing an off-mesh link, but never
+ // resurrect one invalidated by a changed surface or obstacle layout.
+ const keep = path === null && !state.invalidated.has(entity) && rt?.reachable
+ && rt.index < rt.waypoints.length;
+ if (keep && rt) {
+ rt.plannedX = agent.targetX; rt.plannedY = agent.targetY; rt.plannedZ = agent.targetZ;
+ rt.plannedRadius = agent.radius; rt.repathTimer = agent.repathInterval;
+ } else {
+ rt = { waypoints: path ?? [], index: path && path.length > 1 ? 1 : 0,
+ plannedX: agent.targetX, plannedY: agent.targetY, plannedZ: agent.targetZ,
+ plannedRadius: agent.radius, repathTimer: agent.repathInterval,
+ reachable: path !== null, velocityA: rt?.velocityA ?? 0, velocityB: rt?.velocityB ?? 0 };
+ }
+ runtimes.set(entity, rt);
+ state.invalidated.delete(entity);
+ state.blocked.delete(entity);
+ completed++;
+ }
+ } finally {
+ nav.planningStats.completed = completed;
+ nav.planningStats.pending = state.pending.size;
+ nav.planningStats.elapsedMs = now() - began;
+ }
+ return state.blocked;
+}
diff --git a/sdk/tests/nav-planning-budget.test.ts b/sdk/tests/nav-planning-budget.test.ts
new file mode 100644
index 000000000..897c9f027
--- /dev/null
+++ b/sdk/tests/nav-planning-budget.test.ts
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: Apache-2.0
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { Transform, type AnyComponentDef, type ComponentData } from '../src/ecs/component';
+import type { Entity } from '../src/types';
+import { CharacterController3D } from '../src/physics3d/Physics3DComponents';
+import { NavAgent } from '../src/ai/nav/NavAgent';
+import { NavGrid } from '../src/ai/nav/NavGrid';
+import { Navigation } from '../src/ai/nav/Navigation';
+import { stepNavigation, type AgentRuntime, type NavWorldView } from '../src/ai/nav/NavPlugin';
+
+class World implements NavWorldView {
+ readonly entities: Entity[] = [];
+ private data = new Map<string, unknown>();
+ spawn(): Entity {
+ const e = (this.entities.length + 1) as Entity;
+ this.entities.push(e);
+ this.set(e, NavAgent, NavAgent.create({ hasTarget: true, targetX: 80 + e, speed: 0, arriveRadius: 0, repathInterval: 0 }));
+ this.set(e, Transform, { position: { x: 0, y: 10, z: 0 } } as ComponentData<typeof Transform>);
+ return e;
+ }
+ getEntitiesWithComponents(): readonly Entity[] { return this.entities; }
+ has<C extends AnyComponentDef>(e: Entity, c: C): boolean { return this.data.has(`${e}:${c._name}`); }
+ get<C extends AnyComponentDef>(e: Entity, c: C): ComponentData<C> { return structuredClone(this.data.get(`${e}:${c._name}`)) as ComponentData<C>; }
+ set<C extends AnyComponentDef>(e: Entity, c: C, data: ComponentData<C>): void { this.data.set(`${e}:${c._name}`, data); }
+ patch<C extends AnyComponentDef>(e: Entity, c: C, data: Partial<ComponentData<C>>): void {
+ this.set(e, c, { ...this.get(e, c), ...data });
+ }
+}
+function setup(count: number) {
+ const world = new World(), nav = new Navigation(), runtimes = new Map<Entity, AgentRuntime>();
+ const entities = Array.from({ length: count }, () => world.spawn());
+ nav.setSurface(new NavGrid({ width: 20, height: 8, cellSize: 10 }));
+ nav.planningBudgetMs = 0;
+ const query = vi.spyOn(nav, 'findWorldPath');
+ const step = () => stepNavigation(world, nav, 0.01, runtimes);
+ return { world, nav, runtimes, entities, query, step };
+}
+afterEach(() => vi.restoreAllMocks());
+
+describe('agent planning budgets', () => {
+ it('serves FIFO requests fairly despite early agents becoming due again and world order changes', () => {
+ const f = setup(5); f.nav.maxPlansPerFrame = 2;
+ for (const e of f.entities) f.world.patch(e, NavAgent, { repathInterval: 0.001 });
+ f.step();
+ expect(f.query.mock.calls.map(c => c[1].x)).toEqual([81, 82]);
+ expect(f.nav.planningStats).toMatchObject({ completed: 2, pending: 3 });
+ f.world.entities.reverse(); f.step();
+ expect(f.query.mock.calls.map(c => c[1].x)).toEqual([81, 82, 83, 84]);
+ f.step();
+ expect(f.query.mock.calls.map(c => c[1].x)).toEqual([81, 82, 83, 84, 85, 82]);
+ expect(new Set(f.query.mock.calls.slice(0, 5).map(c => c[1].x)).size).toBe(5);
+ });
+
+ it('checks time between queries, guarantees progress, and reports an indivisible overrun honestly', () => {
+ const f = setup(5); f.nav.maxPlansPerFrame = 0; f.nav.planningBudgetMs = 2;
+ let clock = 0;
+ vi.spyOn(performance, 'now').mockImplementation(() => clock);
+ f.query.mockImplementation((from, to) => { clock += 1.5; return [{ ...from, z: 0 }, { ...to, z: 0 }]; });
+ f.step();
+ expect(f.nav.planningStats).toEqual({ completed: 2, pending: 3, elapsedMs: 3 });
+ f.query.mockImplementation((from, to) => { clock += 25; return [{ ...from, z: 0 }, { ...to, z: 0 }]; });
+ f.step();
+ expect(f.nav.planningStats).toEqual({ completed: 1, pending: 2, elapsedMs: 25 });
+ });
+
+ it('coalesces queued edits and reads current position, target and radius when served', () => {
+ const f = setup(2); f.nav.maxPlansPerFrame = 1;
+ f.step();
+ const e = f.entities[1]!;
+ f.world.patch(e, NavAgent, { targetX: 120, targetY: 30, targetZ: 7, radius: 2 });
+ f.world.patch(e, Transform, { position: { x: 15, y: 20, z: 3 } });
+ f.step();
+ expect(f.query.mock.calls[1]).toEqual([{ x: 15, y: 20, z: 3 }, { x: 120, y: 30, z: 7 }, { radius: 2 }]);
+ expect(f.runtimes.get(e)).toMatchObject({ plannedX: 120, plannedY: 30, plannedZ: 7, plannedRadius: 2 });
+ });
+
+ it('stops deferred character steering while preserving gravity, and drops stopped or removed requests', () => {
+ const f = setup(3); f.nav.maxPlansPerFrame = 1;
+ const e = f.entities[1]!;
+ f.world.set(e, CharacterController3D, { enabled: true, velocity: { x: 10, y: -30, z: 20 } } as ComponentData<typeof CharacterController3D>);
+ f.step();
+ expect(f.world.get(e, CharacterController3D).velocity).toEqual({ x: 0, y: -30, z: 0 });
+ f.world.patch(e, NavAgent, { hasTarget: false });
+ f.world.entities.splice(f.world.entities.indexOf(f.entities[2]!), 1);
+ f.step();
+ expect(f.query).toHaveBeenCalledTimes(1);
+ expect(f.nav.planningStats.pending).toBe(0);
+ expect(f.runtimes.has(e)).toBe(false);
+ });
+
+ it('keeps valid cached routes moving while periodic refresh requests wait', () => {
+ const f = setup(3); f.nav.maxPlansPerFrame = 1;
+ for (let i = 0; i < 3; i++) f.step();
+ for (const e of f.entities) {
+ f.world.patch(e, NavAgent, { speed: 10, repathInterval: 0.001 });
+ }
+ const before = f.entities.map(e => ({ ...f.world.get(e, Transform).position }));
+ f.step();
+ expect(f.nav.planningStats).toMatchObject({ completed: 1, pending: 2 });
+ for (const [i, e] of f.entities.entries()) expect(f.world.get(e, Transform).position.x).toBeGreaterThan(before[i]!.x);
+ // A changed target is not a periodic refresh: it waits for a fresh plan.
+ const e = f.entities[2]!;
+ const held = { ...f.world.get(e, Transform).position };
+ f.world.patch(e, NavAgent, { targetX: -50 });
+ f.step();
+ expect(f.world.get(e, Transform).position).toEqual(held);
+ });
+
+ it('retires stale grid routes, even with periodic replanning disabled, and waits safely for its turn', () => {
+ const f = setup(2); f.nav.maxPlansPerFrame = 1;
+ const e = f.entities[0]!; f.world.patch(e, NavAgent, { speed: 10 });
+ f.step();
+ const before = { ...f.world.get(e, Transform).position };
+ const grid = f.nav.surface as NavGrid;
+ for (let y = 0; y < grid.height; y++) grid.setWalkable(5, y, false);
+ f.step(); // Entity 2 was already queued; entity 1 joins behind it.
+ expect(f.world.get(e, Transform).position).toEqual(before);
+ expect(f.nav.planningStats.pending).toBe(1);
+ f.step();
+ expect(f.query).toHaveBeenCalledTimes(3);
+ expect(f.runtimes.get(e)?.waypoints.at(-1)?.x).toBeLessThan(50);
+ expect(f.nav.planningStats.pending).toBe(0);
+ });
+
+ it('does not keep an old narrow route after body radius changes or explicit invalidation', () => {
+ const f = setup(1), e = f.entities[0]!;
+ f.world.patch(e, NavAgent, { speed: 10 });
+ f.step();
+ const before = { ...f.world.get(e, Transform).position };
+ f.world.patch(e, NavAgent, { radius: 2 });
+ f.query.mockReturnValueOnce(null);
+ f.step();
+ expect(f.world.get(e, Transform).position).toEqual(before);
+ expect(f.runtimes.get(e)?.reachable).toBe(false);
+ f.world.patch(e, NavAgent, { radius: 0 }); f.step();
+ f.query.mockReturnValue(null); f.nav.invalidatePaths(); f.step();
+ expect(f.runtimes.get(e)?.reachable).toBe(false);
+ });
+
+ it('cleans runtimes after component removal, supports disabling budgets, and leaves direct queries synchronous', () => {
+ const f = setup(20); f.nav.maxPlansPerFrame = 0;
+ f.step();
+ expect(f.nav.planningStats).toMatchObject({ completed: 20, pending: 0 });
+ f.world.entities.length = 0; f.step();
+ expect(f.runtimes.size).toBe(0);
+ f.nav.maxPlansPerFrame = 1; f.nav.planningBudgetMs = 0.001;
+ for (let i = 0; i < 20; i++) expect(f.nav.findWorldPath({ x: 0, y: 10 }, { x: 80, y: 10 })).not.toBeNull();
+ expect(f.query).toHaveBeenCalledTimes(40);
+ });
+
+ it('clears failed or cancelled navigation steering, then relinquishes idle characters to other controls', () => {
+ const f = setup(1), e = f.entities[0]!;
+ f.world.set(e, CharacterController3D, { enabled: true, velocity: { x: 10, y: -30, z: 20 } } as ComponentData<typeof CharacterController3D>);
+ f.world.patch(e, NavAgent, { speed: 10 }); f.step();
+ f.query.mockReturnValueOnce(null); f.nav.invalidatePaths(); f.step();
+ expect(f.world.get(e, CharacterController3D).velocity).toEqual({ x: 0, y: -30, z: 0 });
+ f.world.patch(e, NavAgent, { hasTarget: false });
+ f.world.patch(e, CharacterController3D, { velocity: { x: 8, y: -30, z: 0 } }); f.step();
+ expect(f.world.get(e, CharacterController3D).velocity.x).toBe(0);
+ f.world.patch(e, CharacterController3D, { velocity: { x: 15, y: -30, z: 0 } }); f.step();
+ expect(f.world.get(e, CharacterController3D).velocity.x).toBe(15);
+ });
+
+ it('removes a throwing query from the head so other queued agents can make progress', () => {
+ const f = setup(2); f.nav.maxPlansPerFrame = 1;
+ f.query.mockImplementationOnce(() => { throw Error('custom query failed'); });
+ expect(f.step).toThrow('custom query failed');
+ f.step();
+ expect(f.query.mock.calls.map(c => c[1].x)).toEqual([81, 82]);
+ expect(f.nav.planningStats).toMatchObject({ completed: 1, pending: 1 });
+ f.step();
+ expect(f.query.mock.calls.at(-1)?.[1].x).toBe(81);
+ });
+});
diff --git a/sdk/tests/nav-step.test.ts b/sdk/tests/nav-step.test.ts
index 7cc62db4e..050a7bc82 100644
--- a/sdk/tests/nav-step.test.ts
+++ b/sdk/tests/nav-step.test.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { Transform } from '../src/ecs/component';
import type { Entity } from '../src/types';
import { NavGrid } from '../src/ai/nav/NavGrid';
@@ -311,11 +311,11 @@ describe('an agent with a body', () => {
/**
* A replan is asked from wherever the agent has got to, and that is not always
- * somewhere the navigable world has an answer for — halfway across a link, or
- * standing where a door has just shut.
+ * somewhere the navigable world has an answer for — halfway across a link.
+ * A replaced surface, however, must not resurrect an invalidated old route.
*/
describe('a replan that finds nothing', () => {
- it('leaves the agent walking the route it already had', () => {
+ it('stops instead of reviving a route invalidated by a replacement surface', () => {
const world = new FakeWorld();
const entity = world.spawnAgent(0, 0, {
speed: 100, arriveRadius: 0, repathInterval: 0.1, hasTarget: true, targetX: 80, targetY: 0,
@@ -329,6 +329,20 @@ describe('a replan that finds nothing', () => {
// Nowhere to plan from any more, and the timer is up.
nav.setSurface(new NavGrid({ width: 10, height: 3, cellSize: 10, walkable: new Uint8Array(30) }));
stepNavigation(world, nav, 0.2, runtimes);
+ expect(world.pos(entity).x).toBe(after);
+ expect(world.agent(entity).arrived).toBe(false);
+ });
+
+ it('keeps a route when a transient query fails on the unchanged surface', () => {
+ const world = new FakeWorld();
+ const entity = world.spawnAgent(0, 0, {
+ speed: 100, arriveRadius: 0, repathInterval: 0.1, hasTarget: true, targetX: 80, targetY: 0,
+ });
+ const nav = openNav(), runtimes = new Map<Entity, AgentRuntime>();
+ stepNavigation(world, nav, 0.05, runtimes);
+ const after = world.pos(entity).x;
+ vi.spyOn(nav, 'findWorldPath').mockReturnValue(null);
+ stepNavigation(world, nav, 0.2, runtimes);
expect(world.pos(entity).x).toBeGreaterThan(after);
});
diff --git a/tools/fixtures/navigation-build-corpus.ts b/tools/fixtures/navigation-build-corpus.ts
index 9bb50b816..c42bda712 100644
--- a/tools/fixtures/navigation-build-corpus.ts
+++ b/tools/fixtures/navigation-build-corpus.ts
@@ -10,7 +10,7 @@ const percentile = (a: number[], q: number) => [...a].sort((x, y) => x - y)[Math
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[] {
+export 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({
diff --git a/tools/fixtures/navigation-planning-corpus.ts b/tools/fixtures/navigation-planning-corpus.ts
new file mode 100644
index 000000000..3944cc32f
--- /dev/null
+++ b/tools/fixtures/navigation-planning-corpus.ts
@@ -0,0 +1,101 @@
+// SPDX-License-Identifier: Apache-2.0
+import { NavGrid } from '../../sdk/src/ai/nav/NavGrid';
+import { Navigation } from '../../sdk/src/ai/nav/Navigation';
+import { NavAgent } from '../../sdk/src/ai/nav/NavAgent';
+import { stepNavigation, type AgentRuntime, type NavWorldView } from '../../sdk/src/ai/nav/NavPlugin';
+import { applyObstaclesToGrid } from '../../sdk/src/ai/nav/navObstacles';
+import type { AnyComponentDef, ComponentData } from '../../sdk/src/ecs/component';
+import type { Entity } from '../../sdk/src/types';
+import type { NavPoint, NavQueryOptions } from '../../sdk/src/ai/nav/NavSurface';
+import { obstacles } from './navigation-build-corpus';
+
+const frame = () => new Promise<number>(resolve => requestAnimationFrame(() => resolve(performance.now())));
+const p95 = (a: number[]) => [...a].sort((x, y) => x - y)[Math.ceil(a.length * 0.95) - 1]!;
+class World implements NavWorldView {
+ readonly ids: Entity[] = [];
+ private data = new Map<string, unknown>();
+ constructor(span: number) {
+ for (let i = 0; i < 64; i++) {
+ const id = (i + 1) as Entity;
+ this.ids.push(id);
+ const a = span * (0.15 + 0.7 * (i % 16) / 15);
+ const b = span * (0.15 + 0.7 * ((i * 7) % 16) / 15);
+ this.data.set(`${id}:Transform`, { position: { x: span * 0.2, y: a, z: 0 } });
+ this.data.set(`${id}:NavAgent`, NavAgent.create({ speed: 0, radius: 5, arriveRadius: 0,
+ repathInterval: 0, hasTarget: true, targetX: span * 0.8, targetY: b }));
+ }
+ }
+ getEntitiesWithComponents(): readonly Entity[] { return this.ids; }
+ has<C extends AnyComponentDef>(id: Entity, type: C): boolean { return this.data.has(`${id}:${type._name}`); }
+ get<C extends AnyComponentDef>(id: Entity, type: C): ComponentData<C> { return this.data.get(`${id}:${type._name}`) as ComponentData<C>; }
+ set<C extends AnyComponentDef>(id: Entity, type: C, value: ComponentData<C>): void { this.data.set(`${id}:${type._name}`, value); }
+}
+class ObservedNavigation extends Navigation {
+ readonly shapes: object[] = [];
+ readonly queryTimesMs: number[] = [];
+ override findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions) {
+ const began = performance.now();
+ const path = super.findWorldPath(from, to, opts);
+ this.queryTimesMs.push(performance.now() - began);
+ // Keep every waypoint, not just the first agent's endpoint. Compare all
+ // 64 routes across the two budget settings after each door/building edit.
+ this.shapes.push({ from: { ...from }, to: { ...to }, radius: opts?.radius,
+ path });
+ return path;
+ }
+}
+
+export async function runNavigationPlanningCorpus() {
+ const records = [];
+ for (const size of [32, 64, 128]) {
+ const modes = [];
+ for (const mode of ['unlimited', 'budgeted'] as const) {
+ const samples = [];
+ for (let iteration = -3; iteration < 16; iteration++) {
+ const span = size * 10, closed = iteration % 2 === 0, placed = iteration % 3 === 0;
+ const world = new World(span), nav = new ObservedNavigation();
+ const runtimes = new Map<Entity, AgentRuntime>();
+ nav.setSurface(new NavGrid({ width: size, height: size, cellSize: 10 }));
+ if (mode === 'unlimited') { nav.planningBudgetMs = 0; nav.maxPlansPerFrame = 0; }
+ let previous = await frame();
+ const began = previous, buildStart = performance.now();
+ applyObstaclesToGrid(nav.surface as NavGrid, obstacles(size, closed, placed).map(box => ({
+ ...box, center: { x: box.center.x, y: box.center.z, z: 0 },
+ halfExtents: { x: box.halfExtents.x, y: box.halfExtents.z, z: 20 },
+ })));
+ const buildMs = performance.now() - buildStart;
+ const cpuMs = [], planningMs = [], frameGapsMs = [], completed = [], pending = [];
+ do {
+ const start = performance.now();
+ stepNavigation(world, nav, 1 / 60, runtimes);
+ const elapsed = performance.now() - start;
+ cpuMs.push(elapsed + (cpuMs.length === 0 ? buildMs : 0));
+ planningMs.push(nav.planningStats.elapsedMs);
+ completed.push(nav.planningStats.completed); pending.push(nav.planningStats.pending);
+ const next = await frame();
+ const gap = next - previous;
+ if (gap + 1 < cpuMs.at(-1)!) throw Error('Frame gap excludes measured CPU work');
+ frameGapsMs.push(gap); previous = next;
+ if (cpuMs.length > 64 || (nav.planningStats.pending > 0 && nav.planningStats.completed === 0)) throw Error('Planning queue did not make progress');
+ } while (nav.planningStats.pending > 0);
+ if (nav.shapes.length !== 64) throw Error('Did not query all 64 agents');
+ if (mode === 'budgeted' && completed.some(n => n > nav.maxPlansPerFrame)) throw Error('Count budget exceeded');
+ if (iteration >= 0) samples.push({ closed, placed, buildMs, cpuMs, planningMs, frameGapsMs, completed, pending,
+ latencyMs: previous - began, queryTimesMs: nav.queryTimesMs, shapes: nav.shapes });
+ }
+ modes.push({ mode, samples,
+ peakStepP95Ms: p95(samples.map(s => Math.max(...s.cpuMs))),
+ peakPlanningP95Ms: p95(samples.map(s => Math.max(...s.planningMs))),
+ peakQueryP95Ms: p95(samples.map(s => Math.max(...s.queryTimesMs))),
+ peakFrameGapP95Ms: p95(samples.map(s => Math.max(...s.frameGapsMs))),
+ totalCpuP95Ms: p95(samples.map(s => s.cpuMs.reduce((a, b) => a + b, 0))),
+ latencyP95Ms: p95(samples.map(s => s.latencyMs)),
+ batchesOverFrameBudget: samples.filter(s => Math.max(...s.cpuMs) > 1000 / 60).length });
+ }
+ for (let i = 0; i < 16; i++) {
+ if (JSON.stringify(modes[0]!.samples[i]!.shapes) !== JSON.stringify(modes[1]!.samples[i]!.shapes)) throw Error('Budget settings changed route shapes');
+ }
+ records.push({ size, agents: 64, planningBudgetMs: 2, maxPlansPerFrame: 16, modes });
+ }
+ return { warmup: 3, samples: 16, frameBudgetMs: 1000 / 60, records };
+}
diff --git a/tools/navigation-planning-benchmark.mjs b/tools/navigation-planning-benchmark.mjs
new file mode 100644
index 000000000..1b9bf8a24
--- /dev/null
+++ b/tools/navigation-planning-benchmark.mjs
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: Apache-2.0
+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 bundle = await build({ entryPoints: [path.join(root, 'tools/fixtures/navigation-planning-corpus.ts')],
+ bundle: true, platform: 'browser', format: 'iife', globalName: 'NavPlanningCorpus', write: false });
+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.NavPlanningCorpus.runNavigationPlanningCorpus());
+ const report = { source, bundleSha256: createHash('sha256').update(code).digest('hex'), recordedAt: new Date().toISOString(),
+ sourceDirtyFiles: execFileSync('git', ['status', '--porcelain=1', '--untracked-files=all', '--', 'sdk/src/ai/nav'], { cwd: root, encoding: 'utf8', windowsHide: true }).split('\n').filter(Boolean),
+ platform: process.platform, cpu: os.cpus()[0]?.model, browser: browser.version(),
+ scope: 'Same current agent system and building maps, unlimited versus default planning budgets. Includes grid obstacle marking, agent planning, movement and avoidance over an in-memory World. Zero movement speed keeps all query inputs identical. Genuine headless Chromium rAF callback gaps; no rendering, physics, editor or full game frame. Budget is soft between indivisible synchronous queries; latency and total CPU are reported separately.',
+ ...result };
+ const destination = path.resolve(root, process.argv[2] ?? 'output/navigation-planning.json');
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
+ fs.writeFileSync(destination, JSON.stringify(report, null, 2));
+ for (const r of result.records) for (const m of r.modes) console.log(`${r.size} ${m.mode}: peak-step-p95=${m.peakStepP95Ms.toFixed(2)}ms peak-plan-p95=${m.peakPlanningP95Ms.toFixed(2)}ms total-cpu-p95=${m.totalCpuP95Ms.toFixed(2)}ms batch-latency-p95=${m.latencyP95Ms.toFixed(2)}ms over-budget=${m.batchesOverFrameBudget}/16`);
+ console.log(destination);
+} finally { await browser.close(); }
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 277cdb84e..30c79529d 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -32,6 +32,10 @@ export const NOTED = {
{ note: 'Text-input length limits preserve complete supplementary characters.' },
'fix(ui): bind field rendering to the active editing owner':
{ note: 'Text fields read only the editing surface they actually own.' },
+ 'feat(nav): budget agent replans fairly across frames':
+ { note: 'Agent replans share a fair per-frame budget.' },
+ 'feat(inspector): show sampled navigation planning queues':
+ { note: 'Agent replans share a fair per-frame budget.' },
'feat(editor): inspect live agent route failures on demand':
{ note: "Inspect a live agent's current route on demand." },
'feat(inspector): inspect live agent route failures on demand':
diff --git a/tools/verify-navigation-inspector.mjs b/tools/verify-navigation-inspector.mjs
index a6ca2b601..c03227eb0 100644
--- a/tools/verify-navigation-inspector.mjs
+++ b/tools/verify-navigation-inspector.mjs
@@ -55,6 +55,7 @@ addPlugin({name:'navigation-inspection-fixture',build(app){
const result = JSON.parse(line.slice('[eval] '.length));
const expected = { complete: 'Route reaches the resolved destination', disconnected: 'Start and target are disconnected', 'insufficient-clearance': 'this agent cannot fit', 'no-target': 'No active destination' }[state];
assert(result.status.includes(expected), JSON.stringify(result));
+ if (state !== 'no-target') assert(result.status.includes('Last planning tick:'), 'Missing live planning queue counters');
assert(fs.existsSync(path.join(out, state + '.png')), 'Missing editor screenshot');
records.push(result);
fs.writeFileSync(path.join(out, 'observations.json'), JSON.stringify({ records }, null, 2));