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): the grid knows which plane it lies in, and how high its ground is

esengine2302385f6b8b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1cd49ff2a..b816f6805 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,17 @@ published separately; it ships inside the editor.
### Fixed
+- **Navigation plans and walks in three dimensions.** `NavGrid` now knows which
+ world plane its cells lie in — `xy` (a flat scene, the default and unchanged) or
+ `xz`, the ground of a spatial one, where each cell also carries the height of
+ the ground there. A* honours a `stepHeight`, so a kerb is a route and a ledge of
+ the same width is not, and a route that ends up cut in two reports no path
+ rather than one that walks through a wall. Paths, `NavAgent` (`targetZ`) and the
+ kinematic follower are three-dimensional throughout — a slope is longer than its
+ shadow, and spending a frame's budget on the shadow walked agents uphill faster
+ than along the flat. One grid class rather than two: a second would be this one
+ with two axes renamed.
+
- **AI sensing is three-dimensional.** A `Perceiver`'s range came from x and y,
its cone from `atan2` in the same plane, and its facing from the Z half of a
quaternion — so a guard saw through floors, and any rotation but a flat one
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 029f4f092..aee28d5cd 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1967,6 +1967,11 @@
"type": "number",
"default": "0"
},
+ {
+ "key": "targetZ",
+ "type": "number",
+ "default": "0"
+ },
{
"key": "arrived",
"type": "boolean",
@@ -1980,7 +1985,8 @@
"arriveRadius",
"repathInterval",
"targetX",
- "targetY"
+ "targetY",
+ "targetZ"
]
},
{
diff --git a/examples/celestial-heights/src/systems/world.ts b/examples/celestial-heights/src/systems/world.ts
index e2c24a784..0972ff3ec 100644
--- a/examples/celestial-heights/src/systems/world.ts
+++ b/examples/celestial-heights/src/systems/world.ts
@@ -180,7 +180,7 @@ export const spawnerSystem = defineSystem(
*/
function standable(grid: NavGrid | null, at: { x: number; y: number }): { x: number; y: number } {
if (!grid) return at;
- const cell = grid.worldToCell(at.x, at.y);
+ const cell = grid.worldToCell(at);
if (grid.isWalkable(cell.x, cell.y)) return at;
const near = grid.nearestWalkable(cell.x, cell.y, 6);
return near ? grid.cellToWorld(near.x, near.y) : at;
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 21cc775b7..9031fc291 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4666,12 +4666,14 @@ repathInterval: number
speed: number
targetX: number
targetY: number
+targetZ: number
```
## NavGrid — class @experimental
```
+canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
-cellToWorld: (gx: number, gy: number) => Vec2
+cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
height: number
inBounds: (gx: number, gy: number) => boolean
@@ -4680,10 +4682,15 @@ isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
originX: number
originY: number
+originZ: number
+plane: NavPlane
setWalkable: (gx: number, gy: number, walkable: boolean) => void
+stepHeight: number
+surface: Float32Array<ArrayBufferLike> | null
+surfaceAt: (gx: number, gy: number) => number
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (wx: number, wy: number) => Cell
+worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4692,7 +4699,10 @@ static prototype: NavGrid
```
cellSize: number
height: number
-origin: Vec2 | undefined
+origin: { x: number; y: number; z?: number; } | undefined
+plane: NavPlane | undefined
+stepHeight: number | undefined
+surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
@@ -4707,7 +4717,7 @@ static prototype: NavPlugin
## Navigation — class @experimental
```
-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | null
+findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
grid: NavGrid | null
hasGrid: () => boolean
setGrid: (grid: NavGrid | null) => void
@@ -10997,7 +11007,7 @@ ParticlePlugin
## pathToWorld — function @experimental
```
-(grid: NavGrid, path: Cell[]): Vec2[]
+(grid: NavGrid, path: Cell[]): Vec3[]
```
## percent — const @public
@@ -11682,7 +11692,7 @@ ServicesPlugin
## setNavDestination — function @experimental
```
-(world: World, entity: Entity, target: Vec2): void
+(world: World, entity: Entity, target: { x: number; y: number; z?: number; }): void
```
## setPlayMode — function @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 843ee0546..0b7ccd8f6 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4844,12 +4844,14 @@ repathInterval: number
speed: number
targetX: number
targetY: number
+targetZ: number
```
## NavGrid — class @experimental
```
+canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
-cellToWorld: (gx: number, gy: number) => Vec2
+cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
height: number
inBounds: (gx: number, gy: number) => boolean
@@ -4858,10 +4860,15 @@ isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
originX: number
originY: number
+originZ: number
+plane: NavPlane
setWalkable: (gx: number, gy: number, walkable: boolean) => void
+stepHeight: number
+surface: Float32Array<ArrayBufferLike> | null
+surfaceAt: (gx: number, gy: number) => number
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (wx: number, wy: number) => Cell
+worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4870,7 +4877,10 @@ static prototype: NavGrid
```
cellSize: number
height: number
-origin: Vec2 | undefined
+origin: { x: number; y: number; z?: number; } | undefined
+plane: NavPlane | undefined
+stepHeight: number | undefined
+surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
@@ -4885,7 +4895,7 @@ static prototype: NavPlugin
## Navigation — class @experimental
```
-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | null
+findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
grid: NavGrid | null
hasGrid: () => boolean
setGrid: (grid: NavGrid | null) => void
@@ -11240,7 +11250,7 @@ ParticlePlugin
## pathToWorld — function @experimental
```
-(grid: NavGrid, path: Cell[]): Vec2[]
+(grid: NavGrid, path: Cell[]): Vec3[]
```
## percent — const @public
@@ -11925,7 +11935,7 @@ ServicesPlugin
## setNavDestination — function @experimental
```
-(world: World, entity: Entity, target: Vec2): void
+(world: World, entity: Entity, target: { x: number; y: number; z?: number; }): void
```
## setPlayMode — function @experimental
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index dd2c8d9aa..65eb458f1 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4661,12 +4661,14 @@ repathInterval: number
speed: number
targetX: number
targetY: number
+targetZ: number
```
## NavGrid — class @experimental
```
+canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
-cellToWorld: (gx: number, gy: number) => Vec2
+cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
height: number
inBounds: (gx: number, gy: number) => boolean
@@ -4675,10 +4677,15 @@ isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
originX: number
originY: number
+originZ: number
+plane: NavPlane
setWalkable: (gx: number, gy: number, walkable: boolean) => void
+stepHeight: number
+surface: Float32Array<ArrayBufferLike> | null
+surfaceAt: (gx: number, gy: number) => number
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (wx: number, wy: number) => Cell
+worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4687,7 +4694,10 @@ static prototype: NavGrid
```
cellSize: number
height: number
-origin: Vec2 | undefined
+origin: { x: number; y: number; z?: number; } | undefined
+plane: NavPlane | undefined
+stepHeight: number | undefined
+surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
@@ -4702,7 +4712,7 @@ static prototype: NavPlugin
## Navigation — class @experimental
```
-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | null
+findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
grid: NavGrid | null
hasGrid: () => boolean
setGrid: (grid: NavGrid | null) => void
@@ -11002,7 +11012,7 @@ ParticlePlugin
## pathToWorld — function @experimental
```
-(grid: NavGrid, path: Cell[]): Vec2[]
+(grid: NavGrid, path: Cell[]): Vec3[]
```
## percent — const @public
@@ -11687,7 +11697,7 @@ ServicesPlugin
## setNavDestination — function @experimental
```
-(world: World, entity: Entity, target: Vec2): void
+(world: World, entity: Entity, target: { x: number; y: number; z?: number; }): void
```
## setPlayMode — function @experimental
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 60656abad..7d880e034 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4906,12 +4906,14 @@ repathInterval: number
speed: number
targetX: number
targetY: number
+targetZ: number
```
## NavGrid — class @experimental
```
+canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
-cellToWorld: (gx: number, gy: number) => Vec2
+cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
height: number
inBounds: (gx: number, gy: number) => boolean
@@ -4920,10 +4922,15 @@ isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
originX: number
originY: number
+originZ: number
+plane: NavPlane
setWalkable: (gx: number, gy: number, walkable: boolean) => void
+stepHeight: number
+surface: Float32Array<ArrayBufferLike> | null
+surfaceAt: (gx: number, gy: number) => number
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (wx: number, wy: number) => Cell
+worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4932,7 +4939,10 @@ static prototype: NavGrid
```
cellSize: number
height: number
-origin: Vec2 | undefined
+origin: { x: number; y: number; z?: number; } | undefined
+plane: NavPlane | undefined
+stepHeight: number | undefined
+surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
@@ -4947,7 +4957,7 @@ static prototype: NavPlugin
## Navigation — class @experimental
```
-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | null
+findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
grid: NavGrid | null
hasGrid: () => boolean
setGrid: (grid: NavGrid | null) => void
@@ -11252,7 +11262,7 @@ ParticlePlugin
## pathToWorld — function @experimental
```
-(grid: NavGrid, path: Cell[]): Vec2[]
+(grid: NavGrid, path: Cell[]): Vec3[]
```
## percent — const @public
@@ -11937,7 +11947,7 @@ ServicesPlugin
## setNavDestination — function @experimental
```
-(world: World, entity: Entity, target: Vec2): void
+(world: World, entity: Entity, target: { x: number; y: number; z?: number; }): void
```
## setPlayMode — function @experimental
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e35230124..5f4783dcb 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4668,12 +4668,14 @@ repathInterval: number
speed: number
targetX: number
targetY: number
+targetZ: number
```
## NavGrid — class @experimental
```
+canStep: (fromX: number, fromY: number, toX: number, toY: number) => boolean
cellSize: number
-cellToWorld: (gx: number, gy: number) => Vec2
+cellToWorld: (gx: number, gy: number) => Vec3
clearanceAt: (gx: number, gy: number) => number
height: number
inBounds: (gx: number, gy: number) => boolean
@@ -4682,10 +4684,15 @@ isWalkable: (gx: number, gy: number) => boolean
nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number) => Cell | null
originX: number
originY: number
+originZ: number
+plane: NavPlane
setWalkable: (gx: number, gy: number, walkable: boolean) => void
+stepHeight: number
+surface: Float32Array<ArrayBufferLike> | null
+surfaceAt: (gx: number, gy: number) => number
walkable: Uint8Array<ArrayBufferLike>
width: number
-worldToCell: (wx: number, wy: number) => Cell
+worldToCell: (p: { x: number; y: number; z?: number; }) => Cell
static new (opts: NavGridOptions): NavGrid
static prototype: NavGrid
```
@@ -4694,7 +4701,10 @@ static prototype: NavGrid
```
cellSize: number
height: number
-origin: Vec2 | undefined
+origin: { x: number; y: number; z?: number; } | undefined
+plane: NavPlane | undefined
+stepHeight: number | undefined
+surface: ArrayLike<number> | undefined
walkable: ArrayLike<number> | undefined
width: number
```
@@ -4709,7 +4719,7 @@ static prototype: NavPlugin
## Navigation — class @experimental
```
-findWorldPath: (from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number; }) => Vec2[] | null
+findWorldPath: (from: { x: number; y: number; z?: number; }, to: { x: number; y: number; z?: number; }, opts?: PathfindOptions & { radius?: number; }) => Vec3[] | null
grid: NavGrid | null
hasGrid: () => boolean
setGrid: (grid: NavGrid | null) => void
@@ -11024,7 +11034,7 @@ ParticlePlugin
## pathToWorld — function @experimental
```
-(grid: NavGrid, path: Cell[]): Vec2[]
+(grid: NavGrid, path: Cell[]): Vec3[]
```
## percent — const @public
@@ -11709,7 +11719,7 @@ ServicesPlugin
## setNavDestination — function @experimental
```
-(world: World, entity: Entity, target: Vec2): void
+(world: World, entity: Entity, target: { x: number; y: number; z?: number; }): void
```
## setPlayMode — function @experimental
diff --git a/sdk/src/ai/nav/NavAgent.ts b/sdk/src/ai/nav/NavAgent.ts
index 4229484db..7d1cdf24a 100644
--- a/sdk/src/ai/nav/NavAgent.ts
+++ b/sdk/src/ai/nav/NavAgent.ts
@@ -13,7 +13,7 @@
import { defineComponent } from '../../ecs/component';
import type { World } from '../../ecs/world';
-import type { Entity, Vec2 } from '../../types';
+import type { Entity } from '../../types';
export interface NavAgentData {
/** Movement speed in world pixels per second. */
@@ -34,6 +34,7 @@ export interface NavAgentData {
/** Destination in world pixels. */
targetX: number;
targetY: number;
+ targetZ: number;
/** Set true by the system the frame the agent reaches its goal. */
arrived: boolean;
}
@@ -46,6 +47,7 @@ export const NavAgent = defineComponent<NavAgentData>('NavAgent', {
hasTarget: false,
targetX: 0,
targetY: 0,
+ targetZ: 0,
arrived: false,
}, {
fields: {
@@ -59,6 +61,7 @@ export const NavAgent = defineComponent<NavAgentData>('NavAgent', {
hasTarget: { category: 'Target' },
targetX: { unit: 'px', category: 'Target' },
targetY: { unit: 'px', category: 'Target' },
+ targetZ: { unit: 'px', category: 'Target' },
arrived: { category: 'Target', advanced: true },
},
});
@@ -68,12 +71,19 @@ export const NavAgent = defineComponent<NavAgentData>('NavAgent', {
* (e.g. to chase a moving target) — the system only replans when the target
* actually moves or the repath timer elapses.
*/
-export function setNavDestination(world: World, entity: Entity, target: Vec2): void {
+export function setNavDestination(
+ world: World,
+ entity: Entity,
+ target: { x: number; y: number; z?: number },
+): void {
if (!world.has(entity, NavAgent)) return;
const agent = world.get(entity, NavAgent);
agent.hasTarget = true;
agent.targetX = target.x;
agent.targetY = target.y;
+ // `z` is optional so a flat game keeps naming a destination in two, and a
+ // point in the ground plane of a spatial one is not silently taken as depth 0.
+ agent.targetZ = target.z ?? 0;
agent.arrived = false;
world.set(entity, NavAgent, agent);
}
diff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.ts
index 70d3af79d..c980a0773 100644
--- a/sdk/src/ai/nav/NavGrid.ts
+++ b/sdk/src/ai/nav/NavGrid.ts
@@ -3,14 +3,21 @@
/**
* @file NavGrid.ts
* @brief Uniform navigation grid — a walkability bitmap plus the affine map
- * between grid cells and world pixels.
+ * between grid cells and world space.
+ *
+ * ONE grid for both kinds of scene. What separates them is which world plane the
+ * cells lie in and what the third axis holds: a flat scene's cells lie in x/y at
+ * a constant depth, a spatial one's lie in x/z and each carries the height of
+ * the ground there. Everything above that — the walkability mask, the clearance
+ * transform, the A* over it — is the same question either way, and a second
+ * class would be the same code with two axes renamed.
*
* Pure data + math, zero engine/wasm dependency, so the whole pathfinding core
- * is unit-testable in isolation. The engine binding (build one from a tilemap
- * layer) lives in navGridFromTilemap.ts; the A* search in pathfind.ts.
+ * is unit-testable in isolation. The engine bindings (build one from a tilemap
+ * layer, or bake one out of the 3D solver) live beside it; A* in pathfind.ts.
*/
-import type { Vec2 } from '../../types';
+import type { Vec2, Vec3 } from '../../types';
/** Integer grid coordinate. Kept distinct from {@link Vec2} to flag cell-space. */
export interface Cell {
@@ -18,6 +25,14 @@ export interface Cell {
y: number;
}
+/**
+ * Which world plane the cells lie in. `xy` is a flat scene's own plane — the
+ * one every 2D game has been navigated on. `xz` is the ground of a spatial
+ * scene, whose remaining axis (height) is what {@link NavGrid.surfaceAt}
+ * answers per cell.
+ */
+export type NavPlane = 'xy' | 'xz';
+
export interface NavGridOptions {
/** Cell columns. */
width: number;
@@ -25,13 +40,28 @@ export interface NavGridOptions {
height: number;
/** World pixels per cell (square). */
cellSize: number;
- /** World position of cell (0,0)'s center. Defaults to origin. */
- origin?: Vec2;
+ /** World position of cell (0,0)'s center. Defaults to the world origin. */
+ origin?: { x: number; y: number; z?: number };
/**
* Walkability, row-major `width * height`, 1 = walkable / 0 = blocked.
* Defaults to fully walkable. Copied in, not retained.
*/
walkable?: ArrayLike<number>;
+ /** The plane the cells lie in. Defaults to `xy` — a flat scene. */
+ plane?: NavPlane;
+ /**
+ * Height of the walkable ground in each cell, on the axis the plane leaves
+ * out, row-major. Absent ⇒ every cell sits at the origin's own third axis,
+ * which is what a flat scene means.
+ */
+ surface?: ArrayLike<number>;
+ /**
+ * How big a height difference between neighbouring cells an agent can cross
+ * — a step it can walk up, as opposed to a ledge it would fall off. Only
+ * meaningful with a `surface`; 0 (the default) lets any difference through,
+ * which is what a grid with no heights has always done.
+ */
+ stepHeight?: number;
}
/**
@@ -43,10 +73,17 @@ export class NavGrid {
readonly width: number;
readonly height: number;
readonly cellSize: number;
+ /** Cell (0,0)'s centre, on the plane's two axes. */
readonly originX: number;
readonly originY: number;
+ /** Where the plane itself sits on the axis it leaves out. */
+ readonly originZ: number;
+ readonly plane: NavPlane;
+ readonly stepHeight: number;
/** Row-major walkability, 1 = walkable. Mutable via {@link setWalkable}. */
readonly walkable: Uint8Array;
+ /** Row-major ground height, or null when every cell sits at `originZ`. */
+ readonly surface: Float32Array | null;
constructor(opts: NavGridOptions) {
this.width = opts.width;
@@ -54,6 +91,9 @@ export class NavGrid {
this.cellSize = opts.cellSize;
this.originX = opts.origin?.x ?? 0;
this.originY = opts.origin?.y ?? 0;
+ this.originZ = opts.origin?.z ?? 0;
+ this.plane = opts.plane ?? 'xy';
+ this.stepHeight = opts.stepHeight ?? 0;
const n = this.width * this.height;
this.walkable = new Uint8Array(n);
@@ -62,6 +102,7 @@ export class NavGrid {
} else {
this.walkable.fill(1);
}
+ this.surface = opts.surface ? Float32Array.from(opts.surface as ArrayLike<number>) : null;
}
index(gx: number, gy: number): number {
@@ -96,16 +137,40 @@ export class NavGrid {
private clearance_: Uint8Array | null = null;
- /** Center of cell `(gx, gy)` in world pixels. */
- cellToWorld(gx: number, gy: number): Vec2 {
- return { x: this.originX + gx * this.cellSize, y: this.originY + gy * this.cellSize };
+ /** Height of the ground in cell `(gx, gy)`, on the axis the plane leaves out. */
+ surfaceAt(gx: number, gy: number): number {
+ if (!this.surface || !this.inBounds(gx, gy)) return this.originZ;
+ return this.surface[gy * this.width + gx];
+ }
+
+ /**
+ * Whether an agent can walk between two NEIGHBOURING cells. Both must be
+ * walkable, and the ground between them must not step further than
+ * {@link stepHeight} — a wall a metre high blocks a route that a kerb does
+ * not, and a grid with no heights (or no step limit) never says no here.
+ */
+ canStep(fromX: number, fromY: number, toX: number, toY: number): boolean {
+ if (!this.isWalkable(fromX, fromY) || !this.isWalkable(toX, toY)) return false;
+ if (!this.surface || this.stepHeight <= 0) return true;
+ return Math.abs(this.surfaceAt(toX, toY) - this.surfaceAt(fromX, fromY)) <= this.stepHeight;
+ }
+
+ /** Centre of cell `(gx, gy)` in world space, on the grid's own plane. */
+ cellToWorld(gx: number, gy: number): Vec3 {
+ const u = this.originX + gx * this.cellSize;
+ const v = this.originY + gy * this.cellSize;
+ return this.plane === 'xy'
+ ? { x: u, y: v, z: this.originZ }
+ : { x: u, y: this.surfaceAt(gx, gy), z: v };
}
- /** Cell containing world point `(wx, wy)`. May be out of bounds — caller checks. */
- worldToCell(wx: number, wy: number): Cell {
+ /** Cell containing a world point. May be out of bounds — caller checks. */
+ worldToCell(p: { x: number; y: number; z?: number }): Cell {
+ const u = p.x;
+ const v = this.plane === 'xy' ? p.y : (p.z ?? 0);
return {
- x: Math.round((wx - this.originX) / this.cellSize),
- y: Math.round((wy - this.originY) / this.cellSize),
+ x: Math.round((u - this.originX) / this.cellSize),
+ y: Math.round((v - this.originY) / this.cellSize),
};
}
diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.ts
index d0cee8982..28c78d44b 100644
--- a/sdk/src/ai/nav/NavPlugin.ts
+++ b/sdk/src/ai/nav/NavPlugin.ts
@@ -28,10 +28,11 @@ import { advanceAlongPath } from './follow';
/** Per-entity runtime path state, owned by the driving system (not serialized). */
export interface AgentRuntime {
- waypoints: import('../../types').Vec2[];
+ waypoints: import('../../types').Vec3[];
index: number;
plannedX: number;
plannedY: number;
+ plannedZ: number;
repathTimer: number;
reachable: boolean;
}
@@ -66,12 +67,13 @@ export function stepNavigation(
const tf = world.get(entity, Transform);
let rt = runtimes.get(entity);
- const targetMoved = !rt || rt.plannedX !== agent.targetX || rt.plannedY !== agent.targetY;
+ 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(
- { x: tf.position.x, y: tf.position.y },
- { x: agent.targetX, y: agent.targetY },
+ tf.position,
+ { x: agent.targetX, y: agent.targetY, z: agent.targetZ },
{ radius: agent.radius },
);
rt = {
@@ -80,6 +82,7 @@ export function stepNavigation(
index: path && path.length > 1 ? 1 : 0,
plannedX: agent.targetX,
plannedY: agent.targetY,
+ plannedZ: agent.targetZ,
repathTimer: agent.repathInterval,
reachable: path !== null,
};
@@ -90,10 +93,11 @@ export function stepNavigation(
// change or repath timer) rather than churning it every frame.
if (!rt.reachable) continue;
- const pos = { x: tf.position.x, y: tf.position.y };
+ const pos = { x: tf.position.x, y: tf.position.y, z: tf.position.z };
rt.index = advanceAlongPath(pos, rt.waypoints, rt.index, agent.speed * dt);
tf.position.x = pos.x;
tf.position.y = pos.y;
+ tf.position.z = pos.z;
world.set(entity, Transform, tf);
// Arrival is a DISTANCE, not the end of the list: an agent that has to
@@ -101,7 +105,7 @@ export function stepNavigation(
// one that walks the path exactly stands on top of its target.
const goal = rt.waypoints[rt.waypoints.length - 1];
const withinGoal = goal !== undefined && agent.arriveRadius > 0
- && Math.hypot(goal.x - pos.x, goal.y - pos.y) <= agent.arriveRadius;
+ && Math.hypot(goal.x - pos.x, goal.y - pos.y, goal.z - pos.z) <= agent.arriveRadius;
if (rt.index >= rt.waypoints.length || withinGoal) {
agent.arrived = true;
agent.hasTarget = false;
diff --git a/sdk/src/ai/nav/Navigation.ts b/sdk/src/ai/nav/Navigation.ts
index 89e40240f..5b35b9aa8 100644
--- a/sdk/src/ai/nav/Navigation.ts
+++ b/sdk/src/ai/nav/Navigation.ts
@@ -9,7 +9,7 @@
*/
import { defineResource } from '../../ecs/resource';
-import type { Vec2 } from '../../types';
+import type { Vec3 } from '../../types';
import { NavGrid } from './NavGrid';
import { findPath, pathToWorld, type PathfindOptions } from './pathfind';
@@ -26,16 +26,24 @@ export class Navigation {
}
/**
- * Plan a world-space path (cell-center waypoints) between two world points,
+ * Plan a world-space path (cell-centre waypoints) between two world points,
* or null if there is no grid or no route. `radius` is the body being
* routed, in world units: a path planned for a point is a path only the
* centre of an agent fits through.
+ *
+ * The waypoints carry all three axes: on a flat grid the third is the plane
+ * the scene is drawn on, and on a spatial one it is the height of the ground
+ * the route walks over.
*/
- findWorldPath(from: Vec2, to: Vec2, opts?: PathfindOptions & { radius?: number }): Vec2[] | null {
+ findWorldPath(
+ from: { x: number; y: number; z?: number },
+ to: { x: number; y: number; z?: number },
+ opts?: PathfindOptions & { radius?: number },
+ ): Vec3[] | null {
const grid = this.grid;
if (!grid) return null;
- const start = grid.worldToCell(from.x, from.y);
- const goal = grid.worldToCell(to.x, to.y);
+ const start = grid.worldToCell(from);
+ const goal = grid.worldToCell(to);
const radius = opts?.radius ?? 0;
const clearance = opts?.clearance ?? (radius > 0 ? Math.ceil(radius / grid.cellSize) : 0);
const cells = findPath(grid, start, goal, { ...opts, clearance });
diff --git a/sdk/src/ai/nav/follow.ts b/sdk/src/ai/nav/follow.ts
index dbb54e32f..ec99609a5 100644
--- a/sdk/src/ai/nav/follow.ts
+++ b/sdk/src/ai/nav/follow.ts
@@ -5,17 +5,22 @@
* @brief Kinematic path following — pure, unit-testable movement integration.
*/
-import type { Vec2 } from '../../types';
+import type { Vec3 } from '../../types';
/**
* Advance `pos` up to `distance` pixels along the waypoint chain starting at
* `startIndex`, snapping onto each reached waypoint so a single frame can cross
* several. Mutates `pos` in place. Returns the new waypoint index — a value
* `>= waypoints.length` means the end was reached.
+ *
+ * The walk is three-dimensional: a route over sloped ground is longer than its
+ * shadow, and spending the frame's budget on the shadow walks an agent up a hill
+ * faster than it walks along the flat. On a flat grid every waypoint shares one
+ * third axis and the arithmetic is what it always was.
*/
export function advanceAlongPath(
- pos: Vec2,
- waypoints: Vec2[],
+ pos: Vec3,
+ waypoints: Vec3[],
startIndex: number,
distance: number,
): number {
@@ -25,7 +30,8 @@ export function advanceAlongPath(
const wp = waypoints[index];
const dx = wp.x - pos.x;
const dy = wp.y - pos.y;
- const dist = Math.hypot(dx, dy);
+ const dz = wp.z - pos.z;
+ const dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (dist === 0) {
// Already on this waypoint; step to the next without consuming budget.
index++;
@@ -34,11 +40,13 @@ export function advanceAlongPath(
if (dist <= remaining) {
pos.x = wp.x;
pos.y = wp.y;
+ pos.z = wp.z;
remaining -= dist;
index++;
} else {
pos.x += (dx / dist) * remaining;
pos.y += (dy / dist) * remaining;
+ pos.z += (dz / dist) * remaining;
remaining = 0;
}
}
diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.ts
index 0183fb706..4fb3b684c 100644
--- a/sdk/src/ai/nav/pathfind.ts
+++ b/sdk/src/ai/nav/pathfind.ts
@@ -11,7 +11,7 @@
*/
import type { NavGrid, Cell } from './NavGrid';
-import type { Vec2 } from '../../types';
+import type { Vec3 } from '../../types';
export interface PathfindOptions {
/** Allow 8-connected diagonal moves. Default true. */
@@ -88,6 +88,9 @@ export function findPath(
const nx = cx + dx;
const ny = cy + dy;
if (!fits(grid, nx, ny, clearance)) continue;
+ // Ground that steps up further than the agent can climb is a wall,
+ // however walkable the cell on top of it is.
+ if (!grid.canStep(cx, cy, nx, ny)) continue;
// No corner-cutting: a diagonal needs both shared orthogonals open.
if (i >= 4 && (!fits(grid, cx + dx, cy, clearance) || !fits(grid, cx, cy + dy, clearance))) continue;
@@ -107,8 +110,8 @@ export function findPath(
return null;
}
-/** Convert a cell path to world-space waypoints (cell centers). */
-export function pathToWorld(grid: NavGrid, path: Cell[]): Vec2[] {
+/** 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-follow.test.ts b/sdk/tests/nav-follow.test.ts
index c4464954c..6ba47fc6f 100644
--- a/sdk/tests/nav-follow.test.ts
+++ b/sdk/tests/nav-follow.test.ts
@@ -3,49 +3,69 @@
import { describe, it, expect } from 'vitest';
import { advanceAlongPath } from '../src/ai/nav/follow';
+// Every case below is the FLAT one, written in three axes with a constant third:
+// what a 2D game does is what this function did before it learnt about depth.
describe('advanceAlongPath', () => {
it('moves part-way toward a single waypoint', () => {
- const pos = { x: 0, y: 0 };
- const idx = advanceAlongPath(pos, [{ x: 10, y: 0 }], 0, 4);
- expect(pos).toEqual({ x: 4, y: 0 });
+ const pos = { x: 0, y: 0, z: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 10, y: 0, z: 0 }], 0, 4);
+ expect(pos).toEqual({ x: 4, y: 0, z: 0 });
expect(idx).toBe(0); // not yet reached
});
it('snaps onto a waypoint reached exactly', () => {
- const pos = { x: 0, y: 0 };
- const idx = advanceAlongPath(pos, [{ x: 10, y: 0 }], 0, 10);
- expect(pos).toEqual({ x: 10, y: 0 });
+ const pos = { x: 0, y: 0, z: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 10, y: 0, z: 0 }], 0, 10);
+ expect(pos).toEqual({ x: 10, y: 0, z: 0 });
expect(idx).toBe(1);
});
it('crosses multiple waypoints in one step', () => {
- const pos = { x: 0, y: 0 };
- const waypoints = [{ x: 10, y: 0 }, { x: 20, y: 0 }, { x: 30, y: 0 }];
+ const pos = { x: 0, y: 0, z: 0 };
+ const waypoints = [{ x: 10, y: 0, z: 0 }, { x: 20, y: 0, z: 0 }, { x: 30, y: 0, z: 0 }];
const idx = advanceAlongPath(pos, waypoints, 0, 25);
- expect(pos).toEqual({ x: 25, y: 0 });
+ expect(pos).toEqual({ x: 25, y: 0, z: 0 });
expect(idx).toBe(2); // consumed wp0 and wp1, part-way to wp2
});
it('reports end reached when budget exceeds the whole chain', () => {
- const pos = { x: 0, y: 0 };
- const waypoints = [{ x: 10, y: 0 }, { x: 20, y: 0 }];
+ const pos = { x: 0, y: 0, z: 0 };
+ const waypoints = [{ x: 10, y: 0, z: 0 }, { x: 20, y: 0, z: 0 }];
const idx = advanceAlongPath(pos, waypoints, 0, 1000);
- expect(pos).toEqual({ x: 20, y: 0 });
+ expect(pos).toEqual({ x: 20, y: 0, z: 0 });
expect(idx).toBe(2); // == waypoints.length → done
});
it('follows a diagonal correctly', () => {
- const pos = { x: 0, y: 0 };
- const idx = advanceAlongPath(pos, [{ x: 3, y: 4 }], 0, 5);
+ const pos = { x: 0, y: 0, z: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 3, y: 4, z: 0 }], 0, 5);
expect(pos.x).toBeCloseTo(3);
expect(pos.y).toBeCloseTo(4);
expect(idx).toBe(1);
});
+ // A slope is longer than its shadow: budgeting on the shadow walks an agent
+ // uphill faster than along the flat, and every case above has a constant
+ // third axis, so none of them can tell.
+ it('spends the budget on the real distance, not on its shadow', () => {
+ const pos = { x: 0, y: 0, z: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 0, y: 40, z: 30 }], 0, 25);
+ expect(pos.y).toBeCloseTo(20); // half of a 50-unit leg, not of a 40 one
+ expect(pos.z).toBeCloseTo(15);
+ expect(idx).toBe(0);
+ });
+
+ it('snaps onto a waypoint on another level, and carries the height', () => {
+ const pos = { x: 0, y: 0, z: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 0, y: 40, z: 30 }], 0, 50);
+ expect(pos).toEqual({ x: 0, y: 40, z: 30 });
+ expect(idx).toBe(1);
+ });
+
it('skips a waypoint already at pos without looping', () => {
- const pos = { x: 5, y: 5 };
- const idx = advanceAlongPath(pos, [{ x: 5, y: 5 }, { x: 15, y: 5 }], 0, 4);
- expect(pos).toEqual({ x: 9, y: 5 });
+ const pos = { x: 5, y: 5, z: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 5, y: 5, z: 0 }, { x: 15, y: 5, z: 0 }], 0, 4);
+ expect(pos).toEqual({ x: 9, y: 5, z: 0 });
expect(idx).toBe(1);
});
});
diff --git a/sdk/tests/nav-pathfind.test.ts b/sdk/tests/nav-pathfind.test.ts
index ee24e318e..b54725a96 100644
--- a/sdk/tests/nav-pathfind.test.ts
+++ b/sdk/tests/nav-pathfind.test.ts
@@ -35,12 +35,37 @@ function isContiguous(path: Cell[], diagonal: boolean): boolean {
describe('NavGrid', () => {
it('maps cells to world centers and back', () => {
const grid = new NavGrid({ width: 4, height: 4, cellSize: 32, origin: { x: 100, y: 200 } });
- expect(grid.cellToWorld(0, 0)).toEqual({ x: 100, y: 200 });
- expect(grid.cellToWorld(2, 1)).toEqual({ x: 164, y: 232 });
+ expect(grid.cellToWorld(0, 0)).toEqual({ x: 100, y: 200, z: 0 });
+ expect(grid.cellToWorld(2, 1)).toEqual({ x: 164, y: 232, z: 0 });
// worldToCell is the inverse of cellToWorld on cell centers.
- expect(grid.worldToCell(164, 232)).toEqual({ x: 2, y: 1 });
+ expect(grid.worldToCell({ x: 164, y: 232 })).toEqual({ x: 2, y: 1 });
// Points anywhere inside a cell round to that cell.
- expect(grid.worldToCell(170, 210)).toEqual({ x: 2, y: 0 });
+ expect(grid.worldToCell({ x: 170, y: 210 })).toEqual({ x: 2, y: 0 });
+ });
+
+ // The same grid, laid in the ground plane of a spatial scene: the cells map
+ // to x/z and the axis they leave out carries the height of the ground.
+ it('maps cells to the ground plane, at the height of each cell', () => {
+ const grid = new NavGrid({
+ width: 2, height: 2, cellSize: 10, plane: 'xz', origin: { x: 0, y: 0, z: 0 },
+ surface: [0, 0, 5, 40],
+ });
+ expect(grid.cellToWorld(0, 0)).toEqual({ x: 0, y: 0, z: 0 });
+ expect(grid.cellToWorld(1, 1)).toEqual({ x: 10, y: 40, z: 10 });
+ // The cell is named by x/z; the height is an answer, never a question.
+ expect(grid.worldToCell({ x: 10, y: 999, z: 10 })).toEqual({ x: 1, y: 1 });
+ });
+
+ // A step an agent can walk up is a route; a wall of the same width is not.
+ // With no surface (or no limit) nothing here can say no — a flat grid's rule.
+ it('lets a small step through and a tall one not', () => {
+ const opts = { width: 2, height: 1, cellSize: 10, plane: 'xz' as const, stepHeight: 10 };
+ const kerb = new NavGrid({ ...opts, surface: [0, 6] });
+ const wall = new NavGrid({ ...opts, surface: [0, 60] });
+ expect(kerb.canStep(0, 0, 1, 0)).toBe(true);
+ expect(wall.canStep(0, 0, 1, 0)).toBe(false);
+ expect(new NavGrid({ ...opts, surface: [0, 60], stepHeight: 0 }).canStep(0, 0, 1, 0)).toBe(true);
+ expect(new NavGrid(opts).canStep(0, 0, 1, 0)).toBe(true);
});
it('reports bounds and walkability', () => {
@@ -147,7 +172,38 @@ describe('findPath', () => {
const grid = new NavGrid({ width: 3, height: 1, cellSize: 20, origin: { x: 5, y: 5 } });
const path = findPath(grid, { x: 0, y: 0 }, { x: 2, y: 0 })!;
expect(pathToWorld(grid, path)).toEqual([
- { x: 5, y: 5 }, { x: 25, y: 5 }, { x: 45, y: 5 },
+ { x: 5, y: 5, z: 0 }, { x: 25, y: 5, z: 0 }, { x: 45, y: 5, z: 0 },
]);
});
+
+ // A ledge is not a wall — every cell here is walkable — but it is not a route
+ // either, and only the step limit can tell the search that.
+ it('routes around a ledge it cannot climb, and over one it can', () => {
+ // A tall ridge down the middle column, open along the top row:
+ // row 2: . . . row 1: . ^ . row 0: S ^ G
+ const ridge = () => [
+ 0, 90, 0,
+ 0, 90, 0,
+ 0, 0, 0,
+ ];
+ const spatial = { width: 3, height: 3, cellSize: 10, plane: 'xz' as const };
+ const blocked = new NavGrid({ ...spatial, surface: ridge(), stepHeight: 20 });
+ const path = findPath(blocked, { x: 0, y: 0 }, { x: 2, y: 0 }, { diagonal: false })!;
+ expect(path).not.toBeNull();
+ // It went the long way: through the open row rather than over the ridge.
+ expect(path.some(c => c.y === 2)).toBe(true);
+
+ // The same ridge, an agent that can climb it: straight across.
+ const climbable = new NavGrid({ ...spatial, surface: ridge(), stepHeight: 100 });
+ const over = findPath(climbable, { x: 0, y: 0 }, { x: 2, y: 0 }, { diagonal: false })!;
+ expect(over).toEqual([{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 2, y: 0 }]);
+ });
+
+ it('reports no route when the ledge cuts the grid in two', () => {
+ const grid = new NavGrid({
+ width: 3, height: 1, cellSize: 10, plane: 'xz',
+ surface: [0, 90, 0], stepHeight: 20,
+ });
+ expect(findPath(grid, { x: 0, y: 0 }, { x: 2, y: 0 })).toBeNull();
+ });
});