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): a door can shut

esengine703fc448389c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3a1d3cc86..6a65b062e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -170,6 +170,20 @@ published separately; it ships inside the editor.
than the box around them. Nothing waits for the solver any more: the geometry is
in the scene from the first frame.
+- **A door can shut.** `NavObstacle` is a box that takes ground away from the
+ navigable world without being geometry — a door, a gate, a tower just built —
+ and `enabled` is what opens it again. Blocking is a BAKE input rather than a
+ filter over the answer: the ground goes before the walkable area is eroded, so a
+ route keeps the agent's full width clear of an obstacle instead of scraping its
+ face. Changing one rebuilds the world, at most a few times a second, and an
+ obstacle that never stops moving says so once rather than taking the frame rate
+ with it. Both surfaces answer to it: a mesh is baked again, a grid has the cells
+ under the box marked — in a mask of its own, so a door closing and opening gives
+ back exactly the ground that was there, including the ground the map itself said
+ was blocked. Unlike the volume it turns with its entity, because a volume IS the
+ voxel grid and this only marks cells in one. New editor check `nav3d-obstacle`
+ shuts a doorway in a running game and opens it again.
+
- **A NavAgent with a body is steered, not moved.** The follower wrote the
Transform, which is right for a marker and wrong for a character: a
`CharacterController3D` has a solver of its own that collides, steps up and
diff --git a/desktop b/desktop
index 5853fcde2..39008bd43 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 5853fcde2f8eb4026c2e4f7526ce8d3bcd4e82f9
+Subproject commit 39008bd43e9fb63b6834fe5cd7dce36bee15817c
diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
index 02e0e8069..10937c21f 100644
--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx
@@ -100,6 +100,41 @@ on its own terms, and `collectNavGeometry(world, box)` is what gathers the trian
in the log.
</Aside>
+### Doors, gates and things placed in the way
+
+Anything with a collider already blocks, because the mesh is baked from the
+scene's collision geometry. **`NavObstacle`** is for what blocks *without* being
+geometry, or what stops blocking without moving:
+
+| `NavObstacle` field | Default | Description |
+|---|---|---|
+| `halfExtents` | `50, 100, 50` | Half the blocking box, in world pixels; the Transform is its centre. Unlike the volume, it turns with the entity. |
+| `enabled` | `true` | Whether it blocks right now. A door that opens is this field. |
+
+Blocking is a **bake input**, not a filter over the answer: an obstacle takes its
+ground away *before* the walkable area is eroded, so routes keep the agent's full
+width clear of it rather than scraping along its face. Changing one — moving it,
+resizing it, switching it on or off — rebuilds the navigable world, at most a few
+times a second.
+
+```typescript
+// A door swinging open, from any system with world access:
+const door = world.get(entity, NavObstacle);
+door.enabled = false;
+world.set(entity, NavObstacle, door);
+```
+
+Both surfaces answer to it: a mesh is baked again, a grid has the cells under the
+box marked. The grid's own walkability is kept separate, so a door closing and
+opening gives back exactly the ground that was there.
+
+<Aside type="caution">
+ **Not for something that travels.** An obstacle is for something that blocks and
+ then stops — a door, a gate, a tower just built. One that moves continuously
+ rebuilds the world several times a second and says so in the log; a moving body
+ is a job for the character controller it collides with, not for the bake.
+</Aside>
+
### Seeing what was baked
The volume's wireframe says where the bake looked. To see what it **found** while
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 8268c6ba6..47bc9ef9a 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
@@ -89,6 +89,36 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {
规划路线,并在日志里说一次。
</Aside>
+### 门、闸,以及被放在路上的东西
+
+任何带碰撞体的东西本来就会挡路——网格就是从场景的碰撞几何烘出来的。**`NavObstacle`**
+是给「**不是几何**却要挡路」的东西,或者「不动地方却要停止挡路」的东西准备的:
+
+| `NavObstacle` 字段 | 默认 | 说明 |
+|---|---|---|
+| `halfExtents` | `50, 100, 50` | 阻挡盒的半尺寸,单位世界像素;实体的 Transform 是它的中心。和体积不同,它会跟着实体转。 |
+| `enabled` | `true` | 它现在挡不挡。会开的门就是这个字段。 |
+
+阻挡是**烘焙的输入**,不是对答案的过滤:障碍在可走区域被腐蚀**之前**就把地面拿走,
+所以路线离它的距离是完整的 agent 宽度,而不是贴着它的面蹭过去。改动一个障碍——移动、
+改尺寸、开关——都会重建可走世界,每秒最多几次。
+
+```typescript
+// 门打开了,在任何能访问 world 的系统里:
+const door = world.get(entity, NavObstacle);
+door.enabled = false;
+world.set(entity, NavObstacle, door);
+```
+
+两种 surface 都认它:网格重新烘焙,格子把盒子底下的格标掉。格子自己的可走性是分开存的,
+所以门关上再打开,还给你的正是原来那片地。
+
+<Aside type="caution">
+ **不要给会一直移动的东西用。**障碍是给「挡一下然后停住」的东西准备的——门、闸、
+ 刚造好的塔。一直在动的障碍会让世界每秒重建好几次,它会在日志里说出来;
+ 会移动的物体该交给和它碰撞的角色控制器,不是交给烘焙。
+</Aside>
+
### 看见烘出来的东西
体积的线框说的是烘焙**往哪看**。想在还在编排场景的时候就看见它**找到了什么**,打开
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 53c95cac5..906820fbd 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 73,
- "experimental": 1612,
+ "experimental": 1618,
"deprecated": 3
},
- "total": 1798,
+ "total": 1804,
"subsystems": [
{
"id": "ecs",
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 91cad5960..833950378 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -144,7 +144,8 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
// ── Gameplay ───────────────────────────────────────────────────────────────
NavAgent: { category: 'gameplay', summary: 'Steers an entity along a path found on the navigation grid.', doc: 'gameplay/ai/navigation' },
- NavVolume: { category: 'gameplay', summary: 'The box a navigation grid is baked over, sampled out of the 3D world.', doc: 'gameplay/ai/navigation' },
+ NavVolume: { category: 'gameplay', summary: 'The box a navigation mesh is baked over, out of the scene\u2019s own collision geometry.', doc: 'gameplay/ai/navigation' },
+ NavObstacle: { category: 'gameplay', summary: 'A box that blocks without being geometry \u2014 a door, a gate, a placed building.', doc: 'gameplay/ai/navigation' },
Perceiver: { category: 'gameplay', summary: 'Senses nearby perception targets within a sight cone and range.', doc: 'gameplay/ai/perception' },
Perception: { category: 'gameplay', summary: "What a perceiver currently sees — written each frame for the entity's own logic to read.", doc: 'gameplay/ai/perception' },
PerceptionTarget: { category: 'gameplay', summary: 'Tag: perceivers can see this entity.', doc: 'gameplay/ai/perception' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 040338789..63c53b3d6 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1989,6 +1989,28 @@
"targetZ"
]
},
+ {
+ "name": "NavObstacle",
+ "source": "ts",
+ "fields": [
+ {
+ "key": "halfExtents",
+ "type": "Vec3",
+ "default": "(50, 100, 50)"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true",
+ "doc": "Whether it blocks right now — a door that opens."
+ }
+ ],
+ "animatable": [
+ "halfExtents.x",
+ "halfExtents.y",
+ "halfExtents.z"
+ ]
+ },
{
"name": "NavVolume",
"source": "ts",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 3456bac26..74c65e83c 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1498 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1504 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1354,6 +1354,7 @@ maxSlopeDegrees: number | undefined
maxVertsPerPoly: number | undefined
min: Vec3
minRegionArea: number | undefined
+obstacles: readonly NavObstacleBox[] | undefined
stepHeight: number | undefined
```
@@ -4715,6 +4716,7 @@ verts: Float32Array<ArrayBufferLike>
```
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
+clearObstructions: () => void
clearanceAt: (gx: number, gy: number) => number
describe: (sink: NavSurfaceSink) => void
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
@@ -4726,6 +4728,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number
originX: number
originY: number
originZ: number
+setObstructed: (gx: number, gy: number, obstructed: boolean) => void
setWalkable: (gx: number, gy: number, walkable: boolean) => void
up: Vec3
walkable: Uint8Array<ArrayBufferLike>
@@ -4778,6 +4781,24 @@ verticalReach: number
verts: Float32Array<ArrayBufferLike>
```
+## NavObstacle — const @experimental
+```
+ComponentDef<NavObstacleData>
+```
+
+## NavObstacleBox — interface @experimental
+```
+center: Vec3
+halfExtents: Vec3
+rotation: Quat
+```
+
+## NavObstacleData — interface @experimental
+```
+enabled: boolean
+halfExtents: Vec3
+```
+
## NavPlugin — class @experimental
```
build: (app: App) => void
@@ -9438,6 +9459,11 @@ AnimationPlugin
(source: PrefabData, delta: SourceDelta): PrefabData
```
+## applyObstaclesToGrid — function @experimental
+```
+(grid: NavGrid, obstacles: readonly NavObstacleBox[]): void
+```
+
## applyOverrides — function @experimental
```
(entity: OverrideTarget, overrides: readonly PrefabOverride[] | undefined): void
@@ -9723,6 +9749,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavObstacles — function @experimental
+```
+(world: World): NavObstacleBox[]
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -10988,6 +11019,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navObstacleDigest — function @experimental
+```
+(obstacles: readonly NavObstacleBox[]): number
+```
+
## navPlugin — const @experimental
```
NavPlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 102358379..5d79a3123 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 71 beta · 1517 experimental · 3 deprecated
+Symbols: 113 public · 71 beta · 1523 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1354,6 +1354,7 @@ maxSlopeDegrees: number | undefined
maxVertsPerPoly: number | undefined
min: Vec3
minRegionArea: number | undefined
+obstacles: readonly NavObstacleBox[] | undefined
stepHeight: number | undefined
```
@@ -4893,6 +4894,7 @@ verts: Float32Array<ArrayBufferLike>
```
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
+clearObstructions: () => void
clearanceAt: (gx: number, gy: number) => number
describe: (sink: NavSurfaceSink) => void
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
@@ -4904,6 +4906,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number
originX: number
originY: number
originZ: number
+setObstructed: (gx: number, gy: number, obstructed: boolean) => void
setWalkable: (gx: number, gy: number, walkable: boolean) => void
up: Vec3
walkable: Uint8Array<ArrayBufferLike>
@@ -4956,6 +4959,24 @@ verticalReach: number
verts: Float32Array<ArrayBufferLike>
```
+## NavObstacle — const @experimental
+```
+ComponentDef<NavObstacleData>
+```
+
+## NavObstacleBox — interface @experimental
+```
+center: Vec3
+halfExtents: Vec3
+rotation: Quat
+```
+
+## NavObstacleData — interface @experimental
+```
+enabled: boolean
+halfExtents: Vec3
+```
+
## NavPlugin — class @experimental
```
build: (app: App) => void
@@ -9631,6 +9652,11 @@ AnimationPlugin
(source: PrefabData, delta: SourceDelta): PrefabData
```
+## applyObstaclesToGrid — function @experimental
+```
+(grid: NavGrid, obstacles: readonly NavObstacleBox[]): void
+```
+
## applyOverrides — function @experimental
```
(entity: OverrideTarget, overrides: readonly PrefabOverride[] | undefined): void
@@ -9931,6 +9957,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavObstacles — function @experimental
+```
+(world: World): NavObstacleBox[]
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -11231,6 +11262,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navObstacleDigest — function @experimental
+```
+(obstacles: readonly NavObstacleBox[]): number
+```
+
## navPlugin — const @experimental
```
NavPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e355386aa..d84fabfa8 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 68 beta · 1497 experimental · 3 deprecated
+Symbols: 113 public · 68 beta · 1503 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1349,6 +1349,7 @@ maxSlopeDegrees: number | undefined
maxVertsPerPoly: number | undefined
min: Vec3
minRegionArea: number | undefined
+obstacles: readonly NavObstacleBox[] | undefined
stepHeight: number | undefined
```
@@ -4710,6 +4711,7 @@ verts: Float32Array<ArrayBufferLike>
```
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
+clearObstructions: () => void
clearanceAt: (gx: number, gy: number) => number
describe: (sink: NavSurfaceSink) => void
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
@@ -4721,6 +4723,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number
originX: number
originY: number
originZ: number
+setObstructed: (gx: number, gy: number, obstructed: boolean) => void
setWalkable: (gx: number, gy: number, walkable: boolean) => void
up: Vec3
walkable: Uint8Array<ArrayBufferLike>
@@ -4773,6 +4776,24 @@ verticalReach: number
verts: Float32Array<ArrayBufferLike>
```
+## NavObstacle — const @experimental
+```
+ComponentDef<NavObstacleData>
+```
+
+## NavObstacleBox — interface @experimental
+```
+center: Vec3
+halfExtents: Vec3
+rotation: Quat
+```
+
+## NavObstacleData — interface @experimental
+```
+enabled: boolean
+halfExtents: Vec3
+```
+
## NavPlugin — class @experimental
```
build: (app: App) => void
@@ -9433,6 +9454,11 @@ AnimationPlugin
(source: PrefabData, delta: SourceDelta): PrefabData
```
+## applyObstaclesToGrid — function @experimental
+```
+(grid: NavGrid, obstacles: readonly NavObstacleBox[]): void
+```
+
## applyOverrides — function @experimental
```
(entity: OverrideTarget, overrides: readonly PrefabOverride[] | undefined): void
@@ -9718,6 +9744,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavObstacles — function @experimental
+```
+(world: World): NavObstacleBox[]
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -10988,6 +11019,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navObstacleDigest — function @experimental
+```
+(obstacles: readonly NavObstacleBox[]): number
+```
+
## navPlugin — const @experimental
```
NavPlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 6e7c6b53d..df9099149 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1518 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1524 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1349,6 +1349,7 @@ maxSlopeDegrees: number | undefined
maxVertsPerPoly: number | undefined
min: Vec3
minRegionArea: number | undefined
+obstacles: readonly NavObstacleBox[] | undefined
stepHeight: number | undefined
```
@@ -4955,6 +4956,7 @@ verts: Float32Array<ArrayBufferLike>
```
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
+clearObstructions: () => void
clearanceAt: (gx: number, gy: number) => number
describe: (sink: NavSurfaceSink) => void
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
@@ -4966,6 +4968,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number
originX: number
originY: number
originZ: number
+setObstructed: (gx: number, gy: number, obstructed: boolean) => void
setWalkable: (gx: number, gy: number, walkable: boolean) => void
up: Vec3
walkable: Uint8Array<ArrayBufferLike>
@@ -5018,6 +5021,24 @@ verticalReach: number
verts: Float32Array<ArrayBufferLike>
```
+## NavObstacle — const @experimental
+```
+ComponentDef<NavObstacleData>
+```
+
+## NavObstacleBox — interface @experimental
+```
+center: Vec3
+halfExtents: Vec3
+rotation: Quat
+```
+
+## NavObstacleData — interface @experimental
+```
+enabled: boolean
+halfExtents: Vec3
+```
+
## NavPlugin — class @experimental
```
build: (app: App) => void
@@ -9678,6 +9699,11 @@ AnimationPlugin
(source: PrefabData, delta: SourceDelta): PrefabData
```
+## applyObstaclesToGrid — function @experimental
+```
+(grid: NavGrid, obstacles: readonly NavObstacleBox[]): void
+```
+
## applyOverrides — function @experimental
```
(entity: OverrideTarget, overrides: readonly PrefabOverride[] | undefined): void
@@ -9963,6 +9989,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavObstacles — function @experimental
+```
+(world: World): NavObstacleBox[]
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -11243,6 +11274,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navObstacleDigest — function @experimental
+```
+(obstacles: readonly NavObstacleBox[]): number
+```
+
## navPlugin — const @experimental
```
NavPlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index eec055ca8..568e2f248 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1508 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1514 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1349,6 +1349,7 @@ maxSlopeDegrees: number | undefined
maxVertsPerPoly: number | undefined
min: Vec3
minRegionArea: number | undefined
+obstacles: readonly NavObstacleBox[] | undefined
stepHeight: number | undefined
```
@@ -4717,6 +4718,7 @@ verts: Float32Array<ArrayBufferLike>
```
cellSize: number
cellToWorld: (gx: number, gy: number) => Vec3
+clearObstructions: () => void
clearanceAt: (gx: number, gy: number) => number
describe: (sink: NavSurfaceSink) => void
findWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null
@@ -4728,6 +4730,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: number
originX: number
originY: number
originZ: number
+setObstructed: (gx: number, gy: number, obstructed: boolean) => void
setWalkable: (gx: number, gy: number, walkable: boolean) => void
up: Vec3
walkable: Uint8Array<ArrayBufferLike>
@@ -4780,6 +4783,24 @@ verticalReach: number
verts: Float32Array<ArrayBufferLike>
```
+## NavObstacle — const @experimental
+```
+ComponentDef<NavObstacleData>
+```
+
+## NavObstacleBox — interface @experimental
+```
+center: Vec3
+halfExtents: Vec3
+rotation: Quat
+```
+
+## NavObstacleData — interface @experimental
+```
+enabled: boolean
+halfExtents: Vec3
+```
+
## NavPlugin — class @experimental
```
build: (app: App) => void
@@ -9460,6 +9481,11 @@ AnimationPlugin
(source: PrefabData, delta: SourceDelta): PrefabData
```
+## applyObstaclesToGrid — function @experimental
+```
+(grid: NavGrid, obstacles: readonly NavObstacleBox[]): void
+```
+
## applyOverrides — function @experimental
```
(entity: OverrideTarget, overrides: readonly PrefabOverride[] | undefined): void
@@ -9745,6 +9771,11 @@ BtPlugin
(world: World, opts: CollectNavGeometryOptions): NavGeometry
```
+## collectNavObstacles — function @experimental
+```
+(world: World): NavObstacleBox[]
+```
+
## collectNestedPrefabPaths — function @experimental
```
(prefab: PrefabData, loadPrefab: (path: string) => PrefabData | null, visited?: Set<string>): string[]
@@ -11015,6 +11046,11 @@ Mesh2DPlugin
(getTile: (x: number, y: number) => number, opts: BuildNavGridOptions): NavGrid
```
+## navObstacleDigest — function @experimental
+```
+(obstacles: readonly NavObstacleBox[]): number
+```
+
## navPlugin — const @experimental
```
NavPlugin
diff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.ts
index 00410c5fb..7e5f938bc 100644
--- a/sdk/src/ai/nav/NavGrid.ts
+++ b/sdk/src/ai/nav/NavGrid.ts
@@ -62,6 +62,9 @@ export class NavGrid implements NavSurface {
readonly originZ: number;
/** Row-major walkability, 1 = walkable. Mutable via {@link setWalkable}. */
readonly walkable: Uint8Array;
+ /** Cells an obstacle is standing on, or null while nothing blocks. Kept apart
+ * from `walkable` so a door closing and reopening cannot erase the map. */
+ private obstructed_: Uint8Array | null = null;
constructor(opts: NavGridOptions) {
this.width = opts.width;
@@ -89,7 +92,9 @@ export class NavGrid implements NavSurface {
}
isWalkable(gx: number, gy: number): boolean {
- return this.inBounds(gx, gy) && this.walkable[gy * this.width + gx] === 1;
+ if (!this.inBounds(gx, gy)) return false;
+ const i = gy * this.width + gx;
+ return this.walkable[i] === 1 && (this.obstructed_ === null || this.obstructed_[i] === 0);
}
setWalkable(gx: number, gy: number, walkable: boolean): void {
@@ -98,6 +103,28 @@ export class NavGrid implements NavSurface {
this.clearance_ = null;
}
+ /**
+ * Put something in the way of a cell, or take it out again. The map's own
+ * walkability is untouched: an obstacle is a thing standing ON the ground, and
+ * lifting it has to give back exactly the ground that was there.
+ */
+ setObstructed(gx: number, gy: number, obstructed: boolean): void {
+ if (!this.inBounds(gx, gy)) return;
+ if (!this.obstructed_) {
+ if (!obstructed) return;
+ this.obstructed_ = new Uint8Array(this.width * this.height);
+ }
+ this.obstructed_[gy * this.width + gx] = obstructed ? 1 : 0;
+ this.clearance_ = null;
+ }
+
+ /** Lift everything off the ground at once, before the obstacles are re-marked. */
+ clearObstructions(): void {
+ if (!this.obstructed_) return;
+ this.obstructed_.fill(0);
+ this.clearance_ = null;
+ }
+
/**
* Cells from here to the nearest thing that blocks — off the grid counts as
* blocked. An agent is a body: a path hugging a wall is walkable for the
diff --git a/sdk/src/ai/nav/NavObstacle.ts b/sdk/src/ai/nav/NavObstacle.ts
new file mode 100644
index 000000000..17e6dfa04
--- /dev/null
+++ b/sdk/src/ai/nav/NavObstacle.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NavObstacle.ts
+ * @brief A box that takes ground away from the navigable world — a door, a
+ * gate, a placed building.
+ *
+ * The scene's collision geometry is what the mesh is baked from, so anything with
+ * a collider already blocks. This is for what BLOCKS WITHOUT BEING GEOMETRY, or
+ * what stops blocking without moving: a closed door that opens, a bridge that is
+ * raised, a tile a tower was just built on.
+ *
+ * It is a box in the entity's own frame, so it turns with the entity — unlike the
+ * volume, which cannot, because the volume is the voxel grid and this only marks
+ * cells in one.
+ */
+
+import { defineComponent } from '../../ecs/component';
+import type { Vec3 } from '../../types';
+
+export interface NavObstacleData {
+ /** Half-extents of the blocking box, in world pixels; the Transform is its centre. */
+ halfExtents: Vec3;
+ /** Whether it blocks right now. A door that opens is this field. */
+ enabled: boolean;
+}
+
+export const NavObstacle = defineComponent<NavObstacleData>('NavObstacle', {
+ halfExtents: { x: 50, y: 100, z: 50 },
+ enabled: true,
+}, {
+ fields: {
+ halfExtents: { unit: 'px', category: 'Navigation' },
+ enabled: { category: 'Navigation', tooltip: 'Whether it blocks right now — a door that opens.' },
+ },
+});
diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.ts
index d04627173..7124d8971 100644
--- a/sdk/src/ai/nav/NavPlugin.ts
+++ b/sdk/src/ai/nav/NavPlugin.ts
@@ -28,8 +28,13 @@ import { log } from '../../util/logger';
import { Navigation, Nav } from './Navigation';
import { NavAgent } from './NavAgent';
import { NavVolume } from './NavVolume';
+import { NavObstacle } from './NavObstacle';
import { buildNavMesh } from './navmesh/build';
import { collectNavGeometry, navGeometryReady, type NavGeometry } from './navGeometry';
+import {
+ applyObstaclesToGrid, collectNavObstacles, navObstacleDigest, type NavObstacleBox,
+} from './navObstacles';
+import { NavGrid } from './NavGrid';
import { setupNavDebugDraw } from './NavDebugDraw';
import { advanceAlongPath } from './follow';
@@ -59,6 +64,7 @@ export function bakeVolumes(
nav: Navigation,
geometry: NavGeometryProvider | null,
baked: Set<Entity>,
+ obstacles: readonly NavObstacleBox[] = [],
): void {
if (!geometry) return;
const volumes = world.getEntitiesWithComponents([NavVolume, Transform]);
@@ -82,6 +88,7 @@ export function bakeVolumes(
agentHeight: volume.agentHeight,
agentRadius: volume.agentRadius,
stepHeight: volume.stepHeight,
+ obstacles,
});
nav.setSurface(mesh);
@@ -102,6 +109,59 @@ export function bakeVolumes(
}
}
+/**
+ * Take the obstacles as they are now, and say whether the surface had to be
+ * rebuilt for them. Blocking is a bake input, not a query filter — one marked
+ * after the erosion would leave routes scraping its face — so a door opening is a
+ * bake, throttled to one per NAV_REBAKE_MS. `state` is carried across frames.
+ */
+export function updateObstacles(
+ nav: Navigation, obstacles: readonly NavObstacleBox[], state: ObstacleState, now: number,
+): boolean {
+ const digest = navObstacleDigest(obstacles);
+ const grid = nav.surface instanceof NavGrid ? nav.surface : null;
+ const changed = digest !== state.digest;
+ // A grid the game only just installed has never had the obstacles put on it,
+ // however long they have stood still.
+ const unmarked = grid !== null && grid !== state.grid;
+ if (!changed && !unmarked) return false;
+ if (changed && now - state.at < NAV_REBAKE_MS) {
+ // Something is still moving. Say so ONCE: an obstacle that never settles
+ // rebuilds the world several times a second, which is a scene to fix
+ // rather than a cost to absorb.
+ if (++state.deferred === REBAKE_COMPLAINT) {
+ log.warn('nav', 'a NavObstacle keeps moving, so the navigable world keeps being'
+ + ' rebuilt — an obstacle is for something that blocks and then stops,'
+ + ' not for something that travels');
+ }
+ return false;
+ }
+ state.digest = digest;
+ state.at = now;
+ state.deferred = 0;
+ // A grid blocks by the cell and can be re-marked in place; a mesh has to be
+ // baked again, which is what the caller does with a `true`.
+ if (grid) {
+ applyObstaclesToGrid(grid, obstacles);
+ state.grid = grid;
+ }
+ return changed;
+}
+
+/** What the obstacles were when the world was last built for them. */
+export interface ObstacleState {
+ digest: number;
+ at: number;
+ deferred: number;
+ grid: NavGrid | null;
+}
+
+/** The shortest gap between two rebuilds. A door should shut at once; something
+ * that keeps moving must not take the frame rate with it. */
+const NAV_REBAKE_MS = 200;
+/** How many deferred rebuilds in a row are worth a word about the scene. */
+const REBAKE_COMPLAINT = 8;
+
/** The slice of `World` the nav step needs — lets tests inject a fake. */
export interface NavWorldView {
getEntitiesWithComponents(components: readonly AnyComponentDef[]): readonly Entity[];
@@ -255,6 +315,7 @@ export class NavPlugin implements Plugin {
const runtimes = new Map<Entity, AgentRuntime>();
const baked = new Set<Entity>();
+ const obstacleState: ObstacleState = { digest: 0, at: 0, deferred: 0, grid: null };
app.world.onDespawn((entity: Entity) => {
runtimes.delete(entity);
baked.delete(entity);
@@ -272,13 +333,15 @@ export class NavPlugin implements Plugin {
? (min: Vec3, max: Vec3, layers: number) =>
collectNavGeometry(app.world, { min, max, layers })
: null;
- bakeVolumes(world as NavWorldView, nav, provider, baked);
+ const obstacles = collectNavObstacles(app.world);
+ if (updateObstacles(nav, obstacles, obstacleState, Date.now())) baked.clear();
+ bakeVolumes(world as NavWorldView, nav, provider, baked, obstacles);
stepNavigation(world as NavWorldView, nav, time.delta, runtimes);
},
{
name: 'NavAgentSystem',
touches: {
- reads: [NavVolume._name],
+ reads: [NavVolume._name, NavObstacle._name],
writes: [NavAgent._name, Transform._name, CharacterController3D._name],
},
// Both move an entity; for one carrying both, the path is the
diff --git a/sdk/src/ai/nav/index.ts b/sdk/src/ai/nav/index.ts
index df0b42281..24f24721c 100644
--- a/sdk/src/ai/nav/index.ts
+++ b/sdk/src/ai/nav/index.ts
@@ -24,5 +24,9 @@ export {
export { Navigation, Nav } from './Navigation';
export { NavAgent, type NavAgentData, setNavDestination, stopNavAgent } from './NavAgent';
export { NavVolume, type NavVolumeData } from './NavVolume';
+export { NavObstacle, type NavObstacleData } from './NavObstacle';
+export {
+ collectNavObstacles, navObstacleDigest, applyObstaclesToGrid, type NavObstacleBox,
+} from './navObstacles';
export { NavPlugin, navPlugin } from './NavPlugin';
export { NavDebugDraw, drawNavDebug, type NavDebugDrawConfig } from './NavDebugDraw';
diff --git a/sdk/src/ai/nav/navObstacles.ts b/sdk/src/ai/nav/navObstacles.ts
new file mode 100644
index 000000000..b057a98a6
--- /dev/null
+++ b/sdk/src/ai/nav/navObstacles.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file navObstacles.ts
+ * @brief The boxes a scene currently says are in the way, and a number that
+ * changes when any of them does.
+ *
+ * Blocking is a bake input, not a query filter: an obstacle has to take its
+ * ground away before the erosion, or routes would scrape along its face. So what
+ * a running game needs from this is cheap CHANGE detection — walking a handful of
+ * boxes every frame to find out whether the expensive thing has to happen again.
+ */
+
+import type { Quat, Vec3 } from '../../types';
+import type { World } from '../../ecs/world';
+import { Transform } from '../../ecs/component';
+import { q } from '../../math/quat';
+import { NavObstacle, type NavObstacleData } from './NavObstacle';
+import type { NavGrid } from './NavGrid';
+import type { NavObstacleBox } from './navmesh/compact';
+
+export type { NavObstacleBox };
+
+/** Every obstacle currently blocking, in world space. Disabled ones are absent,
+ * which is what makes a door opening a change of this list. */
+export function collectNavObstacles(world: World): NavObstacleBox[] {
+ const out: NavObstacleBox[] = [];
+ for (const entity of world.getEntitiesWithComponents([NavObstacle, Transform])) {
+ const obstacle = world.get(entity, NavObstacle) as NavObstacleData;
+ if (obstacle.enabled === false) continue;
+ const h = obstacle.halfExtents;
+ if (h.x <= 0 || h.y <= 0 || h.z <= 0) continue;
+ const tf = world.get(entity, Transform);
+ out.push({
+ center: { ...(tf.position as Vec3) },
+ halfExtents: { x: h.x, y: h.y, z: h.z },
+ rotation: { ...(tf.rotation as Quat) },
+ });
+ }
+ return out;
+}
+
+/**
+ * A number that differs whenever the obstacles do — one moved, resized, added,
+ * removed or switched off. Positions are rounded to a tenth of a pixel first, so
+ * a body settling under gravity does not read as a world that keeps changing.
+ */
+export function navObstacleDigest(obstacles: readonly NavObstacleBox[]): number {
+ let hash = 2166136261;
+ const mix = (v: number): void => {
+ hash = Math.imul(hash ^ (Math.round(v * 10) | 0), 16777619);
+ };
+ for (const box of obstacles) {
+ mix(box.center.x); mix(box.center.y); mix(box.center.z);
+ mix(box.halfExtents.x); mix(box.halfExtents.y); mix(box.halfExtents.z);
+ mix(box.rotation.x * 1000); mix(box.rotation.y * 1000);
+ mix(box.rotation.z * 1000); mix(box.rotation.w * 1000);
+ }
+ return hash;
+}
+
+/**
+ * Mark the cells an obstacle is standing on. A grid blocks by the cell, so this
+ * is the whole of what an obstacle does to one — and it is re-marked from scratch
+ * each time, because working out which cells a box has LEFT is the same walk.
+ */
+export function applyObstaclesToGrid(grid: NavGrid, obstacles: readonly NavObstacleBox[]): void {
+ grid.clearObstructions();
+ const cs = grid.cellSize;
+ for (const box of obstacles) {
+ const reach = Math.abs(box.halfExtents.x) + Math.abs(box.halfExtents.y)
+ + Math.abs(box.halfExtents.z);
+ const inverse = { x: -box.rotation.x, y: -box.rotation.y, z: -box.rotation.z, w: box.rotation.w };
+ const gx0 = Math.max(0, Math.ceil((box.center.x - reach - grid.originX) / cs));
+ const gx1 = Math.min(grid.width - 1, Math.floor((box.center.x + reach - grid.originX) / cs));
+ const gy0 = Math.max(0, Math.ceil((box.center.y - reach - grid.originY) / cs));
+ const gy1 = Math.min(grid.height - 1, Math.floor((box.center.y + reach - grid.originY) / cs));
+ for (let gy = gy0; gy <= gy1; gy++) {
+ for (let gx = gx0; gx <= gx1; gx++) {
+ const local = q.rotate(inverse, {
+ x: grid.originX + gx * cs - box.center.x,
+ y: grid.originY + gy * cs - box.center.y,
+ z: grid.originZ - box.center.z,
+ });
+ if (Math.abs(local.x) > box.halfExtents.x) continue;
+ if (Math.abs(local.y) > box.halfExtents.y) continue;
+ if (Math.abs(local.z) > box.halfExtents.z) continue;
+ grid.setObstructed(gx, gy, true);
+ }
+ }
+ }
+}
diff --git a/sdk/src/ai/nav/navmesh/build.ts b/sdk/src/ai/nav/navmesh/build.ts
index 6717f3863..e576ee3b2 100644
--- a/sdk/src/ai/nav/navmesh/build.ts
+++ b/sdk/src/ai/nav/navmesh/build.ts
@@ -23,7 +23,9 @@ import {
filterLowHangingWalkableObstacles, filterLedgeSpans, filterWalkableLowHeightSpans,
} from './heightfield';
import { log } from '../../../util/logger';
-import { NavCompactField, erodeWalkableArea } from './compact';
+import {
+ NavCompactField, erodeWalkableArea, markObstacles, type NavObstacleBox,
+} from './compact';
import { buildRegionsMonotone } from './regions';
import { buildContours } from './contours';
import { buildPolyMesh } from './polymesh';
@@ -57,6 +59,8 @@ export interface BuildNavMeshOptions {
minRegionArea?: number;
/** Corners a polygon may have. Six is the default this is tuned around. */
maxVertsPerPoly?: number;
+ /** Boxes that block without being geometry — see `NavObstacle`. */
+ obstacles?: readonly NavObstacleBox[];
}
export function buildNavMesh(
@@ -90,6 +94,7 @@ export function buildNavMesh(
filterWalkableLowHeightSpans(hf, walkableHeight);
const chf = new NavCompactField(hf, walkableHeight, walkableClimb);
+ if (opts.obstacles?.length) markObstacles(chf, opts.obstacles);
erodeWalkableArea(chf, walkableRadius);
buildRegionsMonotone(chf, minRegionArea);
diff --git a/sdk/src/ai/nav/navmesh/compact.ts b/sdk/src/ai/nav/navmesh/compact.ts
index 97a93f5fb..730955dcc 100644
--- a/sdk/src/ai/nav/navmesh/compact.ts
+++ b/sdk/src/ai/nav/navmesh/compact.ts
@@ -18,7 +18,8 @@
import {
DIR_X, DIR_Z, NAV_AREA_NULL, NAV_SPAN_MAX_HEIGHT, type NavHeightfield,
} from './heightfield';
-import type { Vec3 } from '../../../types';
+import type { Quat, Vec3 } from '../../../types';
+import { q } from '../../../math/quat';
/** A direction with no reachable neighbour. Six bits per direction, so 63 is the
* one value that cannot also be a span offset. */
@@ -148,6 +149,51 @@ export class NavCompactField {
}
}
+/** A box that blocks, in world space, turned by its own rotation. */
+export interface NavObstacleBox {
+ center: Vec3;
+ halfExtents: Vec3;
+ rotation: Quat;
+}
+
+/**
+ * Take the ground inside each box away, BEFORE the erosion — so the mesh pulls
+ * back from an obstacle by the agent's width, exactly as it does from a wall. An
+ * obstacle marked after eroding would leave routes scraping along its face.
+ */
+export function markObstacles(chf: NavCompactField, obstacles: readonly NavObstacleBox[]): void {
+ const cs = chf.cellSize;
+ const ch = chf.cellHeight;
+ for (const box of obstacles) {
+ const reach = Math.abs(box.halfExtents.x) + Math.abs(box.halfExtents.y)
+ + Math.abs(box.halfExtents.z);
+ const x0 = Math.max(0, Math.floor((box.center.x - reach - chf.min.x) / cs));
+ const x1 = Math.min(chf.width - 1, Math.ceil((box.center.x + reach - chf.min.x) / cs));
+ const z0 = Math.max(0, Math.floor((box.center.z - reach - chf.min.z) / cs));
+ const z1 = Math.min(chf.depth - 1, Math.ceil((box.center.z + reach - chf.min.z) / cs));
+ const inverse = { x: -box.rotation.x, y: -box.rotation.y, z: -box.rotation.z, w: box.rotation.w };
+
+ for (let z = z0; z <= z1; z++) {
+ for (let x = x0; x <= x1; x++) {
+ const c = x + z * chf.width;
+ const start = chf.cellIndex[c]!;
+ const end = start + chf.cellCount[c]!;
+ const wx = chf.min.x + (x + 0.5) * cs - box.center.x;
+ const wz = chf.min.z + (z + 0.5) * cs - box.center.z;
+ for (let i = start; i < end; i++) {
+ if (chf.areas[i] === NAV_AREA_NULL) continue;
+ const wy = chf.min.y + chf.y[i]! * ch - box.center.y;
+ const local = q.rotate(inverse, { x: wx, y: wy, z: wz });
+ if (Math.abs(local.x) > box.halfExtents.x) continue;
+ if (Math.abs(local.y) > box.halfExtents.y) continue;
+ if (Math.abs(local.z) > box.halfExtents.z) continue;
+ chf.areas[i] = NAV_AREA_NULL;
+ }
+ }
+ }
+ }
+}
+
/**
* Take `radius` cells off every edge of the walkable world. An agent is a body:
* planning it down the exact edge of a walkway puts half of it over the drop.
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 3ab50a729..ac0a31fbb 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -673,6 +673,10 @@ export {
Nav,
NavAgent,
NavVolume,
+ NavObstacle,
+ collectNavObstacles,
+ navObstacleDigest,
+ applyObstaclesToGrid,
setNavDestination,
stopNavAgent,
NavPlugin,
@@ -692,6 +696,8 @@ export {
type BuildNavGridOptions,
type NavAgentData,
type NavVolumeData,
+ type NavObstacleData,
+ type NavObstacleBox,
type NavDebugDrawConfig,
} from './ai';
diff --git a/sdk/tests/nav-obstacles.test.ts b/sdk/tests/nav-obstacles.test.ts
new file mode 100644
index 000000000..fca1749ff
--- /dev/null
+++ b/sdk/tests/nav-obstacles.test.ts
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Things that block without being geometry — a door, a gate, a placed tower.
+ *
+ * Blocking is a BAKE input, not a filter over the answer: an obstacle marked
+ * after the walkable area was eroded would leave routes scraping along its face.
+ * So most of what is claimed here is about WHEN it is applied, and the rest is
+ * about the cost of applying it again.
+ */
+import { describe, it, expect } from 'vitest';
+import { buildNavMesh } from '../src/ai/nav/navmesh/build';
+import { NavGrid } from '../src/ai/nav/NavGrid';
+import { Navigation } from '../src/ai/nav/Navigation';
+import { updateObstacles, type ObstacleState } from '../src/ai/nav/NavPlugin';
+import { applyObstaclesToGrid, navObstacleDigest } from '../src/ai/nav/navObstacles';
+import type { NavObstacleBox } from '../src/ai/nav/navmesh/compact';
+
+const NO_TURN = { x: 0, y: 0, z: 0, w: 1 };
+const QUARTER_TURN = { x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 };
+
+/** A floor slab as world triangles, wide enough to have room around a blocker. */
+function floor(half = 600): { verts: Float32Array; indices: Uint32Array } {
+ const verts: number[] = [];
+ for (const [x, z] of [[-half, -half], [half, -half], [half, half], [-half, half]]) {
+ verts.push(x!, 0, z!);
+ }
+ return { verts: Float32Array.from(verts), indices: Uint32Array.from([0, 2, 1, 0, 3, 2]) };
+}
+
+const BOX = {
+ min: { x: -700, y: -100, z: -700 },
+ max: { x: 700, y: 400, z: 700 },
+ cellSize: 25,
+ cellHeight: 10,
+ agentHeight: 180,
+ agentRadius: 50,
+ stepHeight: 40,
+};
+
+const bake = (obstacles: NavObstacleBox[]) => {
+ const f = floor();
+ return buildNavMesh(f.verts, f.indices, { ...BOX, obstacles });
+};
+
+const blocker = (over: Partial<NavObstacleBox> = {}): NavObstacleBox => ({
+ center: { x: 0, y: 0, z: 0 },
+ halfExtents: { x: 100, y: 200, z: 100 },
+ rotation: NO_TURN,
+ ...over,
+});
+
+describe('an obstacle in a baked mesh', () => {
+ it('takes the ground it stands on out of the mesh', () => {
+ expect(bake([]).findPoly({ x: 0, y: 0, z: 0 })).toBeGreaterThanOrEqual(0);
+ expect(bake([blocker()]).findPoly({ x: 0, y: 0, z: 0 })).toBe(-1);
+ });
+
+ // The whole reason it is a bake input. The hole it leaves has to be the box
+ // PLUS the agent's width, or an agent 50 wide is routed to stand with its
+ // centre against the face of something it would be standing inside.
+ it('leaves a hole the agent width wider than itself', () => {
+ const mesh = bake([blocker()]);
+ let nearest = Infinity;
+ for (let i = 0; i < mesh.verts.length; i += 3) {
+ const reach = Math.max(Math.abs(mesh.verts[i]!), Math.abs(mesh.verts[i + 2]!));
+ if (reach > 400) continue; // the floor's own outline, not the hole's
+ nearest = Math.min(nearest, reach);
+ }
+ // 100 of box + 50 of agent, less a cell of voxel rounding.
+ expect(nearest).toBeGreaterThanOrEqual(125);
+ });
+
+ it('blocks along its own axes, not the world', () => {
+ const long = blocker({ halfExtents: { x: 400, y: 200, z: 60 } });
+ const across = bake([long]);
+ const turned = bake([{ ...long, rotation: QUARTER_TURN }]);
+ // Unturned it lies along x; a quarter turn puts the same slab along z.
+ expect(across.findPoly({ x: 300, y: 0, z: 0 })).toBe(-1);
+ expect(across.findPoly({ x: 0, y: 0, z: 300 })).toBeGreaterThanOrEqual(0);
+ expect(turned.findPoly({ x: 300, y: 0, z: 0 })).toBeGreaterThanOrEqual(0);
+ expect(turned.findPoly({ x: 0, y: 0, z: 300 })).toBe(-1);
+ });
+
+ // A door across a corridor is the case this exists for: the route is there
+ // when it is open and gone when it is shut, with nothing else changed.
+ it('closes a route when it blocks and gives it back when it does not', () => {
+ const wall = blocker({ halfExtents: { x: 40, y: 200, z: 700 } });
+ const shut = bake([wall]);
+ const open = bake([]);
+ const from = { x: -500, y: 0, z: 0 };
+ const to = { x: 500, y: 0, z: 0 };
+ expect(open.findWorldPath(from, to)).not.toBeNull();
+ expect(shut.findWorldPath(from, to)).toBeNull();
+ });
+});
+
+describe('an obstacle on a grid', () => {
+ const open = (): NavGrid => new NavGrid({ width: 9, height: 9, cellSize: 10 });
+
+ it('blocks the cells it stands on and no others', () => {
+ const grid = open();
+ applyObstaclesToGrid(grid, [blocker({
+ center: { x: 40, y: 40, z: 0 }, halfExtents: { x: 10, y: 10, z: 10 },
+ })]);
+ expect(grid.isWalkable(4, 4)).toBe(false);
+ expect(grid.isWalkable(3, 4)).toBe(false);
+ expect(grid.isWalkable(2, 4)).toBe(true);
+ });
+
+ // A door that shuts and opens again must give back exactly the ground that was
+ // there — including the ground the map itself said was not walkable.
+ it('gives back the map underneath when it is lifted', () => {
+ const grid = open();
+ grid.setWalkable(4, 4, false);
+ const box = [blocker({ center: { x: 30, y: 30, z: 0 }, halfExtents: { x: 20, y: 20, z: 10 } })];
+ applyObstaclesToGrid(grid, box);
+ expect(grid.isWalkable(3, 3)).toBe(false);
+ applyObstaclesToGrid(grid, []);
+ expect(grid.isWalkable(3, 3)).toBe(true);
+ expect(grid.isWalkable(4, 4)).toBe(false); // the map's own wall, still there
+ });
+
+ it('does not answer for a grid lying at another depth', () => {
+ const grid = new NavGrid({ width: 9, height: 9, cellSize: 10, origin: { x: 0, y: 0, z: 500 } });
+ applyObstaclesToGrid(grid, [blocker({ center: { x: 40, y: 40, z: 0 } })]);
+ expect(grid.isWalkable(4, 4)).toBe(true);
+ });
+});
+
+describe('updateObstacles', () => {
+ const state = (): ObstacleState => ({ digest: navObstacleDigest([]), at: 0, deferred: 0, grid: null });
+
+ it('rebuilds nothing while nothing has changed', () => {
+ const nav = new Navigation();
+ nav.setSurface(new NavGrid({ width: 4, height: 4, cellSize: 10 }));
+ const s = state();
+ expect(updateObstacles(nav, [], s, 10_000)).toBe(false);
+ });
+
+ it('rebuilds when an obstacle appears, and marks the grid', () => {
+ const nav = new Navigation();
+ const grid = new NavGrid({ width: 9, height: 9, cellSize: 10 });
+ nav.setSurface(grid);
+ const s = state();
+ expect(updateObstacles(nav, [blocker({ center: { x: 40, y: 40, z: 0 } })], s, 10_000)).toBe(true);
+ expect(grid.isWalkable(4, 4)).toBe(false);
+ });
+
+ // A rebuild is the most expensive thing a running game can ask of navigation,
+ // so something that changes every frame must not get one every frame.
+ it('will not rebuild twice inside its own interval', () => {
+ const nav = new Navigation();
+ nav.setSurface(new NavGrid({ width: 9, height: 9, cellSize: 10 }));
+ const s = state();
+ expect(updateObstacles(nav, [blocker()], s, 10_000)).toBe(true);
+ expect(updateObstacles(nav, [blocker({ center: { x: 10, y: 0, z: 0 } })], s, 10_050)).toBe(false);
+ expect(updateObstacles(nav, [blocker({ center: { x: 10, y: 0, z: 0 } })], s, 10_400)).toBe(true);
+ });
+
+ // The obstacles were already standing there; the grid is the new thing.
+ it('marks a grid the game has only just installed', () => {
+ const nav = new Navigation();
+ const s = state();
+ const obstacles = [blocker({ center: { x: 40, y: 40, z: 0 } })];
+ updateObstacles(nav, obstacles, s, 10_000);
+ const grid = new NavGrid({ width: 9, height: 9, cellSize: 10 });
+ nav.setSurface(grid);
+ updateObstacles(nav, obstacles, s, 10_050);
+ expect(grid.isWalkable(4, 4)).toBe(false);
+ });
+});