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): ground can cost something
esengine97d1846c7ff1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0cca12357..6942e4361 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.+- **Ground can cost something.** The mesh answers where an agent CAN walk;+ `NavArea` is where a scene says what it would rather walk on. A box, a `cost`+ against 1 for open ground, and routes that go out of their way for a road at+ half price and round a swamp at four times. It never BLOCKS — an agent with+ nowhere else to go wades through, which is the difference between a swamp and a+ fence, and the difference between this and `NavObstacle`.++ Both surfaces answer to it: a mesh gives every polygon the area its patch marked+ and multiplies each step by what that area costs, a grid prices the cells. Which+ patch a polygon belongs to is baked; what the patch costs is read fresh every+ search, so a price can change for nothing and only moving one rebuilds anything.+ The string-pull respects it too: a shortcut may not cross ground priced+ differently from the ground it starts on, because straightening a route back+ through the mud it had just gone round undoes the only reason it went round.+- **An agent sent somewhere it cannot reach walks to the door.** `findWorldPath`and `findPath` returned nothing at all when the goal could not be reached, so anagent whose target was behind a shut door — or momentarily on the far side ofdiff --git a/desktop b/desktopindex cc28fd94f..b663c08eb 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit cc28fd94ff07706b4affbdee2a8fd8bd0a5215f0+Subproject commit b663c08eb570c1ce98d1047103ea606fb13cc6e1diff --git a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx b/docs/astro/src/content/docs/gameplay/ai/navigation.mdxindex 155a04622..f9a245639 100644--- a/docs/astro/src/content/docs/gameplay/ai/navigation.mdx+++ b/docs/astro/src/content/docs/gameplay/ai/navigation.mdx@@ -133,6 +133,33 @@ one is cheap to animate and the other is not.itself halfway.</Aside>+### Ground that costs something++The mesh answers where an agent CAN walk. **`NavArea`** is where a scene says what+it would rather walk on:++| `NavArea` field | Default | Description |+|---|---|---|+| `halfExtents` | `200, 100, 200` | Half the box, in world pixels; the Transform is its centre. It turns with the entity. |+| `cost` | `3` | What a unit of distance inside it costs, against `1` for open ground. |+| `enabled` | `true` | Whether the price applies right now. |++Under 1 is preferred and over 1 is avoided — a road at half price is worth going+out of the way for, a swamp at four times is walked round if there is any way+round. It never **blocks**: an agent with nowhere else to go wades through, which+is the difference between a swamp and a fence.++Moving or resizing a patch rebuilds the navigable world, the way an obstacle does.+Changing its `cost` does not: the mesh carries which patch a polygon belongs to,+and what that patch costs is read fresh on every search.++<Aside type="note">+ **The string-pull respects it.** A route over a grid is pulled taut afterwards,+ and straightening one back through the mud it had just gone round would undo the+ only reason it went round — so a shortcut may not cross ground priced+ differently from the ground it starts on.+</Aside>+### Doors, gates and things placed in the wayAnything with a collider already blocks, because the mesh is baked from thediff --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 1c9f62744..9cebd88c2 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@@ -117,6 +117,27 @@ export const setupNav = defineSystem([Res(Nav)], (nav) => {搁在半路上。</Aside>+### 有代价的地面++网格回答的是 agent **能**走哪。**`NavArea`** 是场景说「它更愿意走哪」的地方:++| `NavArea` 字段 | 默认 | 说明 |+|---|---|---|+| `halfExtents` | `200, 100, 200` | 盒子的半尺寸,单位世界像素;实体的 Transform 是它的中心。它会跟着实体转。 |+| `cost` | `3` | 盒子里每单位距离的代价,开阔地面是 `1`。 |+| `enabled` | `true` | 这个价现在算不算数。 |++小于 1 会被优先选择,大于 1 会被躲开——半价的路值得绕远去走,四倍价的沼泽只要有路绕就绕开。+它**永远不阻挡**:无处可去的 agent 会趟过去,这就是沼泽和栅栏的区别。++移动或改变一块地的尺寸会重建可走世界,和障碍一样。改它的 `cost` 不会:网格记住的是多边形+属于哪一块地,而那块地值多少钱是每次搜索现读的。++<Aside type="note">+ **拉直也认它。**格子上的路线事后会被拉直,而把一条刚绕开泥地的路线又拉直回泥地里,+ 等于把它绕路的唯一理由撤销了——所以抄近道不能跨过和起点价格不同的地面。+</Aside>+### 门、闸,以及被放在路上的东西任何带碰撞体的东西本来就会挡路——网格就是从场景的碰撞几何烘出来的。**`NavObstacle`**diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 8f60b5f09..f22b4a7a0 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": 1623,+ "experimental": 1629,"deprecated": 3},- "total": 1809,+ "total": 1815,"subsystems": [{"id": "ecs",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 9a98440e3..a1207a0a5 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -147,6 +147,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {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' },NavLink: { category: 'gameplay', summary: 'A way between two places the ground does not join \u2014 a drop, a ladder, a plank.', doc: 'gameplay/ai/navigation' },+ NavArea: { category: 'gameplay', summary: 'A box of ground that costs more or less to cross \u2014 mud, water, a road.', 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.jsonindex 5e235dbfc..d6d2099b7 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1989,6 +1989,35 @@"targetZ"]},+ {+ "name": "NavArea",+ "source": "ts",+ "fields": [+ {+ "key": "halfExtents",+ "type": "Vec3",+ "default": "(200, 100, 200)"+ },+ {+ "key": "cost",+ "type": "number",+ "default": "3",+ "doc": "What crossing it costs against 1 for open ground.",+ "range": "≥ 0"+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ }+ ],+ "animatable": [+ "halfExtents.x",+ "halfExtents.y",+ "halfExtents.z",+ "cost"+ ]+ },{"name": "NavLink","source": "ts",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex d9b9eecdb..801b8fe70 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 · 1509 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1515 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1345,6 +1345,7 @@ width: number```agentHeight: number | undefinedagentRadius: number | undefined+areas: readonly NavAreaBox[] | undefinedcellHeight: numbercellSize: numberlinks: readonly NavLinkSegment[] | undefined@@ -4694,6 +4695,26 @@ targetY: numbertargetZ: number```+## NavArea — const @experimental+```+ComponentDef<NavAreaData>+```++## NavAreaBox — interface @experimental+```+area: number+center: Vec3+halfExtents: Vec3+rotation: Quat+```++## NavAreaData — interface @experimental+```+cost: number+enabled: boolean+halfExtents: Vec3+```+## NavDebugDraw — const @experimental```ResourceDef<NavDebugDrawConfig>@@ -4718,8 +4739,10 @@ verts: Float32Array<ArrayBufferLike>```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec3+clearCosts: () => voidclearObstructions: () => voidclearanceAt: (gx: number, gy: number) => number+costAt: (gx: number, gy: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullheight: number@@ -4731,6 +4754,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: numberoriginX: numberoriginY: numberoriginZ: number+setCost: (gx: number, gy: number, cost: number) => voidsetObstructed: (gx: number, gy: number, obstructed: boolean) => voidsetWalkable: (gx: number, gy: number, walkable: boolean) => voidup: Vec3@@ -4775,9 +4799,11 @@ start: Vec3## NavMesh — class @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>connect: (segments: readonly NavLinkSegment[]) => voidcontains: (p: number, x: number, z: number) => booleancorner: (p: number, i: number, out: Vec3) => Vec3+costOf: (p: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindPoly: (p: NavPoint, out?: Vec3, snap?: number) => numberfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null@@ -4788,6 +4814,7 @@ maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: numberpolys: Int32Array<ArrayBufferLike>+setAreaCost: (area: number, cost: number) => voidsnapDistance: numberup: Vec3vertexCount: (p: number) => number@@ -4800,6 +4827,7 @@ static prototype: NavMesh## NavMeshData — interface @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: number@@ -9469,6 +9497,11 @@ AnimationPlugin(def: AnimatorControllerDef): AnimatorEdge[]```+## applyAreasToGrid — function @experimental+```+(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void+```+## applyAssetRefResolvers — function @experimental```(app: App, resolveRef: (ref: string) => string): void@@ -9774,6 +9807,11 @@ BtPlugin(): boolean```+## collectNavAreas — function @experimental+```+(world: World): Array<NavAreaBox & { cost: number; }>+```+## collectNavGeometry — function @experimental```(world: World, opts: CollectNavGeometryOptions): NavGeometry@@ -11039,6 +11077,11 @@ Mesh2DPlugin(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition```+## navAreaDigest — function @experimental+```+(areas: ReadonlyArray<NavAreaBox>): number+```+## navGeometryReady — function @experimental```(world: World, layers?: number): booleandiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex b581d7c3b..0cdc2dc6f 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 · 1528 experimental · 3 deprecated+Symbols: 113 public · 71 beta · 1534 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1345,6 +1345,7 @@ width: number```agentHeight: number | undefinedagentRadius: number | undefined+areas: readonly NavAreaBox[] | undefinedcellHeight: numbercellSize: numberlinks: readonly NavLinkSegment[] | undefined@@ -4872,6 +4873,26 @@ targetY: numbertargetZ: number```+## NavArea — const @experimental+```+ComponentDef<NavAreaData>+```++## NavAreaBox — interface @experimental+```+area: number+center: Vec3+halfExtents: Vec3+rotation: Quat+```++## NavAreaData — interface @experimental+```+cost: number+enabled: boolean+halfExtents: Vec3+```+## NavDebugDraw — const @experimental```ResourceDef<NavDebugDrawConfig>@@ -4896,8 +4917,10 @@ verts: Float32Array<ArrayBufferLike>```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec3+clearCosts: () => voidclearObstructions: () => voidclearanceAt: (gx: number, gy: number) => number+costAt: (gx: number, gy: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullheight: number@@ -4909,6 +4932,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: numberoriginX: numberoriginY: numberoriginZ: number+setCost: (gx: number, gy: number, cost: number) => voidsetObstructed: (gx: number, gy: number, obstructed: boolean) => voidsetWalkable: (gx: number, gy: number, walkable: boolean) => voidup: Vec3@@ -4953,9 +4977,11 @@ start: Vec3## NavMesh — class @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>connect: (segments: readonly NavLinkSegment[]) => voidcontains: (p: number, x: number, z: number) => booleancorner: (p: number, i: number, out: Vec3) => Vec3+costOf: (p: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindPoly: (p: NavPoint, out?: Vec3, snap?: number) => numberfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null@@ -4966,6 +4992,7 @@ maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: numberpolys: Int32Array<ArrayBufferLike>+setAreaCost: (area: number, cost: number) => voidsnapDistance: numberup: Vec3vertexCount: (p: number) => number@@ -4978,6 +5005,7 @@ static prototype: NavMesh## NavMeshData — interface @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: number@@ -9662,6 +9690,11 @@ AnimationPlugin(def: AnimatorControllerDef): AnimatorEdge[]```+## applyAreasToGrid — function @experimental+```+(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void+```+## applyAssetRefResolvers — function @experimental```(app: App, resolveRef: (ref: string) => string): void@@ -9982,6 +10015,11 @@ BtPlugin(): boolean```+## collectNavAreas — function @experimental+```+(world: World): Array<NavAreaBox & { cost: number; }>+```+## collectNavGeometry — function @experimental```(world: World, opts: CollectNavGeometryOptions): NavGeometry@@ -11282,6 +11320,11 @@ Mesh2DPlugin(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition```+## navAreaDigest — function @experimental+```+(areas: ReadonlyArray<NavAreaBox>): number+```+## navGeometryReady — function @experimental```(world: World, layers?: number): booleandiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 532bd6706..df88225f2 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 · 1508 experimental · 3 deprecated+Symbols: 113 public · 68 beta · 1514 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1340,6 +1340,7 @@ width: number```agentHeight: number | undefinedagentRadius: number | undefined+areas: readonly NavAreaBox[] | undefinedcellHeight: numbercellSize: numberlinks: readonly NavLinkSegment[] | undefined@@ -4689,6 +4690,26 @@ targetY: numbertargetZ: number```+## NavArea — const @experimental+```+ComponentDef<NavAreaData>+```++## NavAreaBox — interface @experimental+```+area: number+center: Vec3+halfExtents: Vec3+rotation: Quat+```++## NavAreaData — interface @experimental+```+cost: number+enabled: boolean+halfExtents: Vec3+```+## NavDebugDraw — const @experimental```ResourceDef<NavDebugDrawConfig>@@ -4713,8 +4734,10 @@ verts: Float32Array<ArrayBufferLike>```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec3+clearCosts: () => voidclearObstructions: () => voidclearanceAt: (gx: number, gy: number) => number+costAt: (gx: number, gy: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullheight: number@@ -4726,6 +4749,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: numberoriginX: numberoriginY: numberoriginZ: number+setCost: (gx: number, gy: number, cost: number) => voidsetObstructed: (gx: number, gy: number, obstructed: boolean) => voidsetWalkable: (gx: number, gy: number, walkable: boolean) => voidup: Vec3@@ -4770,9 +4794,11 @@ start: Vec3## NavMesh — class @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>connect: (segments: readonly NavLinkSegment[]) => voidcontains: (p: number, x: number, z: number) => booleancorner: (p: number, i: number, out: Vec3) => Vec3+costOf: (p: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindPoly: (p: NavPoint, out?: Vec3, snap?: number) => numberfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null@@ -4783,6 +4809,7 @@ maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: numberpolys: Int32Array<ArrayBufferLike>+setAreaCost: (area: number, cost: number) => voidsnapDistance: numberup: Vec3vertexCount: (p: number) => number@@ -4795,6 +4822,7 @@ static prototype: NavMesh## NavMeshData — interface @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: number@@ -9464,6 +9492,11 @@ AnimationPlugin(def: AnimatorControllerDef): AnimatorEdge[]```+## applyAreasToGrid — function @experimental+```+(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void+```+## applyAssetRefResolvers — function @experimental```(app: App, resolveRef: (ref: string) => string): void@@ -9769,6 +9802,11 @@ BtPlugin(): boolean```+## collectNavAreas — function @experimental+```+(world: World): Array<NavAreaBox & { cost: number; }>+```+## collectNavGeometry — function @experimental```(world: World, opts: CollectNavGeometryOptions): NavGeometry@@ -11039,6 +11077,11 @@ Mesh2DPlugin(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition```+## navAreaDigest — function @experimental+```+(areas: ReadonlyArray<NavAreaBox>): number+```+## navGeometryReady — function @experimental```(world: World, layers?: number): booleandiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 019908493..652c3657c 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 · 1529 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1535 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1340,6 +1340,7 @@ width: number```agentHeight: number | undefinedagentRadius: number | undefined+areas: readonly NavAreaBox[] | undefinedcellHeight: numbercellSize: numberlinks: readonly NavLinkSegment[] | undefined@@ -4934,6 +4935,26 @@ targetY: numbertargetZ: number```+## NavArea — const @experimental+```+ComponentDef<NavAreaData>+```++## NavAreaBox — interface @experimental+```+area: number+center: Vec3+halfExtents: Vec3+rotation: Quat+```++## NavAreaData — interface @experimental+```+cost: number+enabled: boolean+halfExtents: Vec3+```+## NavDebugDraw — const @experimental```ResourceDef<NavDebugDrawConfig>@@ -4958,8 +4979,10 @@ verts: Float32Array<ArrayBufferLike>```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec3+clearCosts: () => voidclearObstructions: () => voidclearanceAt: (gx: number, gy: number) => number+costAt: (gx: number, gy: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullheight: number@@ -4971,6 +4994,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: numberoriginX: numberoriginY: numberoriginZ: number+setCost: (gx: number, gy: number, cost: number) => voidsetObstructed: (gx: number, gy: number, obstructed: boolean) => voidsetWalkable: (gx: number, gy: number, walkable: boolean) => voidup: Vec3@@ -5015,9 +5039,11 @@ start: Vec3## NavMesh — class @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>connect: (segments: readonly NavLinkSegment[]) => voidcontains: (p: number, x: number, z: number) => booleancorner: (p: number, i: number, out: Vec3) => Vec3+costOf: (p: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindPoly: (p: NavPoint, out?: Vec3, snap?: number) => numberfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null@@ -5028,6 +5054,7 @@ maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: numberpolys: Int32Array<ArrayBufferLike>+setAreaCost: (area: number, cost: number) => voidsnapDistance: numberup: Vec3vertexCount: (p: number) => number@@ -5040,6 +5067,7 @@ static prototype: NavMesh## NavMeshData — interface @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: number@@ -9709,6 +9737,11 @@ AnimationPlugin(def: AnimatorControllerDef): AnimatorEdge[]```+## applyAreasToGrid — function @experimental+```+(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void+```+## applyAssetRefResolvers — function @experimental```(app: App, resolveRef: (ref: string) => string): void@@ -10014,6 +10047,11 @@ BtPlugin(): boolean```+## collectNavAreas — function @experimental+```+(world: World): Array<NavAreaBox & { cost: number; }>+```+## collectNavGeometry — function @experimental```(world: World, opts: CollectNavGeometryOptions): NavGeometry@@ -11294,6 +11332,11 @@ Mesh2DPlugin(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition```+## navAreaDigest — function @experimental+```+(areas: ReadonlyArray<NavAreaBox>): number+```+## navGeometryReady — function @experimental```(world: World, layers?: number): booleandiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 593a46c1f..0229bcde1 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 · 1519 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1525 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1340,6 +1340,7 @@ width: number```agentHeight: number | undefinedagentRadius: number | undefined+areas: readonly NavAreaBox[] | undefinedcellHeight: numbercellSize: numberlinks: readonly NavLinkSegment[] | undefined@@ -4696,6 +4697,26 @@ targetY: numbertargetZ: number```+## NavArea — const @experimental+```+ComponentDef<NavAreaData>+```++## NavAreaBox — interface @experimental+```+area: number+center: Vec3+halfExtents: Vec3+rotation: Quat+```++## NavAreaData — interface @experimental+```+cost: number+enabled: boolean+halfExtents: Vec3+```+## NavDebugDraw — const @experimental```ResourceDef<NavDebugDrawConfig>@@ -4720,8 +4741,10 @@ verts: Float32Array<ArrayBufferLike>```cellSize: numbercellToWorld: (gx: number, gy: number) => Vec3+clearCosts: () => voidclearObstructions: () => voidclearanceAt: (gx: number, gy: number) => number+costAt: (gx: number, gy: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | nullheight: number@@ -4733,6 +4756,7 @@ nearestWalkable: (gx: number, gy: number, maxRadius?: number, clearance?: numberoriginX: numberoriginY: numberoriginZ: number+setCost: (gx: number, gy: number, cost: number) => voidsetObstructed: (gx: number, gy: number, obstructed: boolean) => voidsetWalkable: (gx: number, gy: number, walkable: boolean) => voidup: Vec3@@ -4777,9 +4801,11 @@ start: Vec3## NavMesh — class @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>connect: (segments: readonly NavLinkSegment[]) => voidcontains: (p: number, x: number, z: number) => booleancorner: (p: number, i: number, out: Vec3) => Vec3+costOf: (p: number) => numberdescribe: (sink: NavSurfaceSink) => voidfindPoly: (p: NavPoint, out?: Vec3, snap?: number) => numberfindWorldPath: (from: NavPoint, to: NavPoint, opts?: NavQueryOptions) => Vec3[] | null@@ -4790,6 +4816,7 @@ maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: numberpolys: Int32Array<ArrayBufferLike>+setAreaCost: (area: number, cost: number) => voidsnapDistance: numberup: Vec3vertexCount: (p: number) => number@@ -4802,6 +4829,7 @@ static prototype: NavMesh## NavMeshData — interface @experimental```agentRadius: number+areas: Uint8Array<ArrayBufferLike>maxVertsPerPoly: numberneis: Int32Array<ArrayBufferLike>polyCount: number@@ -9491,6 +9519,11 @@ AnimationPlugin(def: AnimatorControllerDef): AnimatorEdge[]```+## applyAreasToGrid — function @experimental+```+(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void+```+## applyAssetRefResolvers — function @experimental```(app: App, resolveRef: (ref: string) => string): void@@ -9796,6 +9829,11 @@ BtPlugin(): boolean```+## collectNavAreas — function @experimental+```+(world: World): Array<NavAreaBox & { cost: number; }>+```+## collectNavGeometry — function @experimental```(world: World, opts: CollectNavGeometryOptions): NavGeometry@@ -11066,6 +11104,11 @@ Mesh2DPlugin(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition```+## navAreaDigest — function @experimental+```+(areas: ReadonlyArray<NavAreaBox>): number+```+## navGeometryReady — function @experimental```(world: World, layers?: number): booleandiff --git a/sdk/src/ai/nav/NavArea.ts b/sdk/src/ai/nav/NavArea.tsnew file mode 100644index 000000000..a6642b0f1--- /dev/null+++ b/sdk/src/ai/nav/NavArea.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file NavArea.ts+ * @brief A box of ground that costs more or less to cross — mud, water, a road.+ *+ * The mesh answers where an agent CAN walk. This is where a scene says what it+ * would rather walk on: a route through a marked box is charged its `cost` per+ * unit, so a road at half price is taken the long way round and a swamp at four+ * times is walked round entirely if there is any way round at all.+ *+ * It does not block. A cost high enough to be a wall is still a cost — an agent+ * with nowhere else to go wades through, which is what a swamp is and what+ * {@link NavObstacle} is not.+ */++import { defineComponent } from '../../ecs/component';+import type { Vec3 } from '../../types';++export interface NavAreaData {+ /** Half-extents of the box, in world pixels; the Transform is its centre. */+ halfExtents: Vec3;+ /**+ * What a unit of distance inside it costs, against 1 for open ground. Under 1+ * is preferred, over 1 is avoided; 0 or less is not a shortcut but a mistake,+ * and reads as free ground.+ */+ cost: number;+ enabled: boolean;+}++export const NavArea = defineComponent<NavAreaData>('NavArea', {+ halfExtents: { x: 200, y: 100, z: 200 },+ cost: 3,+ enabled: true,+}, {+ fields: {+ halfExtents: { unit: 'px', category: 'Navigation' },+ cost: { min: 0, category: 'Navigation', tooltip: 'What crossing it costs against 1 for open ground.' },+ enabled: { category: 'Navigation' },+ },+});diff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.tsindex 138a040bd..c15c0a808 100644--- a/sdk/src/ai/nav/NavGrid.ts+++ b/sdk/src/ai/nav/NavGrid.ts@@ -65,6 +65,8 @@ export class NavGrid implements NavSurface {/** 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;+ /** What crossing each cell costs, or null while it all costs the same. */+ private cost_: Float32Array | null = null;constructor(opts: NavGridOptions) {this.width = opts.width;@@ -125,6 +127,31 @@ export class NavGrid implements NavSurface {this.clearance_ = null;}+ /**+ * What crossing a cell costs, against 1 for open ground. Cheap makes a route+ * prefer it and dear makes it go round; it never blocks, because a price an+ * agent will not pay when there is another way is still one it pays when+ * there is not.+ */+ costAt(gx: number, gy: number): number {+ if (!this.cost_ || !this.inBounds(gx, gy)) return 1;+ return this.cost_[gy * this.width + gx]!;+ }++ setCost(gx: number, gy: number, cost: number): void {+ if (!this.inBounds(gx, gy)) return;+ if (!this.cost_) {+ if (cost === 1) return;+ this.cost_ = new Float32Array(this.width * this.height).fill(1);+ }+ this.cost_[gy * this.width + gx] = cost > 0 ? cost : 1;+ }++ /** Put every cell back to open-ground price, before the areas are re-marked. */+ clearCosts(): void {+ this.cost_?.fill(1);+ }+/*** 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 thediff --git a/sdk/src/ai/nav/NavMesh.ts b/sdk/src/ai/nav/NavMesh.tsindex 24695f1d2..d4391d01c 100644--- a/sdk/src/ai/nav/NavMesh.ts+++ b/sdk/src/ai/nav/NavMesh.ts@@ -58,6 +58,8 @@ export interface NavMeshData {* ever off by the grid it was voxelised on plus the erosion.*/snapDistance: number;+ /** What crossing each polygon costs, as an area id the cost table is read by. */+ areas: Uint8Array;/*** How far above or below a point a floor may be and still be the one it* stands on. Over more than one floor the nearest wins; this is what makes a@@ -84,6 +86,10 @@ export class NavMesh implements NavSurface {readonly agentRadius: number;readonly snapDistance: number;readonly verticalReach: number;+ readonly areas: Uint8Array;+ /** What a unit of distance costs in each area, 1 for open ground. Read every+ * search rather than baked in, so a swamp can dry out without a rebuild. */+ private areaCost_ = new Float32Array(256).fill(1);/** Ways between polygons that share no edge, both directions listed separately. */private links_: NavLinkEdge[] = [];private linksFrom_: Map<number, number[]> = new Map();@@ -107,6 +113,7 @@ export class NavMesh implements NavSurface {this.agentRadius = data.agentRadius;this.snapDistance = data.snapDistance;this.verticalReach = data.verticalReach;+ this.areas = data.areas;this.bounds = new Float32Array(this.polyCount * 4);let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;@@ -155,6 +162,22 @@ export class NavMesh implements NavSurface {this.buckets = lists.map(l => Int32Array.from(l));}+ /**+ * Say what an area costs to cross, against 1 for open ground. Cheap makes a+ * route prefer it and dear makes it go round; nothing here BLOCKS, because a+ * price an agent will not pay when there is another way is still a price it+ * pays when there is not.+ */+ setAreaCost(area: number, cost: number): void {+ if (area < 0 || area > 255) return;+ this.areaCost_[area] = cost > 0 ? cost : 1;+ }++ /** What crossing polygon `p` costs a unit of distance. */+ costOf(p: number): number {+ return this.areaCost_[this.areas[p] ?? 1] ?? 1;+ }+/*** Join places the ground does not. Each segment is resolved to the polygons* under its two ends; one that reaches no ground at either end joins nothing@@ -414,7 +437,9 @@ export class NavMesh implements NavSurface {const mx = (a.x + b.x) / 2;const my = (a.y + b.y) / 2;const mz = (a.z + b.z) / 2;- const g = cost[cur]! + distance(enterX[cur]!, enterY[cur]!, enterZ[cur]!, mx, my, mz);+ const g = cost[cur]!+ + distance(enterX[cur]!, enterY[cur]!, enterZ[cur]!, mx, my, mz)+ * this.costOf(next);if (g >= cost[next]!) continue;cost[next] = g;parent[next] = cur;@@ -433,9 +458,9 @@ export class NavMesh implements NavSurface {if (closed[next]) continue;const g = cost[cur]!+ distance(enterX[cur]!, enterY[cur]!, enterZ[cur]!,- link.start.x, link.start.y, link.start.z)+ link.start.x, link.start.y, link.start.z) * this.costOf(cur)+ distance(link.start.x, link.start.y, link.start.z,- link.end.x, link.end.y, link.end.z);+ link.end.x, link.end.y, link.end.z) * this.costOf(next);if (g >= cost[next]!) continue;cost[next] = g;parent[next] = cur;diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.tsindex c14083628..d804fef31 100644--- a/sdk/src/ai/nav/NavPlugin.ts+++ b/sdk/src/ai/nav/NavPlugin.ts@@ -33,11 +33,13 @@ import { buildNavMesh } from './navmesh/build';import { collectNavGeometry, navGeometryReady, type NavGeometry } from './navGeometry';import {applyObstaclesToGrid, collectNavObstacles, navObstacleDigest,- collectNavLinks, navLinkDigest, type NavObstacleBox,+ collectNavLinks, navLinkDigest, collectNavAreas, navAreaDigest, applyAreasToGrid, FIRST_AREA,+ type NavObstacleBox, type NavAreaBox,} from './navObstacles';import { NavGrid } from './NavGrid';import { NavMesh, type NavLinkSegment } from './NavMesh';import { NavLink } from './NavLink';+import { NavArea } from './NavArea';import { setupNavDebugDraw } from './NavDebugDraw';import { advanceAlongPath } from './follow';import { avoidVelocity, type AvoidanceNeighbour } from './avoidance';@@ -74,6 +76,7 @@ export function bakeVolumes(baked: Set<Entity>,obstacles: readonly NavObstacleBox[] = [],links: readonly NavLinkSegment[] = [],+ areas: readonly NavAreaBox[] = [],): void {if (!geometry) return;const volumes = world.getEntitiesWithComponents([NavVolume, Transform]);@@ -99,6 +102,7 @@ export function bakeVolumes(stepHeight: volume.stepHeight,obstacles,links,+ areas,});nav.setSurface(mesh);@@ -189,6 +193,32 @@ export interface LinkState {mesh: NavMesh | null;}+/**+ * Tell the surface what each priced patch costs, and say whether one of them+ * MOVED — the price is a lookup and the place is a bake, which is why they are+ * two answers and not one.+ */+export function updateAreas(+ nav: Navigation, areas: ReadonlyArray<NavAreaBox & { cost: number }>, state: AreaState,+): boolean {+ const surface = nav.surface;+ if (surface instanceof NavMesh) {+ for (let id = FIRST_AREA; id < 256; id++) surface.setAreaCost(id, 1);+ for (const area of areas) surface.setAreaCost(area.area, area.cost);+ } else if (surface instanceof NavGrid) {+ applyAreasToGrid(surface, areas);+ }+ const digest = navAreaDigest(areas);+ if (digest === state.digest) return false;+ state.digest = digest;+ return true;+}++/** Where the priced patches were when the world was last built for them. */+export interface AreaState {+ digest: number;+}+/** 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;@@ -517,6 +547,7 @@ export class NavPlugin implements Plugin {const baked = new Set<Entity>();const obstacleState: ObstacleState = { digest: 0, at: 0, deferred: 0, grid: null };const linkState: LinkState = { digest: 0, mesh: null };+ const areaState: AreaState = { digest: 0 };app.world.onDespawn((entity: Entity) => {runtimes.delete(entity);baked.delete(entity);@@ -536,15 +567,19 @@ export class NavPlugin implements Plugin {: null;const obstacles = collectNavObstacles(app.world);const links = collectNavLinks(app.world);+ const areas = collectNavAreas(app.world);if (updateObstacles(nav, obstacles, obstacleState, Date.now())) baked.clear();- bakeVolumes(world as NavWorldView, nav, provider, baked, obstacles, links);+ if (updateAreas(nav, areas, areaState)) baked.clear();+ bakeVolumes(world as NavWorldView, nav, provider, baked, obstacles, links, areas);updateLinks(nav, links, linkState);+ // The mesh a bake just installed has never been told the prices.+ updateAreas(nav, areas, areaState);stepNavigation(world as NavWorldView, nav, time.delta, runtimes);},{name: 'NavAgentSystem',touches: {- reads: [NavVolume._name, NavObstacle._name, NavLink._name],+ reads: [NavVolume._name, NavObstacle._name, NavLink._name, NavArea._name],writes: [NavAgent._name, Transform._name, CharacterController3D._name],},// Both move an entity; for one carrying both, the path is thediff --git a/sdk/src/ai/nav/index.ts b/sdk/src/ai/nav/index.tsindex f4e147c69..30978f08d 100644--- a/sdk/src/ai/nav/index.ts+++ b/sdk/src/ai/nav/index.ts@@ -26,9 +26,11 @@ export { NavAgent, type NavAgentData, setNavDestination, stopNavAgent } from './export { NavVolume, type NavVolumeData } from './NavVolume';export { NavObstacle, type NavObstacleData } from './NavObstacle';export { NavLink, type NavLinkData } from './NavLink';+export { NavArea, type NavAreaData } from './NavArea';export {collectNavObstacles, navObstacleDigest, applyObstaclesToGrid, type NavObstacleBox,collectNavLinks, navLinkDigest,+ collectNavAreas, navAreaDigest, applyAreasToGrid, FIRST_AREA, type NavAreaBox,} 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.tsindex 6c4cb4d94..e5e72d439 100644--- a/sdk/src/ai/nav/navObstacles.ts+++ b/sdk/src/ai/nav/navObstacles.ts@@ -17,11 +17,12 @@ import { Transform } from '../../ecs/component';import { q } from '../../math/quat';import { NavObstacle, type NavObstacleData } from './NavObstacle';import { NavLink, type NavLinkData } from './NavLink';+import { NavArea, type NavAreaData } from './NavArea';import type { NavLinkSegment } from './NavMesh';import type { NavGrid } from './NavGrid';-import type { NavObstacleBox } from './navmesh/compact';+import type { NavAreaBox, NavObstacleBox } from './navmesh/compact';-export type { NavObstacleBox };+export type { NavAreaBox, NavObstacleBox };/** Every obstacle currently blocking, in world space. Disabled ones are absent,* which is what makes a door opening a change of this list. */@@ -42,6 +43,84 @@ export function collectNavObstacles(world: World): NavObstacleBox[] {return out;}+/**+ * Every priced patch of ground a scene declares. Each gets an area id of its own,+ * numbered in the order they are found: a cost can then be changed without+ * rebuilding anything, because the mesh carries the ID and not the price.+ */+export function collectNavAreas(world: World): Array<NavAreaBox & { cost: number }> {+ const out: Array<NavAreaBox & { cost: number }> = [];+ for (const entity of world.getEntitiesWithComponents([NavArea, Transform])) {+ const area = world.get(entity, NavArea) as NavAreaData;+ if (area.enabled === false) continue;+ const h = area.halfExtents;+ if (h.x <= 0 || h.y <= 0 || h.z <= 0) continue;+ // Area 0 is unwalkable and 1 is open ground; a byte is what a span carries,+ // so a scene may price 254 patches and no more.+ const id = FIRST_AREA + out.length;+ if (id > 255) break;+ 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) },+ area: id,+ cost: area.cost > 0 ? area.cost : 1,+ });+ }+ return out;+}++/** The first area id a scene may use. 0 is unwalkable, 1 is open ground. */+export const FIRST_AREA = 2;++/** A number that differs whenever the priced patches move, resize or appear. The+ * COST is left out: changing one costs a lookup, and moving one costs a bake. */+export function navAreaDigest(areas: ReadonlyArray<NavAreaBox>): number {+ let hash = 2166136261;+ const mix = (v: number): void => {+ hash = Math.imul(hash ^ (Math.round(v * 10) | 0), 16777619);+ };+ for (const box of areas) {+ 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);+ mix(box.area);+ }+ return hash;+}++/** Price the cells a patch covers. A grid charges by the cell, as it blocks. */+export function applyAreasToGrid(+ grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number }>,+): void {+ grid.clearCosts();+ const cs = grid.cellSize;+ for (const box of areas) {+ 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.setCost(gx, gy, box.cost);+ }+ }+ }+}+/** Every link a scene declares, with both ends placed in the world. */export function collectNavLinks(world: World): NavLinkSegment[] {const out: NavLinkSegment[] = [];diff --git a/sdk/src/ai/nav/navmesh/build.ts b/sdk/src/ai/nav/navmesh/build.tsindex 3a89c9f1f..e644b7af1 100644--- a/sdk/src/ai/nav/navmesh/build.ts+++ b/sdk/src/ai/nav/navmesh/build.ts@@ -24,7 +24,8 @@ import {} from './heightfield';import { log } from '../../../util/logger';import {- NavCompactField, erodeWalkableArea, markObstacles, type NavObstacleBox,+ NavCompactField, erodeWalkableArea, markObstacles, markAreas,+ type NavObstacleBox, type NavAreaBox,} from './compact';import { buildRegionsMonotone } from './regions';import { buildContours } from './contours';@@ -63,6 +64,8 @@ export interface BuildNavMeshOptions {obstacles?: readonly NavObstacleBox[];/** Ways between places the ground does not join — see `NavLink`. */links?: readonly NavLinkSegment[];+ /** Boxes of ground that cost more or less to cross — see `NavArea`. */+ areas?: readonly NavAreaBox[];}export function buildNavMesh(@@ -97,6 +100,9 @@ export function buildNavMesh(const chf = new NavCompactField(hf, walkableHeight, walkableClimb);if (opts.obstacles?.length) markObstacles(chf, opts.obstacles);+ // An obstacle takes ground away and an area only prices it, so this one does+ // not erode anything and only ever writes over ground that is already walkable.+ if (opts.areas?.length) markAreas(chf, opts.areas);erodeWalkableArea(chf, walkableRadius);buildRegionsMonotone(chf, minRegionArea);@@ -116,6 +122,7 @@ export function buildNavMesh(neis: mesh.neis,polyCount: mesh.polyCount,maxVertsPerPoly: mesh.maxVertsPerPoly,+ areas: mesh.areas,agentRadius,// A point is only ever off the mesh by what the bake took away: the// erosion, plus the cell the voxel grid rounded it into.@@ -142,6 +149,7 @@ function emptyMesh(agentRadius: number, cellSize: number): NavMesh {neis: new Int32Array(0),polyCount: 0,maxVertsPerPoly: 6,+ areas: new Uint8Array(0),agentRadius,snapDistance: agentRadius + cellSize,verticalReach: 0,diff --git a/sdk/src/ai/nav/navmesh/compact.ts b/sdk/src/ai/nav/navmesh/compact.tsindex 730955dcc..3afb4a592 100644--- a/sdk/src/ai/nav/navmesh/compact.ts+++ b/sdk/src/ai/nav/navmesh/compact.ts@@ -156,41 +156,66 @@ export interface NavObstacleBox {rotation: Quat;}+/** The same box, marking ground that costs something other than open ground. */+export interface NavAreaBox extends NavObstacleBox {+ /** Which area id the cells inside it take, 2 upwards. */+ area: number;+}++/** Walk the cells of `chf` a box covers, in the box's own frame. */+function forEachCellIn(+ chf: NavCompactField, box: NavObstacleBox,+ visit: (span: number) => void,+): void {+ const cs = chf.cellSize;+ const ch = chf.cellHeight;+ 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;+ visit(i);+ }+ }+ }+}++/**+ * Give the ground inside each box its own area id. Areas do not block, so this+ * runs AFTER the erosion: pulling the walkable world back from a swamp would put+ * a wall round it, and a swamp is something to wade through.+ */+export function markAreas(chf: NavCompactField, areas: readonly NavAreaBox[]): void {+ for (const box of areas) {+ forEachCellIn(chf, box, (i) => { chf.areas[i] = box.area; });+ }+}+/*** 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;- }- }- }+ forEachCellIn(chf, box, (i) => { chf.areas[i] = NAV_AREA_NULL; });}}diff --git a/sdk/src/ai/nav/navmesh/contours.ts b/sdk/src/ai/nav/navmesh/contours.tsindex acc51db30..cd90fc3ed 100644--- a/sdk/src/ai/nav/navmesh/contours.ts+++ b/sdk/src/ai/nav/navmesh/contours.ts@@ -24,6 +24,8 @@ import type { NavCompactField } from './compact';export interface NavContour {verts: Int32Array;reg: number;+ /** What crossing this patch costs — the area its cells were marked with. */+ area: number;}/**@@ -81,7 +83,7 @@ export function buildContours(removeDegenerateSegments(simplified);if (simplified.length / 4 < 3) continue;- contours.push({ verts: windCorrectly(simplified), reg });+ contours.push({ verts: windCorrectly(simplified), reg, area: chf.areas[i]! });}}}diff --git a/sdk/src/ai/nav/navmesh/polymesh.ts b/sdk/src/ai/nav/navmesh/polymesh.tsindex 46120977e..133349d36 100644--- a/sdk/src/ai/nav/navmesh/polymesh.ts+++ b/sdk/src/ai/nav/navmesh/polymesh.ts@@ -31,6 +31,8 @@ export interface NavPolyMesh {neis: Int32Array;polyCount: number;maxVertsPerPoly: number;+ /** What crossing each polygon costs, as the area its contour carried. */+ areas: Uint8Array;}/**@@ -46,6 +48,7 @@ export function buildPolyMesh(contours: NavContour[], maxVertsPerPoly: number):const indices: number[] = [];const tris: number[] = [];+ const areas: number[] = [];for (const contour of contours) {const n = contour.verts.length / 3;@@ -81,6 +84,7 @@ export function buildPolyMesh(contours: NavContour[], maxVertsPerPoly: number):}mergePolygons(local, verts, nvp);+ for (let i = 0; i < local.length / nvp; i++) areas.push(contour.area);for (const v of local) polys.push(v);}@@ -92,6 +96,7 @@ export function buildPolyMesh(contours: NavContour[], maxVertsPerPoly: number):neis: new Int32Array(polyCount * nvp).fill(NAV_NO_NEIGHBOUR),polyCount,maxVertsPerPoly: nvp,+ areas: Uint8Array.from(areas),};buildAdjacency(mesh);return mesh;diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.tsindex 2fcec5752..77e913c39 100644--- a/sdk/src/ai/nav/pathfind.ts+++ b/sdk/src/ai/nav/pathfind.ts@@ -100,7 +100,7 @@ export function findPath(const nIdx = ny * width + nx;if (closed[nIdx]) continue;- const step = i < 4 ? 1 : SQRT2;+ const step = (i < 4 ? 1 : SQRT2) * grid.costAt(nx, ny);const tentative = baseG + step;if (tentative < gScore[nIdx]) {gScore[nIdx] = tentative;@@ -137,10 +137,13 @@ export function shortenPath(grid: NavGrid, path: Cell[], clearance = 0): Cell[]return out;}-/** Whether every cell between two cells fits the body, walking the same steps. */+/** Whether every cell between two cells fits the body, walking the same steps.+ * Ground that costs something other than what the shortcut starts on is refused:+ * a route that went round the mud must not be straightened back into it. */function clearLine(grid: NavGrid, from: Cell, to: Cell, clearance: number): boolean {let x = from.x;let y = from.y;+ const price = grid.costAt(from.x, from.y);const dx = Math.abs(to.x - x);const dy = Math.abs(to.y - y);const sx = x < to.x ? 1 : -1;@@ -148,6 +151,7 @@ function clearLine(grid: NavGrid, from: Cell, to: Cell, clearance: number): boollet err = dx - dy;for (;;) {if (!fits(grid, x, y, clearance)) return false;+ if (grid.costAt(x, y) !== price) return false;if (x === to.x && y === to.y) return true;const e2 = err * 2;const stepX = e2 > -dy;diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex be61330e3..420f6b665 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -675,9 +675,13 @@ export {NavVolume,NavObstacle,NavLink,+ NavArea,collectNavObstacles,collectNavLinks,navLinkDigest,+ collectNavAreas,+ navAreaDigest,+ applyAreasToGrid,navObstacleDigest,applyObstaclesToGrid,setNavDestination,@@ -701,6 +705,8 @@ export {type NavVolumeData,type NavObstacleData,type NavLinkData,+ type NavAreaData,+ type NavAreaBox,type NavLinkSegment,type NavObstacleBox,type NavDebugDrawConfig,diff --git a/sdk/tests/nav-areas.test.ts b/sdk/tests/nav-areas.test.tsnew file mode 100644index 000000000..f01e32ab3--- /dev/null+++ b/sdk/tests/nav-areas.test.ts@@ -0,0 +1,181 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Ground that costs more or less to cross.+ *+ * A mesh answers where an agent CAN walk; a priced patch is where a scene says+ * what it would rather walk on. Which makes every claim here about a route that+ * is LONGER than the one distance alone would have chosen — and about the one+ * that is not, when the price is the only way through.+ */+import { describe, it, expect } from 'vitest';+import { buildNavMesh } from '../src/ai/nav/navmesh/build';+import { NavMesh } from '../src/ai/nav/NavMesh';+import { NavGrid } from '../src/ai/nav/NavGrid';+import { Navigation } from '../src/ai/nav/Navigation';+import { updateAreas, type AreaState } from '../src/ai/nav/NavPlugin';+import { FIRST_AREA, applyAreasToGrid, type NavAreaBox } from '../src/ai/nav/navObstacles';+import { findPath } from '../src/ai/nav/pathfind';+import type { Vec3 } from '../src/types';++const NO_TURN = { x: 0, y: 0, z: 0, w: 1 };++function floor(half = 500): { 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: -600, y: -100, z: -600 },+ max: { x: 600, y: 400, z: 600 },+ cellSize: 25,+ cellHeight: 10,+ agentHeight: 180,+ agentRadius: 30,+ stepHeight: 40,+};++/** A swamp straight across the middle of the floor, wide but not endless. */+const SWAMP: NavAreaBox = {+ center: { x: 0, y: 0, z: 0 },+ halfExtents: { x: 150, y: 200, z: 250 },+ rotation: NO_TURN,+ area: FIRST_AREA,+};++const bake = (areas: NavAreaBox[] = []): NavMesh => {+ const f = floor();+ return buildNavMesh(f.verts, f.indices, { ...BOX, areas });+};++const FROM = { x: -400, y: 0, z: 0 };+const TO = { x: 400, y: 0, z: 0 };++/** How far a route goes off the straight line between its ends. */+function detour(path: Vec3[]): number {+ return Math.max(...path.map(p => Math.abs(p.z)));+}++describe('priced ground in a mesh', () => {+ it('is walked straight across when it costs what open ground costs', () => {+ const mesh = bake([SWAMP]);+ const path = mesh.findWorldPath(FROM, TO)!;+ expect(path).not.toBeNull();+ expect(detour(path)).toBeLessThan(60);+ });++ it('is walked round when it costs more', () => {+ const mesh = bake([SWAMP]);+ mesh.setAreaCost(FIRST_AREA, 8);+ const path = mesh.findWorldPath(FROM, TO)!;+ expect(detour(path)).toBeGreaterThan(200);+ });++ // A price is not a wall. An agent with nowhere else to go wades through, which+ // is the difference between a swamp and a fence.+ it('is still crossed when there is no way round', () => {+ const wall: NavAreaBox = { ...SWAMP, halfExtents: { x: 150, y: 200, z: 600 } };+ const mesh = bake([wall]);+ mesh.setAreaCost(FIRST_AREA, 40);+ const path = mesh.findWorldPath(FROM, TO)!;+ expect(path[path.length - 1]!.x).toBeGreaterThan(300);+ });++ it('costs nothing extra to change its price', () => {+ const mesh = bake([SWAMP]);+ mesh.setAreaCost(FIRST_AREA, 8);+ const round = detour(mesh.findWorldPath(FROM, TO)!);+ mesh.setAreaCost(FIRST_AREA, 1);+ const across = detour(mesh.findWorldPath(FROM, TO)!);+ expect(round).toBeGreaterThan(200);+ expect(across).toBeLessThan(60);+ });+});++describe('priced ground on a grid', () => {+ const open = (): NavGrid => new NavGrid({ width: 21, height: 21, cellSize: 10 });+ const swamp = (cost: number): NavAreaBox & { cost: number } => ({+ center: { x: 100, y: 100, z: 0 },+ halfExtents: { x: 30, y: 60, z: 10 },+ rotation: NO_TURN,+ area: FIRST_AREA,+ cost,+ });++ it('makes a route go round what it would have walked over', () => {+ const cheap = open();+ applyAreasToGrid(cheap, [swamp(1)]);+ const straight = findPath(cheap, { x: 0, y: 10 }, { x: 20, y: 10 }, { diagonal: false })!;+ expect(straight.every(c => c.y === 10)).toBe(true);++ const dear = open();+ applyAreasToGrid(dear, [swamp(20)]);+ const round = findPath(dear, { x: 0, y: 10 }, { x: 20, y: 10 }, { diagonal: false })!;+ expect(round.some(c => c.y !== 10)).toBe(true);+ // And it never walked into the swamp it was going round.+ for (const c of round) {+ if (c.x >= 7 && c.x <= 13) expect(c.y).not.toBe(10);+ }+ });++ // String-pulling shortens a route by distance. Straightening one back through+ // the mud it just went round would undo the only reason it went round.+ it('is not straightened back through by the string-pull', () => {+ const grid = open();+ applyAreasToGrid(grid, [swamp(20)]);+ const path = grid.findWorldPath({ x: 0, y: 100, z: 0 }, { x: 200, y: 100, z: 0 })!;+ // Sampled ALONG the route, not at its corners: a shortcut clips the mud+ // between two waypoints that are both clear of it.+ for (let i = 1; i < path.length; i++) {+ const a = path[i - 1]!;+ const b = path[i]!;+ const steps = Math.max(2, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / 4));+ for (let t = 0; t <= steps; t++) {+ const cell = grid.worldToCell({+ x: a.x + (b.x - a.x) * (t / steps),+ y: a.y + (b.y - a.y) * (t / steps),+ });+ expect(grid.costAt(cell.x, cell.y)).toBe(1);+ }+ }+ });++ it('gives the ground back its open price when the patch goes', () => {+ const grid = open();+ applyAreasToGrid(grid, [swamp(20)]);+ expect(grid.costAt(10, 10)).toBe(20);+ applyAreasToGrid(grid, []);+ expect(grid.costAt(10, 10)).toBe(1);+ });+});++describe('updateAreas', () => {+ const state = (): AreaState => ({ digest: 0 });++ it('tells a mesh the prices without rebuilding it', () => {+ const nav = new Navigation();+ const mesh = bake([SWAMP]);+ nav.setSurface(mesh);+ const s = state();+ updateAreas(nav, [{ ...SWAMP, cost: 8 }], s);+ expect(mesh.costOf(mesh.findPoly({ x: 0, y: 0, z: 0 }))).toBe(8);+ // A price the scene changed is a price, not a bake: same mesh, new answer.+ updateAreas(nav, [{ ...SWAMP, cost: 2 }], s);+ expect(mesh.costOf(mesh.findPoly({ x: 0, y: 0, z: 0 }))).toBe(2);+ expect(nav.surface).toBe(mesh);+ });++ it('asks for a rebuild when a patch moves, and not when only its price does', () => {+ const nav = new Navigation();+ nav.setSurface(bake([SWAMP]));+ const s = state();+ updateAreas(nav, [{ ...SWAMP, cost: 8 }], s);+ expect(updateAreas(nav, [{ ...SWAMP, cost: 3 }], s)).toBe(false);+ expect(updateAreas(nav, [{+ ...SWAMP, cost: 3, center: { x: 200, y: 0, z: 0 },+ }], s)).toBe(true);+ });+});