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): both surfaces hand back the same shape of route
esengine3f805157a481
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a89db6bfe..d3584d37d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -170,6 +170,21 @@ published separately; it ships inside the editor.than the box around them. Nothing waits for the solver any more: the geometry isin the scene from the first frame.+- **A route over a grid is pulled taut, like a route over a mesh.** A\* answers in+ steps of one cell, so crossing open ground came back as a staircase and an agent+ walking it wobbled down every diagonal. `shortenPath` keeps only the cells where+ the route has to turn, and takes a shortcut only along a line the search itself+ could have walked: every cell it touches fits the body, and a diagonal needs both+ of its shared orthogonals. Both shapes of `NavSurface` now hand back the same+ shape of route, so moving a game from a tilemap to geometry does not change how+ its agents move.++- **A scene has one navigable world.** Two `NavVolume`s were baked a frame apart+ with the last one silently winning, which made which mesh a scene got an accident+ of iteration order. The first is baked and any others are named in the log: a box+ decides where to LOOK, walkability comes from the geometry inside it, and one box+ big enough to hold the level costs voxels and never costs correctness.+- **Navigation plans and walks in three dimensions.** Paths, `NavAgent`(`targetZ`) and the kinematic follower carry all three axes — a slope is longerthan its shadow, and spending a frame's budget on the shadow walked agents uphilldiff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdxindex 799458abb..c7ecd1120 100644--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx@@ -45,6 +45,13 @@ To derive a grid from a painted tilemap instead of hand-authoring the mask, use`navGridFromTiles`. `grid.setWalkable(x, y, false)` closes a cell at any time — adoor shuts, a tower goes up — and the next plan routes around it.+A route over a grid is **string-pulled** before it is handed back: A\* answers in+steps of one cell, and only the cells where the route actually has to turn survive.+A shortcut is taken only along a line the search itself could have walked — every+cell it touches fits the body, and a diagonal needs both of its shared orthogonals+— so a smoothed route is exactly as legal as the staircase it replaced, and the+same shape of route a mesh gives.+### A mesh for a 3D sceneA 3D scene has geometry rather than a tile mask, so its surface is **baked** from@@ -67,6 +74,13 @@ of that size could stand on, and turns what is left into convex polygons. Everycolumn of the world keeps **all** of its floors, so a bridge and the road under itare two places and a route can use either.+<Aside type="note">+ **One volume per scene.** A scene has one navigable world, so the first volume is+ the one that is baked and any others are named in the log. What a box decides is+ where to *look*; walkability comes from the geometry inside it, so one box big+ enough to hold the level costs voxels and never costs correctness.+</Aside>+<Aside type="note">**Static bodies only.** A crate that is about to be pushed is not floor, and amesh baked over one would describe the world for exactly as long as nobodydiff --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 6c0162eae..f80ad5740 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@@ -43,6 +43,11 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {实心瓦片视作阻挡)或 `navGridFromTiles`。`grid.setWalkable(x, y, false)` 随时可以关掉一格——门关上了、塔造起来了——下一次规划就会绕开它。+格子上的路线在交出去之前会先**拉直**:A\* 是一格一步作答的,只有路线真正需要转弯的那些格+留了下来。抄近道只走搜索本身能走的线——线经过的每一格都容得下这个身体,而对角线要求它+两侧的正交格都通——所以拉直后的路线和它替换掉的那条阶梯一样合法,并且和网格给出的是同一+种形状的路线。+### 3D 场景的网格3D 场景有的是几何而不是瓦片掩码,所以它的 surface 是从**它本来就在碰撞的那些刚体**上@@ -62,6 +67,12 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {烘焙把盒子里的碰撞三角面体素化,留下这个尺寸的 agent 站得住的那些面,再把剩下的变成凸多边形。世界的每一列都保留了它**全部**的楼层,所以桥和桥下的路是两个地方,路线两个都能用。+<Aside type="note">+ **一个场景一个体积。**一个场景只有一个可走世界,所以被烘焙的是第一个体积,其余的会在日志里+ 被点名。盒子决定的是**往哪看**;可走性来自盒子里的几何,所以用一个大到装得下整个关卡的盒子+ 只是多花体素,不会损失正确性。+</Aside>+<Aside type="note">**只烘焙静态刚体。**一个马上要被推走的箱子不是地板,在它上面烘出来的网格只在没人碰它的这段时间里成立。任何应该被踩上去(或被绕开)的东西,都给它一个 body type 为 **Static**diff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.tsindex d953a9604..00410c5fb 100644--- a/sdk/src/ai/nav/NavGrid.ts+++ b/sdk/src/ai/nav/NavGrid.ts@@ -18,7 +18,7 @@import type { Vec3 } from '../../types';import type { NavPoint, NavQueryOptions, NavSurface, NavSurfaceSink } from './NavSurface';-import { findPath, pathToWorld } from './pathfind';+import { findPath, pathToWorld, shortenPath } 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. */@@ -152,10 +152,9 @@ export class NavGrid implements NavSurface {findWorldPath(from: NavPoint, to: NavPoint, opts?: NavQueryOptions): Vec3[] | null {const radius = opts?.radius ?? 0;- const cells = findPath(this, this.worldToCell(from), this.worldToCell(to), {- clearance: radius > 0 ? Math.ceil(radius / this.cellSize) : 0,- });- return cells ? pathToWorld(this, cells) : null;+ const clearance = radius > 0 ? Math.ceil(radius / this.cellSize) : 0;+ const cells = findPath(this, this.worldToCell(from), this.worldToCell(to), { clearance });+ return cells ? pathToWorld(this, shortenPath(this, cells, clearance)) : null;}/**diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.tsindex 1ec157eca..be18bab80 100644--- a/sdk/src/ai/nav/NavPlugin.ts+++ b/sdk/src/ai/nav/NavPlugin.ts@@ -48,7 +48,10 @@ export interface AgentRuntime {export type NavGeometryProvider = (min: Vec3, max: Vec3, layers: number) => NavGeometry;/**- * Bake the first NavVolume that has not been baked yet, and install its mesh.+ * Bake the scene's NavVolume and install the mesh. A scene has ONE navigable+ * world, so the first volume is baked and the rest are named in the log: a box+ * decides where to LOOK, walkability comes from the geometry in it, and one box+ * big enough for the level costs voxels rather than correctness.*/export function bakeVolumes(world: NavWorldView,@@ -57,7 +60,8 @@ export function bakeVolumes(baked: Set<Entity>,): void {if (!geometry) return;- for (const entity of world.getEntitiesWithComponents([NavVolume, Transform])) {+ const volumes = world.getEntitiesWithComponents([NavVolume, Transform]);+ for (const entity of volumes) {if (baked.has(entity)) continue;const volume = world.get(entity, NavVolume);// The volume is placed in the same space the geometry is collected in.@@ -87,9 +91,12 @@ export function bakeVolumes(+ `${geo.bodyCount} static bodies — check that it covers the floor, that the`+ ' floor is a STATIC RigidBody3D, and that `layers` includes it');}- // One mesh is installed at a time, so a scene with two volumes would have- // the last one win. Bake one per frame and let the newest be the active- // one rather than silently merging boxes that may not touch.+ if (volumes.length > 1) {+ for (const other of volumes) baked.add(other);+ log.warn('nav', `${volumes.length} NavVolumes in this scene — only the first is`+ + ' baked, since a scene has one navigable world; make one box big enough'+ + ' to hold the level instead');+ }return;}}diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.tsindex d3ac83cc3..e9fc30bc6 100644--- a/sdk/src/ai/nav/pathfind.ts+++ b/sdk/src/ai/nav/pathfind.ts@@ -108,6 +108,47 @@ export function findPath(return null;}+/**+ * Drop the waypoints a straight line can skip, leaving only the cells a route has+ * to turn at — what the funnel does over a mesh. A shortcut is taken only along a+ * line the search itself could have walked: every cell it touches fits the body,+ * and a diagonal needs both of its shared orthogonals.+ */+export function shortenPath(grid: NavGrid, path: Cell[], clearance = 0): Cell[] {+ if (path.length <= 2) return path;+ const out: Cell[] = [path[0]!];+ let anchor = path[0]!;+ for (let i = 2; i < path.length; i++) {+ if (clearLine(grid, anchor, path[i]!, clearance)) continue;+ anchor = path[i - 1]!;+ out.push(anchor);+ }+ out.push(path[path.length - 1]!);+ return out;+}++/** Whether every cell between two cells fits the body, walking the same steps. */+function clearLine(grid: NavGrid, from: Cell, to: Cell, clearance: number): boolean {+ let x = from.x;+ let y = from.y;+ const dx = Math.abs(to.x - x);+ const dy = Math.abs(to.y - y);+ const sx = x < to.x ? 1 : -1;+ const sy = y < to.y ? 1 : -1;+ let err = dx - dy;+ for (;;) {+ if (!fits(grid, x, y, clearance)) return false;+ if (x === to.x && y === to.y) return true;+ const e2 = err * 2;+ const stepX = e2 > -dy;+ const stepY = e2 < dx;+ if (stepX && stepY+ && (!fits(grid, x + sx, y, clearance) || !fits(grid, x, y + sy, clearance))) return false;+ if (stepX) { err -= dy; x += sx; }+ if (stepY) { err += dx; y += sy; }+ }+}+/** Convert a cell path to world-space waypoints (cell centres, on the grid's plane). */export function pathToWorld(grid: NavGrid, path: Cell[]): Vec3[] {return path.map(c => grid.cellToWorld(c.x, c.y));diff --git a/sdk/tests/nav-pathfind.test.ts b/sdk/tests/nav-pathfind.test.tsindex 26c7d4e9a..d29b99d40 100644--- a/sdk/tests/nav-pathfind.test.ts+++ b/sdk/tests/nav-pathfind.test.ts@@ -2,7 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { describe, it, expect } from 'vitest';import { NavGrid, type Cell } from '../src/ai/nav/NavGrid';-import { findPath, pathToWorld } from '../src/ai/nav/pathfind';+import { findPath, pathToWorld, shortenPath } from '../src/ai/nav/pathfind';/*** Build a grid from an ASCII map. '#' = blocked, anything else walkable.@@ -151,3 +151,103 @@ describe('findPath', () => {]);});});++/**+ * A route over cells comes back as a staircase; a route over polygons comes back+ * taut. Both are `NavSurface.findWorldPath`, so a game moving from a tilemap to+ * geometry should not find its agents walking differently.+ */+describe('shortenPath', () => {+ it('crosses open ground in one straight line', () => {+ const grid = new NavGrid({ width: 10, height: 10, cellSize: 10 });+ const path = findPath(grid, { x: 0, y: 0 }, { x: 9, y: 9 })!;+ expect(path.length).toBe(10); // the staircase A* actually walks+ expect(shortenPath(grid, path)).toEqual([{ x: 0, y: 0 }, { x: 9, y: 9 }]);+ });++ it('keeps the turn it has to make, and no others', () => {+ // . . . . .+ // S # # # G ← the wall forces one way round+ // . . . . .+ const grid = new NavGrid({ width: 5, height: 3, cellSize: 10 });+ for (let x = 1; x <= 3; x++) grid.setWalkable(x, 1, false);+ const raw = findPath(grid, { x: 0, y: 1 }, { x: 4, y: 1 })!;+ const short = shortenPath(grid, raw);+ expect(short.length).toBeLessThan(raw.length);+ expect(short.length).toBeGreaterThan(2);+ expect(short[0]).toEqual({ x: 0, y: 1 });+ expect(short[short.length - 1]).toEqual({ x: 4, y: 1 });+ });++ // Swept over scattered walls rather than one drawing: which shortcuts a greedy+ // walk even gets to CONSIDER depends on the shape it is cutting, and one+ // picture leaves most of the rule untested.+ it('never cuts a line the agent could not walk', () => {+ let seed = 12345;+ const next = (): number => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;+ let shortened = 0;+ for (let trial = 0; trial < 200; trial++) {+ const grid = new NavGrid({ width: 12, height: 12, cellSize: 10 });+ for (let i = 0; i < 24; i++) {+ grid.setWalkable(Math.floor(next() * 12), Math.floor(next() * 12), false);+ }+ const raw = findPath(grid, { x: 0, y: 0 }, { x: 11, y: 11 });+ if (!raw) continue;+ const short = shortenPath(grid, raw);+ expect(everySegmentWalkable(grid, short)).toBe(true);+ expect(short.length).toBeLessThanOrEqual(raw.length);+ if (short.length < raw.length) shortened++;+ }+ // A sweep where nothing was ever shortened would prove nothing at all.+ expect(shortened).toBeGreaterThan(50);+ });++ // A diagonal past a blocked corner is a squeeze the search itself refuses; a+ // shortcut that took it would plan the agent through the corner of a wall.+ it('will not cut a diagonal past a blocked corner', () => {+ const grid = new NavGrid({ width: 2, height: 2, cellSize: 10 });+ grid.setWalkable(1, 0, false);+ const raw = findPath(grid, { x: 0, y: 0 }, { x: 1, y: 1 })!;+ expect(shortenPath(grid, raw)).toEqual(raw);+ });++ it('will not cut a line a body that wide does not fit down', () => {+ // A one-cell gap in a wall: a point fits through, a body does not.+ const grid = new NavGrid({ width: 7, height: 7, cellSize: 10 });+ for (let y = 0; y < 7; y++) if (y !== 3) grid.setWalkable(3, y, false);+ const raw = findPath(grid, { x: 0, y: 3 }, { x: 6, y: 3 })!;+ expect(shortenPath(grid, raw, 0)).toEqual([{ x: 0, y: 3 }, { x: 6, y: 3 }]);+ // With a body two cells wide nothing on that line fits, so nothing is cut.+ const wide = shortenPath(grid, raw, 2);+ expect(wide.length).toBeGreaterThan(2);+ });++ it('leaves a path with nothing to drop alone', () => {+ const grid = new NavGrid({ width: 3, height: 1, cellSize: 10 });+ expect(shortenPath(grid, [{ x: 0, y: 0 }])).toEqual([{ x: 0, y: 0 }]);+ expect(shortenPath(grid, [{ x: 0, y: 0 }, { x: 1, y: 0 }]))+ .toEqual([{ x: 0, y: 0 }, { x: 1, y: 0 }]);+ });+});++/** Whether every cell the route passes between its waypoints is walkable. */+function everySegmentWalkable(grid: NavGrid, path: Cell[]): boolean {+ for (let i = 1; i < path.length; i++) {+ let x = path[i - 1]!.x;+ let y = path[i - 1]!.y;+ const to = path[i]!;+ const dx = Math.abs(to.x - x);+ const dy = Math.abs(to.y - y);+ const sx = x < to.x ? 1 : -1;+ const sy = y < to.y ? 1 : -1;+ let err = dx - dy;+ for (;;) {+ if (!grid.isWalkable(x, y)) return false;+ if (x === to.x && y === to.y) break;+ const e2 = err * 2;+ if (e2 > -dy) { err -= dy; x += sx; }+ if (e2 < dx) { err += dx; y += sy; }+ }+ }+ return true;+}diff --git a/sdk/tests/nav-volume-bake.test.ts b/sdk/tests/nav-volume-bake.test.tsindex 39ae912d7..a637c7200 100644--- a/sdk/tests/nav-volume-bake.test.ts+++ b/sdk/tests/nav-volume-bake.test.ts@@ -100,6 +100,22 @@ describe('bakeVolumes', () => {expect((nav.surface as NavMesh).findPoly({ x: 395, y: 0, z: 0 })).toBe(-1);});+ // A scene has one navigable world, and which volume supplies it may not be an+ // accident of iteration order.+ it('bakes the first volume and says the others were not', () => {+ const w = new VolumeWorld();+ spawnVolume(w);+ spawnVolume(w, { halfExtents: { x: 100, y: 100, z: 100 } });+ const geometry = vi.fn(floorGeometry());+ const baked = new Set<number>();+ const nav = new Navigation();+ bakeVolumes(w as never, nav, geometry, baked as never);+ bakeVolumes(w as never, nav, geometry, baked as never);+ expect(geometry).toHaveBeenCalledTimes(1);+ // The one that was baked is the first, not whichever came last.+ expect((nav.surface as NavMesh).findPoly({ x: 300, y: 0, z: 300 })).toBeGreaterThanOrEqual(0);+ });+it('asks only for the layers the volume names', () => {const w = new VolumeWorld();spawnVolume(w, { layers: 0b1010 });