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(water): the sea fills only what joins it, a body is water only over its ground, bodies carry stable ids, and basins show where water gathers

yhh901d3bc0b2be
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a746f32e..613997275 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,6 +26,7 @@ published separately; it ships inside the editor.
- **Terrain collision, the same ground that is drawn.** 3D bodies and characters now collide with a `Terrain`: it is built in tiles round everything that moves on it (`collision`, `collisionDistance`, `collisionLayer`, `friction`), the tile under a body at once, and kept through a rebuild until the new ground replaces it. What is collided with, what `Terrains.heightAt` and `normalAt` answer and the finest level drawn near the eye are now one set of triangles, so a ray, a query and the picture agree wherever the camera is; `Terrains.collisionReadyAt` says when the ground under a point is ready. Any system that makes static geometry while the game runs can hand it to the 3D world through the new `CollisionGeometry` resource.
- **Procedural chunks, with one owner and one budget.** What a game makes as it runs is now chunks of layers in `ProceduralChunks` (`chunksOf(app)`): each layer says how it is cut, how far round the streaming sources it is wanted and how a chunk is made, published and released, and the chunks are made nearest first within the frame's budget (the one `Bakes.budgetMs`, shared with the bakes and the terrain's pages), released with everything they published past the unload radius, and made again when the layer's generation changes, the old version staying until the new one replaces it; an answer for an older generation is thrown away. `status` and `stateAt` say where they stand. Terrain collision and foliage cells are layers: plants now grow round the eye out to `drawDistance` and are let go past it, and a changed field or ground regrows them without blinking out.
- **Generated worlds.** The new `esengine/worldgen` lays a world out by a game's rules as it is explored: biomes weighed from fields (the terrain's height and slope, the water's depth, seeded moisture, temperature and rock, and a game's own), mixed at their edges and painting the terrain; recipes an artist composes (an anchor and members round it, with footprint apart from canopy) placed in layers, big things first, each keeping clear of what was placed before it; and `WorldZone`s (a home, a road, a building) that keep out what they name and hold a biome, fading at their edge. The same seed lays out the same world in whatever order its chunks are made, every placement has an id that outlives rules added later, interactive ones are entities with a `PlacedObject`, and what players change (`diffs().remove(id)`) is kept apart and laid over before anything is shown. `plan().explain(x, z)` says why anything stands or does not. A new example, Generated World, walks through one.
+- **Which water a place is.** The sea fills only low ground joined to the open sea past the water zone's edge: a hollow below its level walled off by higher ground stays dry (or holds a lake of its own). A lake or a river is water only where its surface is over its ground, so a hill inside its outline is land, for what is drawn and what `Waters.sample` answers, whatever order the bodies were added in. `WaterBody.bodyId` names a body the same in every session; `Waters.sample` carries it and `Waters.bodyAt(x, z)` says which body a place belongs to. `findBasins` gives a game the ground's basins (each filled to the lowest point of its rim, with its outlet), the drainage down to the edge and the sea's reach, for deciding where its lakes and rivers go; `drainPath` follows the water from a point.
- **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.
- **Bakes run over frames, with progress.** Work that used to hold a frame until it was done (a terrain worn by rain, a water zone baked, terrain chunks built, plants grown) is now spread over frames within a budget, and listed with its progress in the new `Bakes` resource (`bakesOf(app).active`). The editor's status bar shows it as a bar, for the edit world and for the game running in Play, and a game can show it on a loading screen. Plants wait for the ground and the water they stand on instead of being grown twice.
- **Eroded and warped terrain.** `Terrain.erosion` wears the ground with rain (a heightmap's as well as the noise's): gullies down the slopes, sharper ridges, silt in the valleys, and dirt painted where the water ran; the same seed wears the same ground. `Terrain.warp` bends the noise by noise of its own for winding valleys and bent ridges. `erodeHeightfield` and `erosionJob` do the same for a tool.
diff --git a/docs/WORLD_GENERATION_PLAN.md b/docs/WORLD_GENERATION_PLAN.md
index e4228f96d..6700eb17a 100644
--- a/docs/WORLD_GENERATION_PLAN.md
+++ b/docs/WORLD_GENERATION_PLAN.md
@@ -66,9 +66,9 @@
| 优先级 | 能力 | 当前状态 | 验收 |
| --- | --- | --- | --- |
-| P0 引擎 | 海洋范围掩码/连通性:只有与开阔海在海面高度下连通的低地属于海 | 未做:区域内海洋按“地面低于海面”判定,封闭干盆地会被填水 | 隔绝的低于海面的干盆地不显示海水、不判为水下 |
-| P0 引擎 | 多水体命中规则:范围、垂向有效区间/底部、优先级、归属 | 部分:区域烘焙已让湖/河优先于海,查询读同一场且与注册顺序无关;尚缺垂向有效区间(陆地落在湖轮廓内的判定)与水体身份 | 上方湖泊不被下方海洋抢先;顺序无关;陆地不被当作水域 |
-| P0 游戏+引擎接口 | 海域连通、盆地/出口、水系连接、独立水位、河床、稳定 waterBodyId | 未做(引擎侧需提供数据接口) | 跨块水位/岸线连续;高湖、低湖与干盆地共存;流向有效 |
+| P0 引擎 | 海洋范围掩码/连通性:只有与开阔海在海面高度下连通的低地属于海 | 已完成:烘焙先取整片网格地面,从区域边缘泛洪,未连通的低于海面洼地为陆地(`zone.ts openSea`);测试 `water-bodies.test.ts` | 隔绝的低于海面的干盆地不显示海水、不判为水下 |
+| P0 引擎 | 多水体命中规则:范围、垂向有效区间/底部、优先级、归属 | 已完成:湖/河只在水面高于地面处成立(轮廓内高出水面的陆地为陆地);湖/河优先于海;与顺序无关(测试逐格比对);`WaterBody.bodyId` 稳定身份,`Waters.sample().bodyId`、`Waters.bodyAt(x,z)` | 上方湖泊不被下方海洋抢先;顺序无关;陆地不被当作水域 |
+| P0 游戏+引擎接口 | 海域连通、盆地/出口、水系连接、独立水位、河床、稳定 waterBodyId | 引擎接口已提供:`findBasins`(优先级泛洪:盆地溢出水位/最深点/出口、填洼高度、排水树与汇流量、海域)、`drainPath`;稳定 `bodyId`。由游戏据此生成湖泊与河流;河床刻蚀仍欠(P1) | 跨块水位/岸线连续;高湖、低湖与干盆地共存;流向有效 |
| P1 引擎+美术 | 河湖接缝、入海口、急流/瀑布,按类型配置外观 | 部分:区域场已消除河湖接缝;拍岸浪、岸边柔化已有;河口水流纹理仍有问题 | 交界无重复透明面/突变 |
### 后续(不阻塞首块可玩地表)
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
index 4483870cd..8aaf0e416 100644
--- a/docs/astro/src/content/docs/graphics/water.mdx
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -17,7 +17,8 @@ into one surface. The entity places the body; it may be turned about its up, not
| Field | What it does |
|---|---|
-| `form` | **Ocean**: without an edge, at the entity's height everywhere the ground is lower, and on past the zone. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity, or the outline in `boundary`, at the entity's height. **River**: follows the `Spline` on the same entity. |
+| `form` | **Ocean**: without an edge, at the entity's height wherever the ground is lower and joined to the open sea, and on past the zone. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity, or the outline in `boundary`, at the entity's height. **River**: follows the `Spline` on the same entity. |
+| `bodyId` | What the game calls the body, the same in every session (an entity's number is not): what a query names the water by. Empty is named by its entity. |
| `sizeX`, `sizeZ` | A lake's size, when it has no outline of its own. |
| `boundary` | A lake's outline: three points or more round it on its own xz plane. Empty is the rectangle. |
| `shoreWidth` | How far in from the shore, and how deep, the waves take to come to full height, for every form. 0 leaves them whole to the edge. |
@@ -99,11 +100,28 @@ A lake is its outline at its entity's height. The zone takes the signed distance
and from the two the share of the waves a point keeps (none at the edge or where the water is not deep, all from `shoreWidth` in). The surface is cut where the
outline is (traced at the zone's resolution, not at the mesh's cells), the geometry and the shading calm toward the shore, and the shore foams along it.
-The water fills the low ground and meets the hills where they cross it (the depth test does that), and the waves die out as it shallows. Over no terrain a lake is
-as deep as it likes. The outline should not cross itself.
+The water fills the low ground and meets the hills where they cross it, and the waves die out as it shallows. A body is water only where its surface is over
+its ground: a hill or a bank inside a lake's outline or a river's width that stands above the water is land, for what is drawn and for what is asked. Over no
+terrain a lake is as deep as it likes. The outline should not cross itself.
An ocean takes its shore from the terrain the same way: inside the zone it is cut where the ground stands above its level, and its waves calm over `shoreWidth`
-of depth. Past the zone it is everywhere at its level with its waves whole.
+of depth. It is the open sea, which lies past the zone's edge: low ground is sea only where low ground joins it to that edge, so a hollow below the sea's level
+walled off by higher ground stays dry (or holds a lake of its own, at its own level). Past the zone it is everywhere at its level with its waves whole.
+
+Where bodies overlap, a lake or a river holds the water over the ocean, and which body a place belongs to does not depend on the order the bodies were added.
+
+### Basins and drainage
+
+Deciding where a world's lakes and rivers go is a game's (or its generator's) work; `findBasins(grid, ground, { seaLevel })` gives it the ground's side of it,
+from one priority flood over a grid:
+
+- `basins`: each hollow, with the `level` water would fill it to (the lowest point of its rim), its `deepest` point and its `outlet`, where it runs over;
+- `filled`: the height water would stand at over each texel; `basin`: which basin a texel is in;
+- `downstream` and `accumulation`: where each texel drains to, down to the region's edge, and how much drains through it, which is where rivers run;
+ `drainPath(map, x, z)` follows it from a point;
+- `sea`: with a sea level, the low ground the sea reaches from the edge.
+
+A lake placed at a basin's `level` over its outline fills it to the brim; a river from its `outlet` down `drainPath` runs where the water would.
## Rivers
@@ -244,7 +262,7 @@ The lite water costs no vertex work for the waves, and the shading still moves,
`Waters.sample(x, y, z)` (the `WatersRes` resource) answers from the zone's field, the same numbers the surface is drawn from:
-- `entity`: the body that owns most of the water there (where two meet, the one the point is further inside);
+- `entity`: the body that owns most of the water there (where two meet, the one the point is further inside), and `bodyId`, what the game calls it;
- `depth`: how far the point is above the surface (negative under it), in world units;
- `normal`: the surface's normal there, in world space;
- `surface`: the world position on the surface straight above or below the point;
@@ -252,7 +270,8 @@ The lite water costs no vertex work for the waves, and the shading still moves,
- `flow`: how the water moves there, in world units a second (a river's current; still water is zero).
It reads the same formula the shader draws, at the time of the frame, with the height the waves stand to there and the ripples. `Waters.heightAt(x, z)` is the
-surface's height alone. A point over no water (outside every shore, or past the zone with no ocean) answers `null`.
+surface's height alone. A point over no water (outside every shore, or past the zone with no ocean) answers `null`. `Waters.bodyAt(x, z)` says which body a
+place belongs to: its entity, its `bodyId`, its form and its level at rest.
The surface the code reads is the full wave sum; a coarse far ring draws less of it (see above), so near the horizon the two can
differ by the short waves, which are small.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
index c2bc69fa7..35a5f2fa6 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
@@ -13,7 +13,8 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一
| 字段 | 作用 |
|---|---|
-| `form` | **海洋**:没有边,在地面低于实体高度的地方处处都在这个高度,并一直延伸到区域之外。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形,或 `boundary` 给出的轮廓,在实体的高度上。**河流**:沿同一实体上的 `Spline`。 |
+| `form` | **海洋**:没有边,在地面低于实体高度且与开阔海相连的地方处处都在这个高度,并一直延伸到区域之外。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形,或 `boundary` 给出的轮廓,在实体的高度上。**河流**:沿同一实体上的 `Spline`。 |
+| `bodyId` | 游戏给这个水体起的名字,在每次运行中都一样(实体编号不是):查询用它来称呼这片水。留空则用实体称呼。 |
| `sizeX`、`sizeZ` | 湖泊没有自己的轮廓时的尺寸。 |
| `boundary` | 湖泊的轮廓:它自己的 xz 平面上围一圈的三个或更多点。留空就是矩形。 |
| `shoreWidth` | 从岸边往里多远、水多深,波浪才长到完整高度,对所有形态都适用。0 表示波浪一直完整到岸边。 |
@@ -69,9 +70,22 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一
湖泊是位于实体高度上的轮廓。区域取到轮廓的有符号距离,场景里有 `Terrain` 时还取水在地形之上的深度,由这两个量得出一个点保留多少波浪(在岸边或水很浅处一点不留,从 `shoreWidth` 往里全留)。水面按轮廓裁出(按区域的分辨率描出,而不是按网格的格子),几何体和着色都向岸边变平静,岸边还会起泡沫。
-水填满低处,在山丘与它相交的地方被山丘截断(深度测试做到这一点),波浪随变浅而消失。没有地形时,湖要多深有多深。轮廓不应自相交。
+水填满低处,在山丘与它相交的地方被截断,波浪随变浅而消失。水体只在水面高于地面的地方才是水:湖泊轮廓或河流宽度之内、高出水面的山丘或河岸是陆地,画面和查询都如此。没有地形时,湖要多深有多深。轮廓不应自相交。
-海洋也同样从地形取岸线:在区域内,地面高出海平面的地方被裁掉,波浪在 `shoreWidth` 的水深内变平静。在区域外,海洋处处在它的水位上,波浪完整。
+海洋也同样从地形取岸线:在区域内,地面高出海平面的地方被裁掉,波浪在 `shoreWidth` 的水深内变平静。它是区域边缘之外的开阔海:低地只有通过低地连到那条边缘时才是海,所以被更高地面围住、低于海平面的洼地保持干燥(或者装着自己水位的湖)。在区域外,海洋处处在它的水位上,波浪完整。
+
+水体重叠时,湖泊或河流优先于海洋占有那里的水;一个地方属于哪个水体,与水体加入的顺序无关。
+
+### 盆地与汇流
+
+决定世界的湖泊和河流放在哪里是游戏(或它的生成器)的事;`findBasins(grid, ground, { seaLevel })` 从网格上的一次优先级泛洪给出地面这一方的信息:
+
+- `basins`:每个洼地,带着水会把它填到的 `level`(它边缘的最低点)、最深点 `deepest`,以及溢出的出口 `outlet`;
+- `filled`:每个格子上水会到达的高度;`basin`:格子属于哪个盆地;
+- `downstream` 和 `accumulation`:每个格子排水流向哪里,一直到区域边缘,以及有多少水流经它,河流就在这里;`drainPath(map, x, z)` 从某点沿它走下去;
+- `sea`:给了海平面时,海从边缘到达的低地。
+
+在盆地的 `level` 上按它的轮廓放一个湖就正好把它填满;从它的 `outlet` 沿 `drainPath` 放一条河,就流在水会流的地方。
## 河流
@@ -167,14 +181,14 @@ Details 只显示水体这种形态用得到的字段:湖有尺寸和边界,河
`Waters.sample(x, y, z)`(资源 `WatersRes`)从区域的场作答,和画水面用的是同一组数:
-- `entity`:那里占水最多的水体(两个水体相接处,是这个点在其内部更深的那个);
+- `entity`:那里占水最多的水体(两个水体相接处,是这个点在其内部更深的那个),以及 `bodyId`,游戏给它起的名字;
- `depth`:这个点高出表面多少(在下面则为负),世界单位;
- `normal`:表面在那里的法线,世界空间;
- `surface`:这个点正上方或正下方、表面上的世界坐标;
- `inside`:这个点是否在水上:只要回答不是 null,就总是;
- `flow`:水在那里怎么流动,世界单位每秒(河流的水流;静水为零)。
-它读的是着色器画的同一个公式,取这一帧的时间,带上那里波浪的高度和涟漪。`Waters.heightAt(x, z)` 只给出水面的高度。点上方没有水(在所有岸线之外,或在区域之外且没有海洋)则返回 `null`。
+它读的是着色器画的同一个公式,取这一帧的时间,带上那里波浪的高度和涟漪。`Waters.heightAt(x, z)` 只给出水面的高度。点上方没有水(在所有岸线之外,或在区域之外且没有海洋)则返回 `null`。`Waters.bodyAt(x, z)` 说明一个地方属于哪个水体:它的实体、`bodyId`、形态和静止水位。
代码读到的是完整的波浪和;远处的粗圈画得少一些(见上),所以在接近地平线处两者可能相差那些短波,它们本来就很小。
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 1c8b7ac5b..e411fdb95 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -7318,6 +7318,12 @@
"River"
]
},
+ {
+ "key": "bodyId",
+ "type": "string",
+ "default": "empty",
+ "doc": "What the game calls this body, the same in every session: what a query names the water by. Empty is named by its entity."
+ },
{
"key": "sizeX",
"type": "number",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 4e6272b82..22731733d 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: 115 public · 159 beta · 1825 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1830 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1563,6 +1563,34 @@ static prototype: Bakes
ResourceDef<Bakes>
```
+## Basin — interface @experimental
+```
+cells: number
+deepest: { x: number; z: number; y: number; }
+id: number
+level: number
+outlet: { x: number; z: number; y: number; index: number; }
+```
+
+## BasinMap — interface @experimental
+```
+accumulation: Float32Array<ArrayBufferLike>
+basin: Int32Array<ArrayBufferLike>
+basins: Basin[]
+downstream: Int32Array<ArrayBufferLike>
+filled: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+ground: Float32Array<ArrayBufferLike>
+sea: Uint8Array<ArrayBufferLike>
+```
+
+## BasinOptions — interface @experimental
+```
+minCells: number | undefined
+minDepth: number | undefined
+seaLevel: number | undefined
+```
+
## BatchBreak — enum @experimental
```
Blend = 4
@@ -11684,6 +11712,7 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+bodyId: string
boundary: Point2[]
flowSpeed: number
form: number
@@ -11732,6 +11761,7 @@ static prototype: WaterPlugin
## WaterSample — interface @experimental
```
+bodyId: string
depth: number
entity: number
flow: [number, number, number]
@@ -11775,6 +11805,7 @@ waveSpeed: number
@internal ripples_: RippleField | null
@internal zone_: WaterZoneData
baking: boolean
+bodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | null
depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
@@ -13344,6 +13375,11 @@ DragPlugin
() => DragonBonesPlugin
```
+## drainPath — function @experimental
+```
+(map: BasinMap, x: number, z: number): { x: number; z: number; y: number; }[]
+```
+
## drawPhysics3DDebug — function @experimental
```
(app: App, contacts?: readonly Contact3D[]): void
@@ -13589,6 +13625,11 @@ EventBindingPlugin
(url: string, maxEdge?: number): Promise<DecodedPixels>
```
+## findBasins — function @experimental
+```
+(grid: ZoneGrid, ground: (x: number, z: number) => number | null, options?: BasinOptions): BasinMap
+```
+
## findControllerOwner — function @experimental
```
(world: World, entity: Entity, name: string): Entity | null
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index f21b598e4..ea8db522d 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: 115 public · 164 beta · 1844 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1849 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1563,6 +1563,34 @@ static prototype: Bakes
ResourceDef<Bakes>
```
+## Basin — interface @experimental
+```
+cells: number
+deepest: { x: number; z: number; y: number; }
+id: number
+level: number
+outlet: { x: number; z: number; y: number; index: number; }
+```
+
+## BasinMap — interface @experimental
+```
+accumulation: Float32Array<ArrayBufferLike>
+basin: Int32Array<ArrayBufferLike>
+basins: Basin[]
+downstream: Int32Array<ArrayBufferLike>
+filled: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+ground: Float32Array<ArrayBufferLike>
+sea: Uint8Array<ArrayBufferLike>
+```
+
+## BasinOptions — interface @experimental
+```
+minCells: number | undefined
+minDepth: number | undefined
+seaLevel: number | undefined
+```
+
## BatchBreak — enum @experimental
```
Blend = 4
@@ -11897,6 +11925,7 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+bodyId: string
boundary: Point2[]
flowSpeed: number
form: number
@@ -11945,6 +11974,7 @@ static prototype: WaterPlugin
## WaterSample — interface @experimental
```
+bodyId: string
depth: number
entity: number
flow: [number, number, number]
@@ -11988,6 +12018,7 @@ waveSpeed: number
@internal ripples_: RippleField | null
@internal zone_: WaterZoneData
baking: boolean
+bodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | null
depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
@@ -13597,6 +13628,11 @@ DragPlugin
() => DragonBonesPlugin
```
+## drainPath — function @experimental
+```
+(map: BasinMap, x: number, z: number): { x: number; z: number; y: number; }[]
+```
+
## drawPhysics3DDebug — function @experimental
```
(app: App, contacts?: readonly Contact3D[]): void
@@ -13842,6 +13878,11 @@ EventBindingPlugin
(url: string, maxEdge?: number): Promise<DecodedPixels>
```
+## findBasins — function @experimental
+```
+(grid: ZoneGrid, ground: (x: number, z: number) => number | null, options?: BasinOptions): BasinMap
+```
+
## findControllerOwner — function @experimental
```
(world: World, entity: Entity, name: string): Entity | null
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index f516eab80..535208313 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: 115 public · 161 beta · 1824 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1829 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1558,6 +1558,34 @@ static prototype: Bakes
ResourceDef<Bakes>
```
+## Basin — interface @experimental
+```
+cells: number
+deepest: { x: number; z: number; y: number; }
+id: number
+level: number
+outlet: { x: number; z: number; y: number; index: number; }
+```
+
+## BasinMap — interface @experimental
+```
+accumulation: Float32Array<ArrayBufferLike>
+basin: Int32Array<ArrayBufferLike>
+basins: Basin[]
+downstream: Int32Array<ArrayBufferLike>
+filled: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+ground: Float32Array<ArrayBufferLike>
+sea: Uint8Array<ArrayBufferLike>
+```
+
+## BasinOptions — interface @experimental
+```
+minCells: number | undefined
+minDepth: number | undefined
+seaLevel: number | undefined
+```
+
## BatchBreak — enum @experimental
```
Blend = 4
@@ -11679,6 +11707,7 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+bodyId: string
boundary: Point2[]
flowSpeed: number
form: number
@@ -11727,6 +11756,7 @@ static prototype: WaterPlugin
## WaterSample — interface @experimental
```
+bodyId: string
depth: number
entity: number
flow: [number, number, number]
@@ -11770,6 +11800,7 @@ waveSpeed: number
@internal ripples_: RippleField | null
@internal zone_: WaterZoneData
baking: boolean
+bodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | null
depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
@@ -13339,6 +13370,11 @@ DragPlugin
() => DragonBonesPlugin
```
+## drainPath — function @experimental
+```
+(map: BasinMap, x: number, z: number): { x: number; z: number; y: number; }[]
+```
+
## drawPhysics3DDebug — function @experimental
```
(app: App, contacts?: readonly Contact3D[]): void
@@ -13584,6 +13620,11 @@ EventBindingPlugin
(url: string, maxEdge?: number): Promise<DecodedPixels>
```
+## findBasins — function @experimental
+```
+(grid: ZoneGrid, ground: (x: number, z: number) => number | null, options?: BasinOptions): BasinMap
+```
+
## findControllerOwner — function @experimental
```
(world: World, entity: Entity, name: string): Entity | null
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 8f3bbabd1..5d7bc35a4 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: 115 public · 159 beta · 1846 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1851 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1558,6 +1558,34 @@ static prototype: Bakes
ResourceDef<Bakes>
```
+## Basin — interface @experimental
+```
+cells: number
+deepest: { x: number; z: number; y: number; }
+id: number
+level: number
+outlet: { x: number; z: number; y: number; index: number; }
+```
+
+## BasinMap — interface @experimental
+```
+accumulation: Float32Array<ArrayBufferLike>
+basin: Int32Array<ArrayBufferLike>
+basins: Basin[]
+downstream: Int32Array<ArrayBufferLike>
+filled: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+ground: Float32Array<ArrayBufferLike>
+sea: Uint8Array<ArrayBufferLike>
+```
+
+## BasinOptions — interface @experimental
+```
+minCells: number | undefined
+minDepth: number | undefined
+seaLevel: number | undefined
+```
+
## BatchBreak — enum @experimental
```
Blend = 4
@@ -11978,6 +12006,7 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+bodyId: string
boundary: Point2[]
flowSpeed: number
form: number
@@ -12026,6 +12055,7 @@ static prototype: WaterPlugin
## WaterSample — interface @experimental
```
+bodyId: string
depth: number
entity: number
flow: [number, number, number]
@@ -12069,6 +12099,7 @@ waveSpeed: number
@internal ripples_: RippleField | null
@internal zone_: WaterZoneData
baking: boolean
+bodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | null
depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
@@ -13643,6 +13674,11 @@ DragPlugin
() => DragonBonesPlugin
```
+## drainPath — function @experimental
+```
+(map: BasinMap, x: number, z: number): { x: number; z: number; y: number; }[]
+```
+
## drawPhysics3DDebug — function @experimental
```
(app: App, contacts?: readonly Contact3D[]): void
@@ -13888,6 +13924,11 @@ EventBindingPlugin
(url: string, maxEdge?: number): Promise<DecodedPixels>
```
+## findBasins — function @experimental
+```
+(grid: ZoneGrid, ground: (x: number, z: number) => number | null, options?: BasinOptions): BasinMap
+```
+
## findControllerOwner — function @experimental
```
(world: World, entity: Entity, name: string): Entity | null
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index 9bedf08b7..fa1a1777f 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -1,7 +1,35 @@
# API surface — esengine/water
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 34 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 39 experimental · 0 deprecated
+
+## Basin — interface @experimental
+```
+cells: number
+deepest: { x: number; z: number; y: number; }
+id: number
+level: number
+outlet: { x: number; z: number; y: number; index: number; }
+```
+
+## BasinMap — interface @experimental
+```
+accumulation: Float32Array<ArrayBufferLike>
+basin: Int32Array<ArrayBufferLike>
+basins: Basin[]
+downstream: Int32Array<ArrayBufferLike>
+filled: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+ground: Float32Array<ArrayBufferLike>
+sea: Uint8Array<ArrayBufferLike>
+```
+
+## BasinOptions — interface @experimental
+```
+minCells: number | undefined
+minDepth: number | undefined
+seaLevel: number | undefined
+```
## FieldSample — interface @experimental
```
@@ -99,6 +127,7 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+bodyId: string
boundary: Point2[]
flowSpeed: number
form: number
@@ -147,6 +176,7 @@ static prototype: WaterPlugin
## WaterSample — interface @experimental
```
+bodyId: string
depth: number
entity: number
flow: [number, number, number]
@@ -190,6 +220,7 @@ waveSpeed: number
@internal ripples_: RippleField | null
@internal zone_: WaterZoneData
baking: boolean
+bodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | null
depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
@@ -224,6 +255,16 @@ speed: number
(width: number, widest: number): number
```
+## drainPath — function @experimental
+```
+(map: BasinMap, x: number, z: number): { x: number; z: number; y: number; }[]
+```
+
+## findBasins — function @experimental
+```
+(grid: ZoneGrid, ground: (x: number, z: number) => number | null, options?: BasinOptions): BasinMap
+```
+
## floatingForce — function @experimental
```
(body: FloatingBody, point: [number, number, number], sample: WaterSample | null, floating: FloatingData, gravity: [number, number, number], ppu: number, dt: number, points: number): FloatingForce | null
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 142c3793a..d19750502 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: 115 public · 159 beta · 1837 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1842 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1558,6 +1558,34 @@ static prototype: Bakes
ResourceDef<Bakes>
```
+## Basin — interface @experimental
+```
+cells: number
+deepest: { x: number; z: number; y: number; }
+id: number
+level: number
+outlet: { x: number; z: number; y: number; index: number; }
+```
+
+## BasinMap — interface @experimental
+```
+accumulation: Float32Array<ArrayBufferLike>
+basin: Int32Array<ArrayBufferLike>
+basins: Basin[]
+downstream: Int32Array<ArrayBufferLike>
+filled: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+ground: Float32Array<ArrayBufferLike>
+sea: Uint8Array<ArrayBufferLike>
+```
+
+## BasinOptions — interface @experimental
+```
+minCells: number | undefined
+minDepth: number | undefined
+seaLevel: number | undefined
+```
+
## BatchBreak — enum @experimental
```
Blend = 4
@@ -11686,6 +11714,7 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+bodyId: string
boundary: Point2[]
flowSpeed: number
form: number
@@ -11734,6 +11763,7 @@ static prototype: WaterPlugin
## WaterSample — interface @experimental
```
+bodyId: string
depth: number
entity: number
flow: [number, number, number]
@@ -11777,6 +11807,7 @@ waveSpeed: number
@internal ripples_: RippleField | null
@internal zone_: WaterZoneData
baking: boolean
+bodyAt: (x: number, z: number) => { entity: Entity; bodyId: string; form: number; level: number; } | null
depthAt: (x: number, z: number, y: number) => number | null
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
@@ -13370,6 +13401,11 @@ DragPlugin
() => DragonBonesPlugin
```
+## drainPath — function @experimental
+```
+(map: BasinMap, x: number, z: number): { x: number; z: number; y: number; }[]
+```
+
## drawPhysics3DDebug — function @experimental
```
(app: App, contacts?: readonly Contact3D[]): void
@@ -13615,6 +13651,11 @@ EventBindingPlugin
(url: string, maxEdge?: number): Promise<DecodedPixels>
```
+## findBasins — function @experimental
+```
+(grid: ZoneGrid, ground: (x: number, z: number) => number | null, options?: BasinOptions): BasinMap
+```
+
## findControllerOwner — function @experimental
```
(world: World, entity: Entity, name: string): Entity | null
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 858b71adc..b97921645 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -825,6 +825,7 @@ export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './wa
export { WaterZone, WaterField, currentShare, type WaterZoneData, type FieldSample } from './water/zone';
export { buildOceanMesh, oceanReach, oceanSnap } from './water/waterMesh';
export { polygonSdf, shoreDamp, type Point2 } from './water/shore';
+export { findBasins, drainPath, type Basin, type BasinMap, type BasinOptions } from './water/basins';
export {
scatterCell, buildGrassMesh, buildInstancedMesh, buildBillboardMesh, rng,
type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
diff --git a/sdk/src/water/basins.ts b/sdk/src/water/basins.ts
new file mode 100644
index 000000000..c13db69b5
--- /dev/null
+++ b/sdk/src/water/basins.ts
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file basins.ts
+ * @brief Where water would gather and how it would run off a piece of ground: basins with their spill levels and outlets, and the
+ * drainage down to the edge. For a game to decide its lakes, rivers and sea, not water that is drawn.
+ *
+ * @details One priority flood (Barnes et al., 2014) from the region's edge, lowest first. Each texel is reached from a neighbour no
+ * higher than it would drain to, so:
+ * - a texel reached from above its own ground is in a basin, filled to the level the flood stood at: the basin's spill
+ * level, where a lake there would run over, through its outlet;
+ * - the texel each one was reached from is where its water goes, so every texel drains along a tree to the edge, flats and
+ * basins included, and the accumulation along it (how many texels drain through each) is where rivers run;
+ * - with a sea level, low ground the flood reaches from the edge without climbing over it is sea; a basin below the sea that
+ * is walled off from it stays a basin (dry, or a lake at its own level).
+ * The answer depends only on the ground and the region, never on the order anything is asked.
+ */
+import type { ZoneGrid } from './zone';
+
+/** A basin: the texels a lake filling it to its spill level would cover. */
+export interface Basin {
+ id: number;
+ /** The height water stands at when the basin is full: the lowest point of its rim. */
+ level: number;
+ /** How many texels it covers, and its deepest point. */
+ cells: number;
+ deepest: { x: number; z: number; y: number };
+ /** Where it runs over its rim, and the texel index there. */
+ outlet: { x: number; z: number; y: number; index: number };
+}
+
+export interface BasinMap {
+ grid: ZoneGrid;
+ /** The ground's height per texel (row by row from minZ), and the height water would fill it to. */
+ ground: Float32Array;
+ filled: Float32Array;
+ /** The texel each one drains to; -1 at the edge, where water leaves the region. */
+ downstream: Int32Array;
+ /** How many texels drain through each, itself included. */
+ accumulation: Float32Array;
+ /** The basin each texel is in, or -1. */
+ basin: Int32Array;
+ /** 1 where the ground is the sea's (with a sea level). */
+ sea: Uint8Array;
+ basins: Basin[];
+}
+
+export interface BasinOptions {
+ /** The sea's level: low ground joined to the edge below it is sea, not basin. */
+ seaLevel?: number;
+ /** A basin shallower than this, or of fewer texels, is not kept as one (its texels still drain through it). */
+ minDepth?: number;
+ minCells?: number;
+}
+
+/** A binary heap of texels by height, lowest first; ties in the order pushed. */
+class Heap {
+ private readonly k: number[] = [];
+ private readonly h: number[] = [];
+ private readonly o: number[] = [];
+ private n = 0;
+ get size(): number { return this.k.length; }
+ push(key: number, height: number): void {
+ this.k.push(key); this.h.push(height); this.o.push(this.n++);
+ let i = this.k.length - 1;
+ while (i > 0) {
+ const p = (i - 1) >> 1;
+ if (!this.less(i, p)) break;
+ this.swap(i, p);
+ i = p;
+ }
+ }
+ pop(): number {
+ const top = this.k[0]!;
+ const lk = this.k.pop()!, lh = this.h.pop()!, lo = this.o.pop()!;
+ if (this.k.length > 0) {
+ this.k[0] = lk; this.h[0] = lh; this.o[0] = lo;
+ let i = 0;
+ for (;;) {
+ const l = i * 2 + 1, r = l + 1;
+ let m = i;
+ if (l < this.k.length && this.less(l, m)) m = l;
+ if (r < this.k.length && this.less(r, m)) m = r;
+ if (m === i) break;
+ this.swap(i, m);
+ i = m;
+ }
+ }
+ return top;
+ }
+ private less(a: number, b: number): boolean {
+ return this.h[a]! < this.h[b]! || (this.h[a] === this.h[b] && this.o[a]! < this.o[b]!);
+ }
+ private swap(a: number, b: number): void {
+ [this.k[a], this.k[b]] = [this.k[b]!, this.k[a]!];
+ [this.h[a], this.h[b]] = [this.h[b]!, this.h[a]!];
+ [this.o[a], this.o[b]] = [this.o[b]!, this.o[a]!];
+ }
+}
+
+/** The basins and drainage of the ground over `grid`. Ground not known is taken as the sea's level (or as low as the lowest known). */
+export function findBasins(grid: ZoneGrid, ground: (x: number, z: number) => number | null, options: BasinOptions = {}): BasinMap {
+ const { nx, nz } = grid;
+ const n = nx * nz;
+ const at = (k: number): [number, number] => [
+ grid.minX + ((k % nx) / Math.max(nx - 1, 1)) * grid.sizeX,
+ grid.minZ + (Math.floor(k / nx) / Math.max(nz - 1, 1)) * grid.sizeZ,
+ ];
+ const g = new Float32Array(n);
+ let lowest = Infinity;
+ const known: boolean[] = new Array(n);
+ for (let k = 0; k < n; k++) {
+ const [x, z] = at(k);
+ const y = ground(x, z);
+ known[k] = y !== null;
+ g[k] = y ?? 0;
+ if (y !== null) lowest = Math.min(lowest, y);
+ }
+ const unknown = options.seaLevel ?? (Number.isFinite(lowest) ? lowest : 0);
+ for (let k = 0; k < n; k++) if (!known[k]) g[k] = unknown;
+
+ const filled = new Float32Array(n);
+ const downstream = new Int32Array(n).fill(-1);
+ const sea = new Uint8Array(n);
+ const done = new Uint8Array(n);
+ const order: number[] = [];
+ const heap = new Heap();
+ const sl = options.seaLevel;
+ const seed = (k: number): void => {
+ if (done[k]) return;
+ done[k] = 1;
+ filled[k] = g[k]!;
+ if (sl !== undefined && g[k]! < sl) sea[k] = 1;
+ heap.push(k, g[k]!);
+ };
+ for (let i = 0; i < nx; i++) { seed(i); seed((nz - 1) * nx + i); }
+ for (let j = 0; j < nz; j++) { seed(j * nx); seed(j * nx + nx - 1); }
+ while (heap.size > 0) {
+ const c = heap.pop();
+ order.push(c);
+ const ci = c % nx, cj = Math.floor(c / nx);
+ for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) {
+ if (!di && !dj) continue;
+ const i = ci + di, j = cj + dj;
+ if (i < 0 || j < 0 || i >= nx || j >= nz) continue;
+ const k = j * nx + i;
+ if (done[k]) continue;
+ done[k] = 1;
+ downstream[k] = c;
+ filled[k] = Math.max(g[k]!, filled[c]!);
+ // The sea comes in from the edge over ground below it, and no further than that ground goes.
+ if (sea[c] && g[k]! < sl!) sea[k] = 1;
+ heap.push(k, filled[k]!);
+ }
+ }
+
+ // Through every texel drains what drains into it: the reverse of the order the flood reached them.
+ const accumulation = new Float32Array(n).fill(1);
+ for (let q = order.length - 1; q >= 0; q--) {
+ const k = order[q]!, d = downstream[k]!;
+ if (d >= 0) accumulation[d] += accumulation[k]!;
+ }
+
+ // The basins: texels filled above their ground (and not the sea), joined where they touch.
+ const basin = new Int32Array(n).fill(-1);
+ const basins: Basin[] = [];
+ const minDepth = options.minDepth ?? 0, minCells = options.minCells ?? 1;
+ const wet = (k: number): boolean => !sea[k] && filled[k]! - g[k]! > 1e-6;
+ for (let s = 0; s < n; s++) {
+ if (!wet(s) || basin[s]! >= 0) continue;
+ const id = basins.length, level = filled[s]!;
+ const members: number[] = [s];
+ basin[s] = id;
+ let deepest = s;
+ for (let q = 0; q < members.length; q++) {
+ const c = members[q]!, ci = c % nx, cj = Math.floor(c / nx);
+ if (g[c]! < g[deepest]!) deepest = c;
+ for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) {
+ const i = ci + di, j = cj + dj;
+ if (i < 0 || j < 0 || i >= nx || j >= nz) continue;
+ const k = j * nx + i;
+ if (basin[k]! < 0 && wet(k) && filled[k] === level) { basin[k] = id; members.push(k); }
+ }
+ }
+ // It runs over where the water leaving it first leaves it: down the drainage from its deepest point to the first texel outside.
+ let out = deepest;
+ while (out >= 0 && basin[out] === id) out = downstream[out]!;
+ const outlet = out >= 0 ? out : deepest;
+ if (level - g[deepest]! < minDepth || members.length < minCells) {
+ for (const k of members) basin[k] = -2;
+ continue;
+ }
+ const [dx, dz] = at(deepest), [ox, oz] = at(outlet);
+ basins.push({
+ id, level, cells: members.length, deepest: { x: dx, z: dz, y: g[deepest]! },
+ outlet: { x: ox, z: oz, y: g[outlet]!, index: outlet },
+ });
+ }
+ // Ids follow the kept basins in order; the dropped ones are no basin.
+ const remap = new Map<number, number>();
+ basins.forEach((b, i) => { remap.set(b.id, i); b.id = i; });
+ for (let k = 0; k < n; k++) basin[k] = basin[k]! >= 0 ? remap.get(basin[k]!) ?? -1 : -1;
+ return { grid, ground: g, filled, downstream, accumulation, basin, sea, basins };
+}
+
+/** The path water takes from (x, z) down the drainage, texel by texel, to the region's edge: a river's course, as world points. */
+export function drainPath(map: BasinMap, x: number, z: number): { x: number; z: number; y: number }[] {
+ const { grid } = map, { nx, nz } = grid;
+ const i = Math.round(((x - grid.minX) / grid.sizeX) * (nx - 1)), j = Math.round(((z - grid.minZ) / grid.sizeZ) * (nz - 1));
+ if (i < 0 || j < 0 || i >= nx || j >= nz) return [];
+ const out: { x: number; z: number; y: number }[] = [];
+ for (let k = j * nx + i; k >= 0; k = map.downstream[k]!) {
+ out.push({
+ x: grid.minX + ((k % nx) / Math.max(nx - 1, 1)) * grid.sizeX,
+ z: grid.minZ + (Math.floor(k / nx) / Math.max(nz - 1, 1)) * grid.sizeZ,
+ y: map.filled[k]!,
+ });
+ }
+ return out;
+}
diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.ts
index 43141eb40..c09965744 100644
--- a/sdk/src/water/index.ts
+++ b/sdk/src/water/index.ts
@@ -10,6 +10,7 @@ export { Floating, FloatingPlugin, floatingForce, wakeStrength, type FloatingBod
export { WaterZone, WaterField, currentShare, type WaterZoneData, type FieldSample } from './zone';
export { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';
export { polygonSdf, shoreDamp, type Point2 } from './shore';
+export { findBasins, drainPath, type Basin, type BasinMap, type BasinOptions } from './basins';
// Importing this subpath INSTALLS water — see tilemap/index.ts.
import { registerWaterSupport } from './waterSupport';
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 20e04ccc8..a809cb2e8 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -54,6 +54,8 @@ export const WaterForm = { Ocean: 0, Lake: 1, River: 2 } as const;
export interface WaterBodyData {
/** {@link WaterForm}. */
form: number;
+ /** What the game calls the body, the same in every session (an entity's number is not): what a query names the water by. */
+ bodyId: string;
/** A lake's extent along x and z, centred on its entity, when it has no outline of its own. An ocean has none: it goes on past the zone. */
sizeX: number;
sizeZ: number;
@@ -73,10 +75,11 @@ export interface WaterBodyData {
* @experimental
*/
export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {
- form: WaterForm.Lake, sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, flowSpeed: 2, waveHeight: 0.3,
+ form: WaterForm.Lake, bodyId: '', sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, flowSpeed: 2, waveHeight: 0.3,
}, {
fields: {
form: { enum: [{ label: 'Ocean', value: WaterForm.Ocean }, { label: 'Lake', value: WaterForm.Lake }, { label: 'River', value: WaterForm.River }], category: 'Shape', tooltip: 'An ocean is without edge: everywhere at its height where the ground is lower; a lake is a rectangle or an outline of its own; a river follows the Spline on the same entity.' },
+ bodyId: { category: 'Shape', tooltip: 'What the game calls this body, the same in every session: what a query names the water by. Empty is named by its entity.' },
sizeX: { min: 1, category: 'Shape', tooltip: 'A lake\'s size along x.', shownWhen: { field: 'form', values: [WaterForm.Lake] } },
sizeZ: { min: 1, category: 'Shape', tooltip: 'A lake\'s size along z.', shownWhen: { field: 'form', values: [WaterForm.Lake] } },
boundary: { category: 'Shape', tooltip: 'The outline of a lake: points round it on its own xz plane. Empty is the rectangle of its size.', shownWhen: { field: 'form', values: [WaterForm.Lake] } },
@@ -88,8 +91,9 @@ export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyD
/** What {@link Waters.sample} answers. */
export interface WaterSample {
- /** The entity of the body that holds the most of the water there. */
+ /** The entity of the body that holds the most of the water there, and what the game calls it (its `bodyId`). */
entity: Entity;
+ bodyId: string;
/** How far the point is above the surface (negative under it), in world units. */
depth: number;
/** The surface's normal at the point, in world space. */
@@ -169,7 +173,7 @@ export class Waters {
const [sx, sz] = waveSlope(params, x, z, time);
const len = Math.hypot(sx, 1, sz);
return {
- entity: s.key as Entity, depth: y - h, normal: [-sx / len, 1 / len, -sz / len], flow: [s.flowX, 0, s.flowZ], surface: [x, h, z], inside: true,
+ entity: s.key as Entity, bodyId: this.bodyIdOf(s.key as Entity), depth: y - h, normal: [-sx / len, 1 / len, -sz / len], flow: [s.flowX, 0, s.flowZ], surface: [x, h, z], inside: true,
};
}
@@ -188,6 +192,25 @@ export class Waters {
return this.ripples_?.heightAt(x, z) ?? 0;
}
+ /**
+ * The body of water at (x, z) and its surface at rest, or null where there is none: which water a place belongs to, for what a game
+ * keeps per body (a fishing spot, a level it raises) and a placement that keeps by the shore.
+ */
+ bodyAt(x: number, z: number): { entity: Entity; bodyId: string; form: number; level: number } | null {
+ const s = this.field_?.sample(x, z);
+ const world = this.app_?.world;
+ if (!s || !world || s.key < 0) return null;
+ const entity = s.key as Entity;
+ const body = world.valid(entity) && world.has(entity, WaterBody) ? world.get(entity, WaterBody) as WaterBodyData : null;
+ return { entity, bodyId: body?.bodyId || `entity:${entity}`, form: body?.form ?? WaterForm.Ocean, level: s.height };
+ }
+
+ private bodyIdOf(entity: Entity): string {
+ const world = this.app_?.world;
+ const body = world?.valid(entity) && world.has(entity, WaterBody) ? world.get(entity, WaterBody) as WaterBodyData : null;
+ return body?.bodyId || `entity:${entity}`;
+ }
+
/** The world height of the surface above or below (x, z), or null where there is none. */
heightAt(x: number, z: number): number | null {
return this.sample(x, 0, z)?.surface[1] ?? null;
diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.ts
index 060031556..aeefaa0f7 100644
--- a/sdk/src/water/zone.ts
+++ b/sdk/src/water/zone.ts
@@ -85,7 +85,10 @@ export const WaterZone: ComponentDef<WaterZoneData> = defineComponent<WaterZoneD
},
});
-/** An ocean, as the zone takes it: everywhere at `level`, where the ground (if known) is below it. */
+/**
+ * An ocean, as the zone takes it: at `level` wherever the ground is below it and joined to the open sea, which is past the region's
+ * edge. A basin below the sea's level that no low ground joins to the edge is dry land, not sea.
+ */
export interface ZoneOcean { kind: 'ocean'; key: number; level: number; waveHeight: number; shoreWidth: number }
/** A lake: its outline on its own plane at world height `level`, and how a world point is put into the outline's space. */
@@ -192,13 +195,23 @@ export class WaterField {
const blend = texel * 1.5;
const bounded = bodies.filter((b) => b.kind !== 'ocean') as (ZoneLake | ZoneRiver)[];
const boxes = bounded.map((b) => boundsOf(b));
+ const grounds = new Float64Array(grid.nx * grid.nz).fill(Number.NaN);
+ for (let j = 0; j < grid.nz; j++) {
+ if (j % 32 === 0) yield 0.3 * (j / grid.nz);
+ for (let i = 0; i < grid.nx; i++) {
+ const x = grid.minX + (i / Math.max(grid.nx - 1, 1)) * grid.sizeX;
+ const z = grid.minZ + (j / Math.max(grid.nz - 1, 1)) * grid.sizeZ;
+ grounds[j * grid.nx + i] = ground?.(x, z) ?? Number.NaN;
+ }
+ }
+ const sea = ocean ? openSea(grid, grounds, ocean.level) : null;
for (let j = 0; j < grid.nz; j++) {
- if (j % 16 === 0) yield 0.8 * (j / grid.nz);
+ if (j % 16 === 0) yield 0.3 + 0.5 * (j / grid.nz);
for (let i = 0; i < grid.nx; i++) {
const k = j * grid.nx + i;
const x = grid.minX + (i / Math.max(grid.nx - 1, 1)) * grid.sizeX;
const z = grid.minZ + (j / Math.max(grid.nz - 1, 1)) * grid.sizeZ;
- const g = ground ? ground(x, z) : null;
+ const g = Number.isNaN(grounds[k]!) ? null : grounds[k]!;
let w = 0, h = 0, a = 0, c = 0, sw = 0, fx = 0, fz = 0, best = -Infinity, owner = -1, ownerW = 0, held = 0;
for (let b = 0; b < bounded.length; b++) {
const box = boxes[b]!;
@@ -213,7 +226,8 @@ export class WaterField {
if (weight > ownerW) { ownerW = weight; owner = bounded[b]!.key; }
}
if (ocean) {
- const deep = g === null ? DEEP : ocean.level - g;
+ // Ground below the sea's level that the open sea does not reach is a dry basin: as far above the sea as a texel.
+ const deep = g === null ? DEEP : g < ocean.level && !sea![k] ? -texel : ocean.level - g;
best = Math.max(best, deep);
const weight = smooth(-blend, blend, deep) * (1 - held);
if (weight > 0) {
@@ -326,9 +340,10 @@ function sayOf(body: ZoneLake | ZoneRiver, x: number, z: number, g: number | nul
{ height: number; shore: number; amp: number; calm: number; fx: number; fz: number } | null {
if (body.kind === 'lake') {
const [lx, lz] = body.toLocal(x, z);
- const shore = polygonSdf(body.outline, lx, lz);
const deep = g === null ? DEEP : body.level - g;
- const calm = shoreDamp(Math.min(shore, deep), body.shoreWidth);
+ // Water only where its outline is and its surface is over the ground: land inside the outline, above the water, is land.
+ const shore = Math.min(polygonSdf(body.outline, lx, lz), deep);
+ const calm = shoreDamp(shore, body.shoreWidth);
return { height: body.level, shore, amp: body.waveHeight * calm, calm, fx: 0, fz: 0 };
}
const st = body.stations;
@@ -349,16 +364,39 @@ function sayOf(body: ZoneLake | ZoneRiver, x: number, z: number, g: number | nul
let dx = mix(a.dx, b.dx), dz = mix(a.dz, b.dz);
const len = Math.hypot(dx, dz) || 1;
dx /= len; dz /= len;
- const shore = half - best;
+ const deep = g === null ? DEEP : y - g;
+ // Within its banks and over its bed: a bank inside the river's width that stands above its surface is dry.
+ const shore = Math.min(half - best, deep);
// The current fades in over a width from the spring and out over a width into whatever it runs into.
const along = (at + t) / (st.length - 1);
const length = st.reduce((n, p, i) => (i ? n + Math.hypot(p.x - st[i - 1]!.x, p.z - st[i - 1]!.z) : 0), 0);
const run = smooth(0, 2 * half, along * length) * smooth(0, 2 * half, (1 - along) * length);
- const deep = g === null ? DEEP : y - g;
- const calm = shoreDamp(Math.min(shore, deep), body.shoreWidth);
+ const calm = shoreDamp(shore, body.shoreWidth);
return { height: y, shore, amp: body.waveHeight * calm, calm, fx: dx * speed * run, fz: dz * speed * run };
}
+/**
+ * Which texels the open sea reaches: those whose ground is below `level` (or unknown) and joined, through such texels, to the region's
+ * edge, past which the sea goes on.
+ */
+function openSea(grid: ZoneGrid, grounds: Float64Array, level: number): Uint8Array {
+ const { nx, nz } = grid;
+ const sea = new Uint8Array(nx * nz);
+ const low = (k: number): boolean => { const g = grounds[k]!; return Number.isNaN(g) || g < level; };
+ const queue: number[] = [];
+ const reach = (k: number): void => { if (!sea[k] && low(k)) { sea[k] = 1; queue.push(k); } };
+ for (let i = 0; i < nx; i++) { reach(i); reach((nz - 1) * nx + i); }
+ for (let j = 0; j < nz; j++) { reach(j * nx); reach(j * nx + nx - 1); }
+ for (let q = 0; q < queue.length; q++) {
+ const k = queue[q]!, i = k % nx;
+ if (i > 0) reach(k - 1);
+ if (i < nx - 1) reach(k + 1);
+ if (k >= nx) reach(k - nx);
+ if (k < (nz - 1) * nx) reach(k + nx);
+ }
+ return sea;
+}
+
/** A body's box on the world's xz plane, [minX, minZ, maxX, maxZ]. */
function boundsOf(body: ZoneLake | ZoneRiver): [number, number, number, number] {
let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;
diff --git a/sdk/tests/water-bodies.test.ts b/sdk/tests/water-bodies.test.ts
new file mode 100644
index 000000000..ee482c7ed
--- /dev/null
+++ b/sdk/tests/water-bodies.test.ts
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Which water a place is: the sea only where it reaches, a lake only over its own ground, the same whatever order bodies come in;
+ * and the basins and drainage a game decides its lakes and rivers by.
+ */
+import { describe, expect, it } from 'vitest';
+import { WaterField, type ZoneGrid, type ZoneLake, type ZoneOcean } from '../src/water/zone';
+import { drainPath, findBasins } from '../src/water/basins';
+import type { Point2 } from '../src/water/shore';
+import { App } from '../src/app/app';
+import { AppContext, setDefaultContext } from '../src/ecs/context';
+import { setEditorMode, setPlayMode } from '../src/ecs/env';
+import { Transform } from '../src/ecs/component';
+import { createMockModule } from './mocks/wasm';
+import { WaterBody, WaterForm, WaterPlugin, WatersRes } from '../src/water/waterPlugin';
+import { WaterZone } from '../src/water/zone';
+
+const grid: ZoneGrid = { minX: -100, minZ: -100, sizeX: 200, sizeZ: 200, nx: 201, nz: 201 };
+const ocean: ZoneOcean = { kind: 'ocean', key: 3, level: 0, waveHeight: 1, shoreWidth: 4 };
+const square = (half: number): Point2[] => [{ x: -half, y: -half }, { x: half, y: -half }, { x: half, y: half }, { x: -half, y: half }];
+const lakeAt = (cx: number, cz: number, half: number, level: number, key = 1): ZoneLake => ({
+ kind: 'lake', key, level, waveHeight: 0.2, shoreWidth: 2, outline: square(half),
+ toLocal: (x, z) => [x - cx, z - cz], toWorld: (x, z) => [x + cx, z + cz],
+});
+
+/**
+ * An island rising from the sea, with two hollows in it below the sea's level: one walled off (a dry basin), one with a channel cut
+ * through the island's rim out to the sea.
+ */
+function island(x: number, z: number): number {
+ const r = Math.hypot(x, z);
+ let h = 20 - r * 0.3; // a cone, its shore about 67 out
+ const pit = (cx: number, cz: number, depth: number, radius: number) => depth * Math.max(0, 1 - Math.hypot(x - cx, z - cz) / radius);
+ h -= pit(-25, 0, 40, 15); // walled off: its bottom about 6 below the sea
+ h -= pit(30, 0, 42, 15); // the second hollow
+ if (x > 30 && Math.abs(z) < 4) h = Math.min(h, -3); // and its channel out to the sea
+ return h;
+}
+
+describe('the sea', () => {
+ const field = WaterField.bake(grid, [ocean], island);
+
+ it('fills low ground joined to it, and leaves a basin below its level that nothing joins to it dry', () => {
+ expect(island(-25, 0)).toBeLessThan(0);
+ expect(field.sample(-25, 0)).toBeNull();
+ expect(field.sample(30, 0)?.key).toBe(3);
+ expect(field.sample(90, 90)?.key).toBe(3);
+ expect(field.sample(0, 0)).toBeNull();
+ });
+});
+
+describe('a lake', () => {
+ it('is water only where its surface is over its ground: a hill inside its outline is land', () => {
+ const ground = (x: number, z: number) => (Math.hypot(x, z) < 6 ? 5 : -4);
+ const field = WaterField.bake(grid, [lakeAt(0, 0, 30, 0)], ground);
+ expect(field.sample(15, 15)?.key).toBe(1);
+ expect(field.sample(0, 0)).toBeNull();
+ });
+
+ it('above the sea keeps its own water, and the bodies\' order changes nothing', () => {
+ // A lake held up in the island's walled-off hollow, at 2 over the sea.
+ const high = lakeAt(-25, 0, 12, 2, 7);
+ const a = WaterField.bake(grid, [ocean, high], island), b = WaterField.bake(grid, [high, ocean], island);
+ expect(a.sample(-25, 0)?.key).toBe(7);
+ expect(a.sample(-25, 0)!.height).toBeCloseTo(2, 3);
+ for (const name of ['height', 'shore', 'owner', 'depth'] as const) {
+ const x = a[name], y = b[name];
+ for (let k = 0; k < x.length; k += 97) {
+ if (Number.isNaN(x[k]!)) expect(Number.isNaN(y[k]!)).toBe(true);
+ else expect(y[k]).toBe(x[k]);
+ }
+ }
+ });
+});
+
+describe('basins and drainage', () => {
+ it('finds each hollow, filled to where it runs over, and where that is', () => {
+ const map = findBasins(grid, island, { minDepth: 0.5 });
+ const walled = map.basins.find((b) => Math.hypot(b.deepest.x + 25, b.deepest.z) < 3)!;
+ expect(walled).toBeDefined();
+ expect(walled.deepest.y).toBeLessThan(0);
+ // It fills to the lowest point of its rim, and runs over there.
+ expect(walled.level).toBeGreaterThan(walled.deepest.y + 10);
+ expect(walled.outlet.y).toBeCloseTo(walled.level, 0);
+ expect(Math.hypot(walled.outlet.x + 25, walled.outlet.z)).toBeLessThan(20);
+ });
+
+ it('with a sea level, takes the hollow the sea reaches for sea, and keeps the walled-off one a basin', () => {
+ const map = findBasins(grid, island, { seaLevel: 0, minDepth: 0.5 });
+ const k = (x: number, z: number) => (z + 100) * grid.nx + (x + 100);
+ expect(map.sea[k(30, 0)]).toBe(1);
+ expect(map.sea[k(-25, 0)]).toBe(0);
+ expect(map.basin[k(-25, 0)]).toBeGreaterThanOrEqual(0);
+ expect(map.basin[k(30, 0)]).toBe(-1);
+ });
+
+ it('drains every place to the edge, gathering as it goes', () => {
+ const map = findBasins(grid, island);
+ const path = drainPath(map, 10, 10);
+ expect(path.length).toBeGreaterThan(2);
+ const last = path[path.length - 1]!;
+ expect(Math.max(Math.abs(last.x), Math.abs(last.z))).toBeCloseTo(100, 6);
+ // Water only goes down (or level, across a filled basin) along its course.
+ for (let i = 1; i < path.length; i++) expect(path[i]!.y).toBeLessThanOrEqual(path[i - 1]!.y + 1e-4);
+ const total = map.accumulation.reduce((s, v, k) => (map.downstream[k] === -1 ? s + v : s), 0);
+ expect(total).toBe(grid.nx * grid.nz);
+ });
+});
+
+describe('the water in a running app with no renderer', () => {
+ it('names the body a place belongs to by the id the game gave it, the same in every session', async () => {
+ setDefaultContext(new AppContext());
+ setEditorMode(false);
+ setPlayMode(false);
+ const app = App.new();
+ const module = createMockModule();
+ app.connectCpp(module.getRegistry(), module);
+ app.addPlugin(new WaterPlugin());
+ const zone = app.world.spawn();
+ app.world.insert(zone, Transform, { position: { x: 0, y: 0, z: 0 }, worldPosition: { x: 0, y: 0, z: 0 } });
+ app.world.insert(zone, WaterZone, { ...WaterZone._default, sizeX: 200, sizeZ: 200 });
+ const lake = app.world.spawn();
+ app.world.insert(lake, Transform, { position: { x: 0, y: 2, z: 0 }, worldPosition: { x: 0, y: 2, z: 0 } });
+ app.world.insert(lake, WaterBody, { ...WaterBody._default, form: WaterForm.Lake, bodyId: 'mirror-lake', sizeX: 60, sizeZ: 60 });
+ for (let i = 0; i < 40; i++) { app.tick(1 / 60); await new Promise((r) => setTimeout(r, 0)); }
+ const waters = app.getResource(WatersRes);
+ expect(waters.bodyAt(0, 0)).toMatchObject({ entity: lake, bodyId: 'mirror-lake', form: WaterForm.Lake });
+ expect(waters.bodyAt(0, 0)!.level).toBeCloseTo(2, 3);
+ expect(waters.sample(0, 0, 0)?.bodyId).toBe('mirror-lake');
+ expect(waters.bodyAt(90, 90)).toBeNull();
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index e8e138dd6..1d2eddfe0 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2778,4 +2778,6 @@ export const NOTED = {
{"note":"Generated worlds."},
"feat(editor): a WorldZone's circle or turned box is drawn on the ground":
{"note":"Generated worlds."},
+ "feat(water): the sea fills only what joins it, a body is water only over its ground, bodies carry stable ids, and basins show where water gathers":
+ {"note":"Which water a place is."},
};