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(terrain): findPath asks whether a place can be walked to under a slope limit

yhh633a016fd851
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f64e663f..5c4775f68 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ published separately; it ships inside the editor.
- **Rays against the terrain, anywhere.** `Terrains.raycast(origin, direction, maxDistance)` meets the ground's triangles exactly (the ones collision and `heightAt` use) wherever the ray goes, with no physics world and no collision tile there, for a line of sight, a pick or a landing spot.
- **Far versions for generated decoration.** A recipe member can name its far version (`far`: crossed cards, or a tent for a conifer, showing a rectangle of its texture), drawn past its layer's `lodDistance`, and decoration that leans with the ground (`attach: 'align'`) now leans in its merged mesh too.
- **Terrain modifiers, and zones that level their ground.** `Terrains.setModifier` lays a change over the ground (`flattenModifier` levels a circle or a turned box, blending back over its edge) that what is drawn, the queries, rays and collision all follow, remaking only the pages and collision tiles it reaches; `heightBeneathAt` reads the ground as it was made. A `WorldZone` with `flatten` levels its plot to the ground's height at its centre.
+- **Whether a place can be walked to.** `Terrains.findPath(from, to, { maxSlope, step, blocked })` searches the ground for a way a walker held to a slope can take, reading the ground where it goes (modifiers too, nothing baked), and returns it pulled straight with its length, or says whether there is no way, the search ran out, or an end stands on no ground: what a game checks a spawn or a goal against.
- **World rules as a file, with an editor.** A WorldGen's `rules` can name a `.esworld` file: the biomes, recipes and layers as data, checked as they are read (a missing recipe or layer fails the world with where it went wrong), followed by the cook like a material so the meshes and materials it names ship with the scene, and watched so a saved edit lays the world out again. The editor opens it in a World Rules editor that lists the biomes, recipes and layers, edits each with a form, and says whether the engine would take the rules as they stand.
- **How far a place is from the water.** `Waters.shoreAt(x, z)` gives the distance across the ground to the water's edge (above zero on dry land, below on the water), and generated worlds read it as the `shoreDistance` field, so a beach or a band of reeds can follow the shore.
- **A vertex hook can hand the fragment a colour.** What a material's vertex hook leaves in `es_vertexColor` is now the colour its fragment receives (times the instance's tint), on both backends.
diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.md
index 3fdf0c11a..c4e2a7428 100644
--- a/docs/WORLD_GENERATION_PLAN.md
+++ b/docs/WORLD_GENERATION_PLAN.md
@@ -61,7 +61,7 @@
- 后续已补:有限整地——地形修改器(`Terrains.setModifier`,世界空间函数,所有读取方一致,仅重做触及的页与碰撞块),区域 `flatten` 压平(地面未知时挂起重试)。
- 后续已补:陆地离岸距离——`Waters.shoreAt` 与环境场 `shoreDistance`(陆上为到水边距离,水中为负)。
- 后续已补:规则即资源——`.esworld` 文件(加载时校验、引用的网格材质随场景打包、修改后世界自动重建)与编辑器里的世界规则编辑器(群落/配方/布置层表单,实时显示引擎是否接受)。
- - 仍欠:可达性/安全落点等验收由游戏用查询接口实现(引擎可后续提供寻路连通查询)。
+ - 后续已补:可达性查询——`Terrains.findPath`(按需读取地面的坡度受限 A*,可传 `blocked` 排除水域/禁区,路径拉直,`maxCells` 有界并区分 unreachable/exhausted/noGround);示例 R 键演示回家路径(约 600 单位、300 格、8ms)。导航网格目前只从静态碰撞体烘焙、不含地形,无限地形的分块运行时导航网格另立。
- 验收:林地建房后草木不穿地板;采集后卸载重进不重生;同种子不同加载顺序结果相同;安全落点、早期资源、入口可达。
## 水域补充
diff --git a/docs/astro/src/content/docs/graphics/terrain.mdx b/docs/astro/src/content/docs/graphics/terrain.mdx
index 0c55eaf4a..e6dae9c16 100644
--- a/docs/astro/src/content/docs/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/graphics/terrain.mdx
@@ -172,6 +172,27 @@ terrains.deleteModifier('plot 1'); // the ground comes b
A `WorldZone` with `flatten` levels its ground this way.
+### Can it be walked to
+
+`findPath` searches the ground for a way from one place to another that a walker held to a slope can take: what a game checks a
+spawn, a quest's goal or a village against before it trusts a generated world. It reads the ground where the search goes (modifiers
+and all), so it needs nothing baked and works on ground without end.
+
+```ts
+const terrains = app.getResource(TerrainsRes);
+const waters = app.getResource(WatersRes);
+const way = terrains.findPath(spawn, village, {
+ maxSlope: 32, // degrees; a walker switches back up anything gentler across
+ step: 8, // the search's cell, in world units
+ blocked: (x, z) => (waters.shoreAt(x, z) ?? 1) < 0, // no wading
+});
+if (way.state !== 'reached') regenerate(); // 'unreachable', 'exhausted' (ran out of maxCells) or 'noGround'
+```
+
+The way comes back pulled straight wherever a straight walk holds, with its length along the ground. It is a query for checks and
+plans, not for every frame: a few hundred metres cost milliseconds, and `maxCells` bounds a long one, which then says it ran out
+rather than that there is no way. Agents that walk every frame use [navigation](/docs/gameplay/ai/navigation/).
+
### Providers and versions
Ground without end is made by a provider: one function of the world position, the same on every machine. It is asked for a region
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
index c67b3dcb4..4c358cd0a 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/terrain.mdx
@@ -119,6 +119,23 @@ terrains.deleteModifier('plot 1'); // 地面恢复原样
带 `flatten` 的 `WorldZone` 就是这样压平它的地面的。
+### 能否走到
+
+`findPath` 在地面上搜索从一个地方到另一个地方、受坡度限制的步行者能走的路:游戏在信任一个生成的世界之前,用它检查出生点、任务目标或村庄是否可达。它在搜索经过的地方读取地面(包括修改器),不需要预先烘焙,无限地形上也能用。
+
+```ts
+const terrains = app.getResource(TerrainsRes);
+const waters = app.getResource(WatersRes);
+const way = terrains.findPath(spawn, village, {
+ maxSlope: 32, // 度;更缓的斜面步行者可以斜着之字形爬上去
+ step: 8, // 搜索格子的边长,世界单位
+ blocked: (x, z) => (waters.shoreAt(x, z) ?? 1) < 0, // 不涉水
+});
+if (way.state !== 'reached') regenerate(); // 'unreachable'、'exhausted'(用完 maxCells)或 'noGround'
+```
+
+返回的路径在能直线走通的地方被拉直,并给出沿地面的长度。它是用于检查和规划的查询,不适合每帧调用:几百米耗时几毫秒,`maxCells` 限制长距离搜索,用完时报告"用完了"而不是"没有路"。每帧行走的角色请用[导航](/docs/zh-cn/gameplay/ai/navigation/)。
+
### 生成器与版本
无限地面由生成器生成:一个关于世界位置的函数,在每台机器上都一样。它被要求采样一个区域(世界、种子和版本、以世界单位计的起点、间距和每边样本数),返回那里的高度;如果它自己给地面上色,还返回每个样本四个图层权重。每个区域都是同一个函数在不同点上的读数,所以相邻页共享边上的样本,粗页和细页在样本重合处一致,页生成的先后不改变任何东西。位置是世界的,不是地形的:同一个世界上分开摆放的两个地形是同一片地面。
diff --git a/examples/worldgen/src/main.ts b/examples/worldgen/src/main.ts
index 6c355451f..414d8ecf5 100644
--- a/examples/worldgen/src/main.ts
+++ b/examples/worldgen/src/main.ts
@@ -2,13 +2,15 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
// The rules are a project file (assets/worlds/wilds.esworld) the scene's WorldGen names; mining and building are changes the world keeps.
import { addPlugin, defineSystem, GetWorld, Res, Query, Mut, Input, Time, Transform, Camera, Text, Name, BakesRes,
- spawnUIEntity, UIPositionType, px, type Entity } from 'esengine';
+ spawnUIEntity, UIPositionType, px, Draw, registerDrawCallback, type Entity } from 'esengine';
import { WorldGenRes } from 'esengine/worldgen';
+import { TerrainsRes } from 'esengine/terrain';
const KEYS = [
'W A S D walk Q E turn',
'M mine the nearest copper',
'B build a house in front of you (keeps the wild out of it)',
+ 'R find the way home on foot (no ground steeper than 32 degrees)',
];
addPlugin({
@@ -20,6 +22,14 @@ addPlugin({
let noticeUntil = 0;
let built = 0;
const say = (text: string, now: number): void => { notice = text; noticeUntil = now + 3; };
+ // The way home last found, drawn over the ground until the next is asked for.
+ let way: { x: number; y: number; z: number }[] = [];
+ registerDrawCallback('worldgen-way-home', () => {
+ for (let i = 1; i < way.length; i++) {
+ const a = way[i - 1]!, b = way[i]!;
+ Draw.line3D({ x: a.x, y: a.y + 4, z: a.z }, { x: b.x, y: b.y + 4, z: b.z }, { r: 1, g: 0.78, b: 0.2, a: 1 }, 3);
+ }
+ });
app.addSystem(defineSystem([GetWorld(), Res(Input), Res(Time), Query(Mut(Transform), Camera)], (world, input, time, cameras) => {
const now = time.elapsed;
@@ -27,11 +37,11 @@ addPlugin({
const canvas = world.findEntityByName('Canvas');
if (canvas !== null) {
const panel = { position: UIPositionType.Absolute, insetLeft: px(20), insetTop: px(18), width: px(470), pointerEvents: 0 };
- hud = spawnUIEntity({ world, parent: canvas, node: { ...panel, height: px(80) },
+ hud = spawnUIEntity({ world, parent: canvas, node: { ...panel, height: px(96) },
visual: { color: { r: 0.02, g: 0.05, b: 0.08, a: 0.55 } },
text: { content: `GENERATED WORLD\n${KEYS.join('\n')}`, fontSize: 13, color: { r: 0.9, g: 0.94, b: 0.97, a: 1 }, align: 0 } });
world.insert(hud, Name, { value: 'Keys' });
- status = spawnUIEntity({ world, parent: canvas, node: { ...panel, insetTop: px(104), height: px(64) },
+ status = spawnUIEntity({ world, parent: canvas, node: { ...panel, insetTop: px(120), height: px(64) },
visual: { color: { r: 0.02, g: 0.05, b: 0.08, a: 0.55 } },
text: { content: '', fontSize: 13, color: { r: 0.62, g: 0.86, b: 0.95, a: 1 }, align: 0 } });
world.insert(status, Name, { value: 'Status' });
@@ -76,6 +86,17 @@ addPlugin({
say(`House ${built} built: its plot levelled and the wild kept out of it`, now);
}
+ if (input.isKeyPressed('KeyR') && app.hasResource(TerrainsRes)) {
+ // Home is the Home zone at the origin; the search reads the ground as it stands, levelled plots and all.
+ const started = performance.now();
+ const found = app.getResource(TerrainsRes).findPath({ x, z }, { x: 0, z: 0 }, { step: 12, maxSlope: 32 });
+ const ms = (performance.now() - started).toFixed(0);
+ way = found.path;
+ say(found.state === 'reached'
+ ? `The way home: ${Math.round(found.length)} along the ground (${found.cells} cells, ${ms} ms)`
+ : `No way home on foot: ${found.state} (${found.cells} cells, ${ms} ms)`, now);
+ }
+
if (status !== null && plan) {
const biome = plan.biomeAt(x, z) ?? '—';
const bakes = app.hasResource(BakesRes) ? app.getResource(BakesRes).active : [];
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 87c7bebcd..6d3b60608 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -10114,6 +10114,7 @@ static prototype: TerrainUnavailable
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
+findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 4377bb324..3505d8ab7 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -10327,6 +10327,7 @@ static prototype: TerrainUnavailable
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
+findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 0bb86cc97..71f0eb8d9 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -10109,6 +10109,7 @@ static prototype: TerrainUnavailable
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
+findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index df4d324fa..6946f4633 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -10402,6 +10402,7 @@ static prototype: TerrainUnavailable
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
+findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
diff --git a/sdk/etc/terrain.api.md b/sdk/etc/terrain.api.md
index e42f7c200..d720132dc 100644
--- a/sdk/etc/terrain.api.md
+++ b/sdk/etc/terrain.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/terrain
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 52 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 56 experimental · 0 deprecated
## Eroded — interface @experimental
```
@@ -168,6 +168,28 @@ minHeight: number
range0: number
```
+## ReachGround — interface @experimental
+```
+heightAt: (x: number, z: number) => number | null
+```
+
+## ReachOptions — interface @experimental
+```
+blocked: ((x: number, z: number) => boolean) | undefined
+detour: number | undefined
+maxCells: number | undefined
+maxSlope: number | undefined
+step: number | undefined
+```
+
+## ReachResult — interface @experimental
+```
+cells: number
+length: number
+path: { x: number; y: number; z: number; }[]
+state: "noGround" | "reached" | "unreachable" | "exhausted"
+```
+
## Splat — interface @experimental
```
height: number
@@ -307,6 +329,7 @@ static prototype: TerrainUnavailable
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
+findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
@@ -347,6 +370,11 @@ ResourceDef<Terrains>
(field: Heightfield, p: ErosionParams): Generator<number, Eroded, void>
```
+## findGroundPath — function @experimental
+```
+(ground: ReachGround, fromX: number, fromZ: number, toX: number, toZ: number, options?: ReachOptions): ReachResult
+```
+
## flattenModifier — function @experimental
```
(id: string, shape: { type: "circle"; x: number; z: number; radius: number; } | { type: "rect"; x: number; z: number; halfX: number; halfZ: number; yaw?: number; }, height: number, falloff: number): TerrainModifier
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index ae52e8849..28242c32a 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -10116,6 +10116,7 @@ static prototype: TerrainUnavailable
@internal revision_: number
collisionReadyAt: (x: number, z: number) => boolean
deleteModifier: (id: string) => void
+findPath: (from: { x: number; z: number; }, to: { x: number; z: number; }, options?: ReachOptions) => ReachResult
groundKnownAt: (x: number, z: number) => boolean
heightAt: (x: number, z: number) => number | null
heightBeneathAt: (x: number, z: number) => number | null
diff --git a/sdk/src/terrain/index.ts b/sdk/src/terrain/index.ts
index 0f01a157c..5436ddf32 100644
--- a/sdk/src/terrain/index.ts
+++ b/sdk/src/terrain/index.ts
@@ -11,6 +11,7 @@ export { FieldSource, NoiseSource, ModifiedSource, flattenModifier, noised, type
export { boxDistance, levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
export { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type Page, type PageImage } from './pages';
export { buildPatchMesh } from './patch';
+export { findGroundPath, type ReachGround, type ReachOptions, type ReachResult } from './reach';
export {
noiseProvider, ProviderSource, registerTerrainProvider, terrainProvider, TerrainUnavailable,
type TerrainProvider, type TerrainRegion, type TerrainSamples,
diff --git a/sdk/src/terrain/reach.ts b/sdk/src/terrain/reach.ts
new file mode 100644
index 000000000..374fbe60b
--- /dev/null
+++ b/sdk/src/terrain/reach.ts
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file reach.ts
+ * @brief Whether one place on the ground can be walked to from another, and by what way: a search over the ground itself, held to
+ * how steep a walker can climb.
+ *
+ * @details The ground is read where it is asked, a cell of `step` at a time, so it works on ground without end and on ground a modifier
+ * has just changed, with nothing baked first. A step between two cells is taken when the ground between them is no steeper
+ * than `maxSlope` (sampled along it, so a ridge narrower than a cell is not stepped over) and the caller does not refuse the
+ * place (deep water, a zone kept clear). The way found is pulled straight wherever a straight walk holds, so it reads as a
+ * route, not a staircase of cells. The search is bounded (`maxCells`), and says when it ran out rather than claiming no way.
+ */
+import { MinHeap } from '../ai/nav/minHeap';
+
+/** What a walker can cross. @experimental */
+export interface ReachOptions {
+ /** The side of a cell of the search, in world units. Smaller finds narrower passes and costs more. Default 4. */
+ step?: number;
+ /** The steepest ground a walker climbs, in degrees from flat. Default 35. */
+ maxSlope?: number;
+ /** A place the walker may not stand, besides ground too steep: water deeper than it wades, a zone kept clear. */
+ blocked?: (x: number, z: number) => boolean;
+ /** How many cells the search may open before it gives up (and says so). Default 200 000. */
+ maxCells?: number;
+ /** How far past the box round both ends the search may wander, as a share of the distance between them. Default 1. */
+ detour?: number;
+}
+
+/** The way from one place to another, or why there is none. @experimental */
+export interface ReachResult {
+ /**
+ * `reached`: a way was found. `unreachable`: every way out of the start within the search's bounds was walked, and none came to
+ * the end. `exhausted`: the search ran out of cells before it knew. `noGround`: one end stands where no ground is known, too steep
+ * or refused.
+ */
+ state: 'reached' | 'unreachable' | 'exhausted' | 'noGround';
+ /** The way, from the start to the end (or to the nearest place reached, when it was not), on the ground. */
+ path: { x: number; y: number; z: number }[];
+ /** How long the way is, along the ground. */
+ length: number;
+ /** How many cells were opened. */
+ cells: number;
+}
+
+/** The ground a search reads. */
+export interface ReachGround {
+ heightAt(x: number, z: number): number | null;
+}
+
+const NEIGHBOURS: readonly (readonly [number, number])[] = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]];
+
+/**
+ * Searches the ground for a way from (fromX, fromZ) to (toX, toZ) that a walker held to `maxSlope` can take.
+ * @experimental
+ */
+export function findGroundPath(ground: ReachGround, fromX: number, fromZ: number, toX: number, toZ: number, options: ReachOptions = {}): ReachResult {
+ const step = Math.max(options.step ?? 4, 1e-3);
+ const grade = Math.tan(Math.min(Math.max(options.maxSlope ?? 35, 0), 89.9) * Math.PI / 180);
+ const blocked = options.blocked;
+ const maxCells = Math.max(1, options.maxCells ?? 200_000);
+ const detour = Math.max(options.detour ?? 1, 0);
+
+ const standable = (x: number, z: number): number | null => {
+ const h = ground.heightAt(x, z);
+ return h === null || (blocked && blocked(x, z)) ? null : h;
+ };
+ // Every step is checked a few times along its run, so ground that rises and falls inside one cell is not stepped over.
+ const samples = 3;
+ const walkable = (ax: number, az: number, ah: number, bx: number, bz: number, bh: number): boolean => {
+ const run = Math.hypot(bx - ax, bz - az) / samples;
+ let prev = ah;
+ for (let i = 1; i <= samples; i++) {
+ const t = i / samples;
+ const h = i === samples ? bh : standable(ax + (bx - ax) * t, az + (bz - az) * t);
+ if (h === null || Math.abs(h - prev) > grade * run + 1e-6) return false;
+ prev = h;
+ }
+ return true;
+ };
+
+ const fromH = standable(fromX, fromZ), toH = standable(toX, toZ);
+ if (fromH === null || toH === null) return { state: 'noGround', path: [], length: 0, cells: 0 };
+
+ // The cells are a lattice anchored at the start; the end is joined from the cell nearest it.
+ const span = Math.hypot(toX - fromX, toZ - fromZ);
+ const margin = span * detour + step * 4;
+ const minI = Math.floor((Math.min(fromX, toX) - margin - fromX) / step), maxI = Math.ceil((Math.max(fromX, toX) + margin - fromX) / step);
+ const minJ = Math.floor((Math.min(fromZ, toZ) - margin - fromZ) / step), maxJ = Math.ceil((Math.max(fromZ, toZ) + margin - fromZ) / step);
+ const cols = maxI - minI + 1;
+ const keyOf = (i: number, j: number): number => (j - minJ) * cols + (i - minI);
+ const xOf = (i: number): number => fromX + i * step;
+ const zOf = (j: number): number => fromZ + j * step;
+ const endI = Math.round((toX - fromX) / step), endJ = Math.round((toZ - fromZ) / step);
+
+ const g = new Map<number, number>();
+ const height = new Map<number, number>();
+ const parent = new Map<number, number>();
+ const closed = new Set<number>();
+ const open = new MinHeap(1024);
+ const startKey = keyOf(0, 0);
+ g.set(startKey, 0); height.set(startKey, fromH); open.push(startKey, span);
+ let best = startKey, bestLeft = span, found = -1, cells = 0, exhausted = false;
+
+ while (open.size > 0) {
+ const key = open.pop();
+ if (closed.has(key)) continue;
+ closed.add(key);
+ if (++cells > maxCells) { exhausted = true; break; }
+ const i = (key % cols) + minI, j = Math.floor(key / cols) + minJ;
+ const x = xOf(i), z = zOf(j), h = height.get(key)!;
+ const left = Math.hypot(toX - x, toZ - z);
+ if (left < bestLeft) { bestLeft = left; best = key; }
+ // Near the end the last step is to the end itself, so the way ends where it was asked to, not at a lattice point.
+ if (Math.abs(i - endI) <= 1 && Math.abs(j - endJ) <= 1 && walkable(x, z, h, toX, toZ, toH)) { found = key; break; }
+ for (const [di, dj] of NEIGHBOURS) {
+ const ni = i + di, nj = j + dj;
+ if (ni < minI || ni > maxI || nj < minJ || nj > maxJ) continue;
+ const nk = keyOf(ni, nj);
+ if (closed.has(nk)) continue;
+ const nx = xOf(ni), nz = zOf(nj);
+ let nh = height.get(nk);
+ if (nh === undefined) {
+ const read = standable(nx, nz);
+ if (read === null) { closed.add(nk); continue; }
+ nh = read; height.set(nk, nh);
+ }
+ if (!walkable(x, z, h, nx, nz, nh)) continue;
+ const cost = g.get(key)! + Math.hypot(nx - x, nz - z, nh - h);
+ if (cost >= (g.get(nk) ?? Infinity)) continue;
+ g.set(nk, cost); parent.set(nk, key);
+ open.push(nk, cost + Math.hypot(toX - nx, toZ - nz));
+ }
+ }
+
+ const tail = found >= 0 ? found : best;
+ const cellsOf: number[] = [];
+ for (let k: number | undefined = tail; k !== undefined; k = parent.get(k)) cellsOf.push(k);
+ cellsOf.reverse();
+ const points = cellsOf.map((k) => ({ x: xOf((k % cols) + minI), y: height.get(k)!, z: zOf(Math.floor(k / cols) + minJ) }));
+ points[0] = { x: fromX, y: fromH, z: fromZ };
+ if (found >= 0) points.push({ x: toX, y: toH, z: toZ });
+ // A straight walk is held to the same rule as a step, checked a cell at a time along it.
+ const direct = (a: { x: number; y: number; z: number }, b: { x: number; y: number; z: number }): boolean => {
+ const n = Math.max(1, Math.ceil(Math.hypot(b.x - a.x, b.z - a.z) / step));
+ let px = a.x, pz = a.z, ph = a.y;
+ for (let k = 1; k <= n; k++) {
+ const t = k / n;
+ const x = a.x + (b.x - a.x) * t, z = a.z + (b.z - a.z) * t;
+ const h = k === n ? b.y : standable(x, z);
+ if (h === null || !walkable(px, pz, ph, x, z, h)) return false;
+ px = x; pz = z; ph = h;
+ }
+ return true;
+ };
+ const path = straighten(points, direct);
+ let length = 0;
+ for (let k = 1; k < path.length; k++) length += Math.hypot(path[k]!.x - path[k - 1]!.x, path[k]!.y - path[k - 1]!.y, path[k]!.z - path[k - 1]!.z);
+ const state = found >= 0 ? 'reached' : exhausted ? 'exhausted' : 'unreachable';
+ return { state, path, length, cells };
+}
+
+/** The way with every corner a straight walk can cut left out: each point joined to the farthest one ahead it can walk to directly. */
+function straighten<P>(points: P[], direct: (a: P, b: P) => boolean): P[] {
+ if (points.length <= 2) return points;
+ const out = [points[0]!];
+ let at = 0;
+ while (at < points.length - 1) {
+ let next = at + 1;
+ // Farthest first, within a window, so a long way costs a bounded number of checks per point.
+ for (let k = Math.min(points.length - 1, at + 64); k > at + 1; k--) if (direct(points[at]!, points[k]!)) { next = k; break; }
+ out.push(points[next]!);
+ at = next;
+ }
+ return out;
+}
diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.ts
index 3d5934150..2779866b1 100644
--- a/sdk/src/terrain/terrainPlugin.ts
+++ b/sdk/src/terrain/terrainPlugin.ts
@@ -37,6 +37,7 @@ import { log } from '../util/logger';
import { bakesOf } from '../runtime/bakes';
import type { Color, Entity } from '../types';
import { erosionJob, heightfieldFromPixels, type Heightfield } from './heightfield';
+import { findGroundPath, type ReachOptions, type ReachResult } from './reach';
import { FieldSource, ModifiedSource, type TerrainModifier, type TerrainSource } from './source';
import { levelRange, nodeKey, parentOf, selectNodes, type QuadtreeParams, type TerrainNode } from './quadtree';
import { makePage, PageTable, PAGE_SIDE, PAGE_TEXELS, PATCH_CELLS, type PageImage, type Repaint } from './pages';
@@ -316,6 +317,15 @@ export class Terrains {
return best;
}
+ /**
+ * A way across the ground from one place to another that a walker held to `maxSlope` can take, or why there is none: what a game
+ * checks a spawn, a quest's goal or a village against. The ground is read where the search goes, modifiers and all, so nothing is
+ * baked first; ground still being made is no ground yet (see `groundKnownAt`).
+ */
+ findPath(from: { x: number; z: number }, to: { x: number; z: number }, options?: ReachOptions): ReachResult {
+ return findGroundPath(this, from.x, from.z, to.x, to.z, options);
+ }
+
/** Whether the ground under (x, z) is built for collision: what a game waits on before it drops something there. */
collisionReadyAt(x: number, z: number): boolean {
const app = this.app_;
diff --git a/sdk/tests/terrain-reach.test.ts b/sdk/tests/terrain-reach.test.ts
new file mode 100644
index 000000000..3ecbd9b62
--- /dev/null
+++ b/sdk/tests/terrain-reach.test.ts
@@ -0,0 +1,47 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { findGroundPath } from '../src/terrain/reach';
+
+const flat = { heightAt: () => 0 };
+/** A wall of cliff along x = 50 for |z| < 100, sheer; open round its ends. */
+const cliff = { heightAt: (x: number, z: number) => (Math.abs(x - 50) < 2 && Math.abs(z) < 100 ? 40 : 0) };
+/** A ramp rising 1 in 2 (about 27°) east. */
+const ramp = { heightAt: (x: number) => Math.max(0, x) * 0.5 };
+
+describe('findGroundPath', () => {
+ it('walks flat ground in a straight line', () => {
+ const r = findGroundPath(flat, 0, 0, 100, 37);
+ expect(r.state).toBe('reached');
+ expect(r.path).toHaveLength(2);
+ expect(r.length).toBeCloseTo(Math.hypot(100, 37), 3);
+ });
+
+ it('goes round a cliff it cannot climb, and is longer for it', () => {
+ const r = findGroundPath(cliff, 0, 0, 100, 0, { step: 4 });
+ expect(r.state).toBe('reached');
+ expect(r.length).toBeGreaterThan(200);
+ for (const p of r.path) expect(p.y).toBe(0);
+ expect(r.path.at(-1)).toMatchObject({ x: 100, z: 0 });
+ });
+
+ it('climbs a slope under the limit and not one over it', () => {
+ expect(findGroundPath(ramp, 0, 0, 80, 0, { maxSlope: 30 }).state).toBe('reached');
+ // Across the ramp at an angle it is gentler: at 20 degrees a walker switches back up it, at 15 not even that.
+ expect(findGroundPath(ramp, 0, 0, 80, 0, { maxSlope: 20 }).state).toBe('reached');
+ const steep = findGroundPath(ramp, 0, 0, 80, 0, { maxSlope: 15, detour: 0.2 });
+ expect(steep.state).toBe('unreachable');
+ expect(steep.path.length).toBeGreaterThan(0);
+ });
+
+ it('keeps out of refused places, and says when an end stands in one', () => {
+ const moat = (x: number, z: number) => Math.hypot(x - 100, z) > 20 && Math.hypot(x - 100, z) < 30;
+ expect(findGroundPath(flat, 0, 0, 100, 0, { blocked: moat }).state).toBe('unreachable');
+ expect(findGroundPath(flat, 0, 0, 100, 25, { blocked: moat }).state).toBe('noGround');
+ expect(findGroundPath({ heightAt: () => null }, 0, 0, 10, 0).state).toBe('noGround');
+ });
+
+ it('says it ran out rather than claiming there is no way', () => {
+ expect(findGroundPath(cliff, 0, 0, 100, 0, { step: 1, maxCells: 50 }).state).toBe('exhausted');
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index e04c322cd..ad1850955 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2800,4 +2800,8 @@ export const NOTED = {
{"note":"World rules as a file, with an editor."},
"feat(editor): world rules editor for .esworld files":
{"note":"World rules as a file, with an editor."},
+ "fix(editor): world rules list selects like the folder tree":
+ {"note":"World rules as a file, with an editor."},
+ "feat(terrain): findPath asks whether a place can be walked to under a slope limit":
+ {"note":"Whether a place can be walked to."},
};