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): a lake takes an outline of its own and calms its waves toward the shore

yhh6d52cadf1707
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 16b3b7bcf..e11bd60ba 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ published separately; it ships inside the editor.
- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.
- **Terrain and Foliage.** A Terrain component makes ground from a heightmap or noise, paints it with grass, dirt, snow and rock layers and draws it in chunks that coarsen with distance; a Foliage component scatters grass or a mesh over it, swaying in the wind and thinning out with distance.
- **Separate material maps packed on import.** Importing an FBX with separate metalness, roughness and occlusion images now packs them into the one map the Model shader samples, instead of dropping them. Occlusion goes in red, roughness in green and metal in blue, each from its image's red channel (a glossiness map is inverted); a channel with no image stays at full so the material's own value speaks. Only PNG and DDS can be read.
+- **Lake outlines and shores.** A lake can have an outline of its own and knows its shore. `boundary` cuts it to a polygon on its plane (crisp at the pixel, not at the grid's cells), `shoreWidth` calms its waves toward the edge and where it is shallow over a Terrain, and the shore foams along the outline. `Waters.sample` answers with the same calmed waves and says a point in the notch of a concave lake is not inside.
- **Water bodies.** Water gets a component and a chapter of its own. A WaterBody builds an ocean (without an edge, following the camera, in rings that coarsen with distance) or a rectangular lake, lifts its geometry with the waves, follows its own up when it is tilted, and answers for its surface from code (`Waters.sample`) with the same formula the shader draws. Water is an optional module (`esengine/water`): a 2D game carries none of it.
- **Cyber Rooftop update.** Cyber Rooftop gets a rebuilt rooftop model and textures, a wet roof material with a planar reflection under a rain sky, rain, fog and bloom in the scene, a larger set of HUD icons and inventory art, and a wider build footprint.
- **Hair tips.** The Hair shader can draw the soft outer band of its cards: `u_tipSoftness` is how far below the cutoff alpha a second, blended pass draws each strand's tip fading out, sorted with the other blended draws, so tips are not stair-stepped by coverage. A model imported with Character Materials also has its hair triangles put in the order that pass wants, the cards nearest the middle of the hair first. Off by default.
diff --git a/desktop b/desktop
index 3e00c4540..c4fa33320 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 3e00c45409139baaf9e7071026f43e741f84a60b
+Subproject commit c4fa33320633711dc5c740ff3689da72a97ed54d
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
index b59d8a073..cf025eb59 100644
--- a/docs/astro/src/content/docs/graphics/water.mdx
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -17,7 +17,9 @@ changes.
| Field | What it does |
|---|---|
-| `form` | **Ocean**: without an edge, follows the camera. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity. |
+| `form` | **Ocean**: without an edge, follows the camera. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity, or the outline in `boundary`. |
+| `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 edge, and how deep, the waves take to come to full height. 0 leaves them whole to the edge. |
| `material` | A material on the Water shader. Empty uses the stock water. |
| `cellSize` | The cell size of the finest ring of geometry. |
| `cells`, `rings` | An ocean's rings: cells along a ring's side, and how many rings. |
@@ -46,6 +48,17 @@ A coarse ring cannot draw a short wave: below three cells to a wavelength it wou
its cells (the shading still shows them, per pixel). Where two rings meet, the coarse one has half the vertices along the edge, and the surfaces
can part by what the waves do between them; keep `waveLength` at least six of the coarsest visible ring's cells and there is no seam to see.
+## Lakes and shores
+
+A lake is cut to its outline, and the waves know where its edge is and how deep the water is. The body bakes a small field over the box of its
+outline: the signed distance to the edge, and the depth of the water over the ground under it. From the two comes the share of the waves a point
+keeps (none at the edge or where the water is not deep, all from `shoreWidth` in), written into the mesh's vertices so the geometry calms toward
+the shore, and into a texture so the pixels do too, the edge is cut where the outline is (not at the grid's cells), and the shore foams along it.
+
+With a `Terrain` in the scene and the lake level, the ground under it is the terrain: 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. The field is rebuilt when the terrain changes or the lake moves; a tilted
+lake, or one over no terrain, is as deep as it likes. The outline should not cross itself.
+
## Asking the surface
`Waters.sample(x, y, z)` (the `WatersRes` resource) answers for the body that holds a point:
@@ -53,7 +66,7 @@ can part by what the waves do between them; keep `waveLength` at least six of th
- `depth`: how far the point is above the surface along the body's up (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;
-- `inside`: whether the point is over the body's extent.
+- `inside`: whether the point is over the body's extent: inside a lake's outline (an ocean has none, so it is always).
It reads the same formula the shader draws, at the time of the frame. The body's position, rotation and uniform scale are taken into account.
`Waters.heightAt(x, z)` is the short form for an untilted body. A point over no water answers `null`.
@@ -86,8 +99,8 @@ What is not there yet, so nobody is surprised:
Without the chain the water is drawn over the scene as a translucent surface; without float targets the depth is `u_fallbackDepth` everywhere, so
there is no shore foam and no change of colour with depth.
- Like glass, it refracts the opaque scene only: a boat's hull seen through it is, but another transparent surface is not.
-- A lake is a rectangle; a boundary of your own shape, lakes that fill a terrain basin, rivers along a curve, flow, and the waves' breaking at a
- shore are not built yet.
+- Rivers along a curve and flow are not built yet. A lake's outline is a polygon on a plane: it does not follow a curved shore, and the waves die
+ toward the shore without breaking on it.
- Nothing floats on it or swims in it yet: `Waters.sample` gives what a buoyancy force needs, but there is no force.
- A camera under the surface sees the water turned over, and nothing else changes: no underwater fog or tint.
- It does not react to what moves through it: no ripples, no wake.
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 39a190b85..c3cc642bc 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,9 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
| 字段 | 作用 |
|---|---|
-| `form` | **海洋**:没有边,跟随相机。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形。 |
+| `form` | **海洋**:没有边,跟随相机。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形,或 `boundary` 给出的轮廓。 |
+| `boundary` | 湖泊的轮廓:它自己的 xz 平面上围一圈的三个或更多点。留空就是矩形。 |
+| `shoreWidth` | 从岸边往里多远、水多深,波浪才长到完整高度。0 表示波浪一直完整到岸边。 |
| `material` | 使用 Water 着色器的材质。留空用内置的水。 |
| `cellSize` | 最细一圈几何体的格子大小。 |
| `cells`、`rings` | 海洋的圈:每圈一边多少格,以及有几圈。 |
@@ -33,6 +35,12 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
粗的一圈画不出短的波:一个波长不到三格就会闪烁,所以它的顶点会淡掉比自己六格还短的波(着色仍然逐像素显示它们)。两圈相接处,粗的一圈沿边的顶点少一半,表面可能在顶点之间分开,分开多少取决于波浪在它们之间做了什么;让 `waveLength` 至少是看得到的最粗一圈的六格,接缝就看不出来。
+## 湖泊与岸线
+
+湖泊按它的轮廓裁出形状,波浪知道岸边在哪儿、水有多深。水体在轮廓的包围盒上烘一张小场:到岸边的有符号距离,以及水在它下面的地面之上有多深。从这两个量得出一个点保留多少波浪(在岸边或水很浅处一点不留,从 `shoreWidth` 往里全留),写进网格的顶点,所以几何体向岸边变平静;也写进一张纹理,所以像素也是如此,边缘按轮廓来裁(而不是按网格的格子),岸边还会起泡沫。
+
+场景里有 `Terrain` 且湖面水平时,它下面的地面就是地形:水填满低处,在山丘与它相交的地方被山丘截断(深度测试做到这一点),波浪随变浅而消失。地形一变或湖面一动,这张场就会重建;倾斜的湖,或没有地形的湖,要多深有多深。轮廓不应自相交。
+
## 查询表面
`Waters.sample(x, y, z)`(资源 `WatersRes`)为包含这个点的水体作答:
@@ -40,7 +48,7 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
- `depth`:这个点沿水体上方向高出表面多少(在下面则为负),世界单位;
- `normal`:表面在那里的法线,世界空间;
- `surface`:这个点正上方或正下方、表面上的世界坐标;
-- `inside`:这个点是否在水体范围之上。
+- `inside`:这个点是否在水体范围之上:在湖泊轮廓之内(海洋没有轮廓,所以总是)。
它读的是着色器画的同一个公式,取这一帧的时间。水体的位置、旋转和均匀缩放都被考虑进去。`Waters.heightAt(x, z)` 是未倾斜水体的简写。点上方没有水则返回 `null`。
@@ -61,7 +69,7 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以没有岸边泡沫,颜色也不随水深变化。
- 与玻璃一样,它只折射不透明场景:透过它能看到船体,但看不到另一个透明表面。
-- 湖泊是矩形;自定义形状的边界、填满地形盆地的湖、沿曲线的河流、水流,以及波浪在岸边破碎,都还没有做。
+- 沿曲线的河流和水流还没有做。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。
- 还没有东西能漂在上面或在里面游:`Waters.sample` 给出了浮力需要的量,但还没有这个力。
- 相机在水面以下时,看到的是翻过来的水,别的没有变化:没有水下的雾和染色。
- 它不会对穿过它的东西作出反应:没有涟漪,没有尾迹。
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 081feb54b..a8345c86b 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 115,
"beta": 171,
- "experimental": 2351,
+ "experimental": 2359,
"deprecated": 3
},
- "total": 2637,
+ "total": 2645,
"subsystems": [
{
"id": "mobile-controls",
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index d8584c81f..2f0a07a5a 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -7063,6 +7063,19 @@
"doc": "A lake's size along z.",
"range": "≥ 1"
},
+ {
+ "key": "boundary",
+ "type": "array",
+ "default": "empty",
+ "doc": "The outline of a lake: points round it on its own xz plane. Empty is the rectangle of its size."
+ },
+ {
+ "key": "shoreWidth",
+ "type": "number",
+ "default": "3",
+ "doc": "How far in from the edge, and how deep, the waves take to come to full height. 0 leaves them whole to the edge.",
+ "range": "≥ 0"
+ },
{
"key": "cellSize",
"type": "number",
@@ -7118,6 +7131,7 @@
"material",
"sizeX",
"sizeZ",
+ "shoreWidth",
"cellSize",
"cells",
"rings",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 07b5dc639..c168ea5c7 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 · 1723 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1731 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4452,6 +4452,11 @@ static prototype: GridLayoutProvider
(x: number, z: number) => { y: number; up: number } | null
```
+## GroundDepth — type @experimental
+```
+(x: number, z: number) => number | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -6668,6 +6673,12 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## Point2 — interface @experimental
+```
+x: number
+y: number
+```
+
## PointJoint3D — const @experimental
```
ComponentDef<PointJoint3DData>
@@ -7219,6 +7230,12 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## RectOptions — interface @experimental
+```
+damp: ((x: number, z: number) => number) | undefined
+keep: ((x: number, z: number, cell: number) => boolean) | undefined
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -8302,6 +8319,25 @@ pageWidth: number
spacing: number
```
+## ShoreField — class @experimental
+```
+damp: (x: number, z: number) => number
+depth: Float32Array<ArrayBufferLike>
+distance: (x: number, z: number) => number
+encode: (range: number) => Uint8Array
+inside: (x: number, z: number) => boolean
+minX: number
+minZ: number
+res: number
+sdf: Float32Array<ArrayBufferLike>
+sizeX: number
+sizeZ: number
+waterDepth: (x: number, z: number) => number
+width: number
+static new (poly: readonly Point2[], res: number, width: number, ground?: GroundDepth): ShoreField
+static prototype: ShoreField
+```
+
## ShotState — interface @experimental
```
curve: number
@@ -10732,6 +10768,11 @@ SolidColor = 1
Tiled = 4
```
+## UNKNOWN_DEPTH — const @experimental
+```
+1000000000
+```
+
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11085,11 +11126,13 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+boundary: Point2[]
cellSize: number
cells: number
form: number
material: number
rings: number
+shoreWidth: number
sizeX: number
sizeZ: number
waveDirection: number
@@ -11886,6 +11929,11 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
+## buildBoxMesh — function @experimental
+```
+(minX: number, minZ: number, maxX: number, maxZ: number, cellSize: number, options?: RectOptions): MeshData
+```
+
## buildChunkMesh — function @experimental
```
(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
@@ -11913,7 +11961,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildRectMesh — function @experimental
```
-(sizeX: number, sizeZ: number, cellSize: number): MeshData
+(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
## buildText — function @experimental
@@ -13811,6 +13859,11 @@ ParticlePlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonSdf — function @experimental
+```
+(poly: readonly Point2[], x: number, z: number): number
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
@@ -14526,6 +14579,11 @@ ServicesPlugin
(): string[]
```
+## shoreDamp — function @experimental
+```
+(reach: number, width: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 81290845c..6e3ef88ef 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 · 1742 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1750 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4460,6 +4460,11 @@ static prototype: GridLayoutProvider
(x: number, z: number) => { y: number; up: number } | null
```
+## GroundDepth — type @experimental
+```
+(x: number, z: number) => number | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -6871,6 +6876,12 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## Point2 — interface @experimental
+```
+x: number
+y: number
+```
+
## PointJoint3D — const @experimental
```
ComponentDef<PointJoint3DData>
@@ -7432,6 +7443,12 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## RectOptions — interface @experimental
+```
+damp: ((x: number, z: number) => number) | undefined
+keep: ((x: number, z: number, cell: number) => boolean) | undefined
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -8515,6 +8532,25 @@ pageWidth: number
spacing: number
```
+## ShoreField — class @experimental
+```
+damp: (x: number, z: number) => number
+depth: Float32Array<ArrayBufferLike>
+distance: (x: number, z: number) => number
+encode: (range: number) => Uint8Array
+inside: (x: number, z: number) => boolean
+minX: number
+minZ: number
+res: number
+sdf: Float32Array<ArrayBufferLike>
+sizeX: number
+sizeZ: number
+waterDepth: (x: number, z: number) => number
+width: number
+static new (poly: readonly Point2[], res: number, width: number, ground?: GroundDepth): ShoreField
+static prototype: ShoreField
+```
+
## ShotState — interface @experimental
```
curve: number
@@ -10945,6 +10981,11 @@ SolidColor = 1
Tiled = 4
```
+## UNKNOWN_DEPTH — const @experimental
+```
+1000000000
+```
+
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11298,11 +11339,13 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+boundary: Point2[]
cellSize: number
cells: number
form: number
material: number
rings: number
+shoreWidth: number
sizeX: number
sizeZ: number
waveDirection: number
@@ -12114,6 +12157,11 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
+## buildBoxMesh — function @experimental
+```
+(minX: number, minZ: number, maxX: number, maxZ: number, cellSize: number, options?: RectOptions): MeshData
+```
+
## buildChunkMesh — function @experimental
```
(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
@@ -12141,7 +12189,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildRectMesh — function @experimental
```
-(sizeX: number, sizeZ: number, cellSize: number): MeshData
+(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
## buildText — function @experimental
@@ -14074,6 +14122,11 @@ ParticlePlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonSdf — function @experimental
+```
+(poly: readonly Point2[], x: number, z: number): number
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
@@ -14789,6 +14842,11 @@ ServicesPlugin
(): string[]
```
+## shoreDamp — function @experimental
+```
+(reach: number, width: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index b68f5e242..d08161ec1 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 · 1722 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1730 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4447,6 +4447,11 @@ static prototype: GridLayoutProvider
(x: number, z: number) => { y: number; up: number } | null
```
+## GroundDepth — type @experimental
+```
+(x: number, z: number) => number | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -6663,6 +6668,12 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## Point2 — interface @experimental
+```
+x: number
+y: number
+```
+
## PointJoint3D — const @experimental
```
ComponentDef<PointJoint3DData>
@@ -7214,6 +7225,12 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## RectOptions — interface @experimental
+```
+damp: ((x: number, z: number) => number) | undefined
+keep: ((x: number, z: number, cell: number) => boolean) | undefined
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -8297,6 +8314,25 @@ pageWidth: number
spacing: number
```
+## ShoreField — class @experimental
+```
+damp: (x: number, z: number) => number
+depth: Float32Array<ArrayBufferLike>
+distance: (x: number, z: number) => number
+encode: (range: number) => Uint8Array
+inside: (x: number, z: number) => boolean
+minX: number
+minZ: number
+res: number
+sdf: Float32Array<ArrayBufferLike>
+sizeX: number
+sizeZ: number
+waterDepth: (x: number, z: number) => number
+width: number
+static new (poly: readonly Point2[], res: number, width: number, ground?: GroundDepth): ShoreField
+static prototype: ShoreField
+```
+
## ShotState — interface @experimental
```
curve: number
@@ -10727,6 +10763,11 @@ SolidColor = 1
Tiled = 4
```
+## UNKNOWN_DEPTH — const @experimental
+```
+1000000000
+```
+
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11080,11 +11121,13 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+boundary: Point2[]
cellSize: number
cells: number
form: number
material: number
rings: number
+shoreWidth: number
sizeX: number
sizeZ: number
waveDirection: number
@@ -11881,6 +11924,11 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
+## buildBoxMesh — function @experimental
+```
+(minX: number, minZ: number, maxX: number, maxZ: number, cellSize: number, options?: RectOptions): MeshData
+```
+
## buildChunkMesh — function @experimental
```
(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
@@ -11908,7 +11956,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildRectMesh — function @experimental
```
-(sizeX: number, sizeZ: number, cellSize: number): MeshData
+(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
## buildText — function @experimental
@@ -13816,6 +13864,11 @@ ParticlePlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonSdf — function @experimental
+```
+(poly: readonly Point2[], x: number, z: number): number
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
@@ -14531,6 +14584,11 @@ ServicesPlugin
(): string[]
```
+## shoreDamp — function @experimental
+```
+(reach: number, width: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index cde3b7168..8079df4ea 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 · 1744 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1752 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4447,6 +4447,11 @@ static prototype: GridLayoutProvider
(x: number, z: number) => { y: number; up: number } | null
```
+## GroundDepth — type @experimental
+```
+(x: number, z: number) => number | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -6956,6 +6961,12 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## Point2 — interface @experimental
+```
+x: number
+y: number
+```
+
## PointJoint3D — const @experimental
```
ComponentDef<PointJoint3DData>
@@ -7507,6 +7518,12 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## RectOptions — interface @experimental
+```
+damp: ((x: number, z: number) => number) | undefined
+keep: ((x: number, z: number, cell: number) => boolean) | undefined
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -8590,6 +8607,25 @@ pageWidth: number
spacing: number
```
+## ShoreField — class @experimental
+```
+damp: (x: number, z: number) => number
+depth: Float32Array<ArrayBufferLike>
+distance: (x: number, z: number) => number
+encode: (range: number) => Uint8Array
+inside: (x: number, z: number) => boolean
+minX: number
+minZ: number
+res: number
+sdf: Float32Array<ArrayBufferLike>
+sizeX: number
+sizeZ: number
+waterDepth: (x: number, z: number) => number
+width: number
+static new (poly: readonly Point2[], res: number, width: number, ground?: GroundDepth): ShoreField
+static prototype: ShoreField
+```
+
## ShotState — interface @experimental
```
curve: number
@@ -11020,6 +11056,11 @@ SolidColor = 1
Tiled = 4
```
+## UNKNOWN_DEPTH — const @experimental
+```
+1000000000
+```
+
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11379,11 +11420,13 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+boundary: Point2[]
cellSize: number
cells: number
form: number
material: number
rings: number
+shoreWidth: number
sizeX: number
sizeZ: number
waveDirection: number
@@ -12180,6 +12223,11 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
+## buildBoxMesh — function @experimental
+```
+(minX: number, minZ: number, maxX: number, maxZ: number, cellSize: number, options?: RectOptions): MeshData
+```
+
## buildChunkMesh — function @experimental
```
(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
@@ -12207,7 +12255,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildRectMesh — function @experimental
```
-(sizeX: number, sizeZ: number, cellSize: number): MeshData
+(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
## buildText — function @experimental
@@ -14120,6 +14168,11 @@ ParticlePlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonSdf — function @experimental
+```
+(poly: readonly Point2[], x: number, z: number): number
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
@@ -14835,6 +14888,11 @@ ServicesPlugin
(): string[]
```
+## shoreDamp — function @experimental
+```
+(reach: number, width: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index e65f9f948..86c11b255 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -1,7 +1,48 @@
# API surface — esengine/water
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 17 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 25 experimental · 0 deprecated
+
+## GroundDepth — type @experimental
+```
+(x: number, z: number) => number | null
+```
+
+## Point2 — interface @experimental
+```
+x: number
+y: number
+```
+
+## RectOptions — interface @experimental
+```
+damp: ((x: number, z: number) => number) | undefined
+keep: ((x: number, z: number, cell: number) => boolean) | undefined
+```
+
+## ShoreField — class @experimental
+```
+damp: (x: number, z: number) => number
+depth: Float32Array<ArrayBufferLike>
+distance: (x: number, z: number) => number
+encode: (range: number) => Uint8Array
+inside: (x: number, z: number) => boolean
+minX: number
+minZ: number
+res: number
+sdf: Float32Array<ArrayBufferLike>
+sizeX: number
+sizeZ: number
+waterDepth: (x: number, z: number) => number
+width: number
+static new (poly: readonly Point2[], res: number, width: number, ground?: GroundDepth): ShoreField
+static prototype: ShoreField
+```
+
+## UNKNOWN_DEPTH — const @experimental
+```
+1000000000
+```
## WAVE_SET — const @experimental
```
@@ -15,11 +56,13 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+boundary: Point2[]
cellSize: number
cells: number
form: number
material: number
rings: number
+shoreWidth: number
sizeX: number
sizeZ: number
waveDirection: number
@@ -74,6 +117,11 @@ length: number
speed: number
```
+## buildBoxMesh — function @experimental
+```
+(minX: number, minZ: number, maxX: number, maxZ: number, cellSize: number, options?: RectOptions): MeshData
+```
+
## buildOceanMesh — function @experimental
```
(cells: number, rings: number, cellSize: number): MeshData
@@ -81,7 +129,7 @@ speed: number
## buildRectMesh — function @experimental
```
-(sizeX: number, sizeZ: number, cellSize: number): MeshData
+(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
## oceanReach — function @experimental
@@ -94,6 +142,16 @@ speed: number
(rings: number, cellSize: number): number
```
+## polygonSdf — function @experimental
+```
+(poly: readonly Point2[], x: number, z: number): number
+```
+
+## shoreDamp — function @experimental
+```
+(reach: number, width: number): number
+```
+
## waterPlugin — const @experimental
```
Plugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 0d871f67c..4398cc1da 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 · 1735 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1743 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4447,6 +4447,11 @@ static prototype: GridLayoutProvider
(x: number, z: number) => { y: number; up: number } | null
```
+## GroundDepth — type @experimental
+```
+(x: number, z: number) => number | null
+```
+
## HdrFormat — interface @experimental
```
effective: string
@@ -6670,6 +6675,12 @@ zero: string | undefined
(count: number) => PluralCategory
```
+## Point2 — interface @experimental
+```
+x: number
+y: number
+```
+
## PointJoint3D — const @experimental
```
ComponentDef<PointJoint3DData>
@@ -7221,6 +7232,12 @@ get: () => T
subscribe: (fn: (value: T) => void) => () => void
```
+## RectOptions — interface @experimental
+```
+damp: ((x: number, z: number) => number) | undefined
+keep: ((x: number, z: number, cell: number) => boolean) | undefined
+```
+
## ReflectionAxis — enum @experimental
```
X = 0
@@ -8304,6 +8321,25 @@ pageWidth: number
spacing: number
```
+## ShoreField — class @experimental
+```
+damp: (x: number, z: number) => number
+depth: Float32Array<ArrayBufferLike>
+distance: (x: number, z: number) => number
+encode: (range: number) => Uint8Array
+inside: (x: number, z: number) => boolean
+minX: number
+minZ: number
+res: number
+sdf: Float32Array<ArrayBufferLike>
+sizeX: number
+sizeZ: number
+waterDepth: (x: number, z: number) => number
+width: number
+static new (poly: readonly Point2[], res: number, width: number, ground?: GroundDepth): ShoreField
+static prototype: ShoreField
+```
+
## ShotState — interface @experimental
```
curve: number
@@ -10734,6 +10770,11 @@ SolidColor = 1
Tiled = 4
```
+## UNKNOWN_DEPTH — const @experimental
+```
+1000000000
+```
+
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11087,11 +11128,13 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
+boundary: Point2[]
cellSize: number
cells: number
form: number
material: number
rings: number
+shoreWidth: number
sizeX: number
sizeZ: number
waveDirection: number
@@ -11912,6 +11955,11 @@ MotionDriver<AnimatorBlend2DMotion>
(plants: readonly Plant[], width: number, height: number, rect: CardRect, paint?: BladeParams["paint"], triangle?: boolean): MeshData
```
+## buildBoxMesh — function @experimental
+```
+(minX: number, minZ: number, maxX: number, maxZ: number, cellSize: number, options?: RectOptions): MeshData
+```
+
## buildChunkMesh — function @experimental
```
(field: Heightfield, shape: TerrainShape, cx: number, cz: number, lod: number, paint: TerrainPaint): MeshData
@@ -11939,7 +11987,7 @@ MotionDriver<AnimatorBlend2DMotion>
## buildRectMesh — function @experimental
```
-(sizeX: number, sizeZ: number, cellSize: number): MeshData
+(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
```
## buildText — function @experimental
@@ -13847,6 +13895,11 @@ ParticlePlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonSdf — function @experimental
+```
+(poly: readonly Point2[], x: number, z: number): number
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
@@ -14562,6 +14615,11 @@ ServicesPlugin
(): string[]
```
+## shoreDamp — function @experimental
+```
+(reach: number, width: number): number
+```
+
## shutdownDrawAPI — function @experimental
```
(): void
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 07b5697e8..e607e95de 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -792,7 +792,8 @@ export {
WaterBody, WaterForm, Waters, WatersRes, WaterPlugin, waterPlugin, type WaterBodyData, type WaterSample,
} from './water/waterPlugin';
export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './water/waves';
-export { buildOceanMesh, buildRectMesh, oceanReach, oceanSnap } from './water/waterMesh';
+export { buildBoxMesh, buildOceanMesh, buildRectMesh, oceanReach, oceanSnap, type RectOptions } from './water/waterMesh';
+export { ShoreField, UNKNOWN_DEPTH, polygonSdf, shoreDamp, type GroundDepth, type Point2 } from './water/shore';
export {
scatterCell, buildGrassMesh, buildInstancedMesh, buildBillboardMesh, rng,
type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index d3dbc062e..2e3b08e07 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -732,6 +732,13 @@ const WATER = `#pragma shader "Water"
// The cell size of the mesh's finest ring, for a body the WaterBody component built: a vertex in a coarser ring (its colour's red says which) fades the
// waves it cannot draw, those shorter than six of its cells. 0 draws every wave at every vertex.
#pragma param u_cellSize float default(0) range(0,100) ui(slider)
+// A lake's shore, baked by the WaterBody component over its box: red the signed distance to its outline (0.5 at the edge), green how deep the water is,
+// blue the share of the waves kept, all over u_shoreRange. The pixels outside the outline are cut, the waves die toward the shore, and it foams there.
+#pragma param u_shoreOn float default(0) range(0,1) ui(slider)
+#pragma param u_shoreMap texture default(white) texel(data)
+#pragma param u_shoreOrigin vec2 default(0,0)
+#pragma param u_shoreSize vec2 default(1,1)
+#pragma param u_shoreRange float default(16) range(0.01,10000) ui(slider)
#pragma param u_sceneColor texture default(white)
#pragma param u_sceneDepthMap texture default(white) texel(data)
@@ -756,7 +763,8 @@ float waterWaveHeight(vec2 p, float time, float cell) {
void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
if (u_waveSpace < 0.5) return;
float cell = u_cellSize > 0.0 ? u_cellSize * exp2(es_vertexColor.r * 7.0) : 0.0;
- local.y += waterWaveHeight(uv + u_origin, u_time.x, cell);
+ float damp = u_shoreOn > 0.5 ? es_vertexColor.g : 1.0;
+ local.y += waterWaveHeight(uv + u_origin, u_time.x, cell) * damp;
}
#pragma end
@@ -782,7 +790,9 @@ fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, ve
if (mc.u_waveSpace < 0.5) { return; }
var cell = 0.0;
if (mc.u_cellSize > 0.0) { cell = mc.u_cellSize * exp2(es_vertexColor.r * 7.0); }
- (*local).y = (*local).y + waterWaveHeight(uv + mc.u_origin, tc.u_time.x, cell);
+ var damp = 1.0;
+ if (mc.u_shoreOn > 0.5) { damp = es_vertexColor.g; }
+ (*local).y = (*local).y + waterWaveHeight(uv + mc.u_origin, tc.u_time.x, cell) * damp;
}
#pragma end
@@ -867,8 +877,14 @@ void main() {
// The surface: the long waves, then the ripples they carry, flattened with distance so the far water is calm rather than aliased.
vec2 wp = u_waveSpace > 0.5 ? v_texCoord + u_origin : P.xz;
+ // The lake's shore at this pixel (a texture read, taken before any branch).
+ vec4 shoreTex = texture(u_shoreMap, clamp((v_texCoord - u_shoreOrigin) / max(u_shoreSize, vec2(1e-4)), vec2(0.0), vec2(1.0)));
+ float shoreDist = (shoreTex.r - 0.5) * 2.0 * u_shoreRange;
+ float shoreDepth = shoreTex.g * u_shoreRange;
+ float damp = u_shoreOn > 0.5 ? shoreTex.b : 1.0;
float crest;
- vec2 slope = waveSlope(wp, time, waterDist, crest);
+ vec2 slope = waveSlope(wp, time, waterDist, crest) * damp;
+ crest *= damp;
float rippleFade = clamp(1.0 - waterDist / (u_rippleLength * 180.0), 0.0, 1.0);
float e = u_rippleLength * 0.1;
vec2 ripple = vec2(ripples(wp + vec2(e, 0.0), time) - ripples(wp - vec2(e, 0.0), time),
@@ -924,6 +940,10 @@ void main() {
float breakup = waterNoise(wp * foamScale + vec2(time * 0.07, time * 0.05)) * 0.6 + waterNoise(wp * foamScale * 3.0 - vec2(time * 0.13, 0.0)) * 0.4;
float pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);
float shore = haveDepth && u_foamWidth > 0.0 ? clamp((1.0 - vertical / (u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.0) : 0.0;
+ // The baked shore foams too, where the depth buffer cannot say (no chain, no float targets) and along the lake's outline.
+ if (u_shoreOn > 0.5 && u_foamWidth > 0.0) {
+ shore = max(shore, clamp((1.0 - min(shoreDist, shoreDepth) / (u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.0));
+ }
float onCrest = u_foamCrest > 0.0 ? smoothstep(1.0 - 0.3 * u_foamCrest, 1.0, crest) * smoothstep(0.35, 0.75, breakup) : 0.0;
float foam = clamp(max(shore, onCrest * u_foamCrest), 0.0, 1.0);
@@ -935,6 +955,8 @@ void main() {
float cosV = clamp(dot(N, viewDir), 0.0, 1.0);
float fresnel = 0.0204 + (1.0 - 0.0204) * pow(1.0 - cosV, 5.0);
vec3 seen = behind * transmit * (1.0 - fresnel) * (1.0 - foam);
+ // Outside the lake's outline there is no water.
+ if (u_shoreOn > 0.5 && shoreDist < 0.0) discard;
fragColor = vec4(lit + seen, haveColor ? 1.0 : 0.85);
#ifdef ES_GBUFFER
fragSurface = vec4(packNormal(normalize(N)), roughness, 0.75);
@@ -1024,8 +1046,14 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
var wp = P.xz;
if (mc.u_waveSpace > 0.5) { wp = v.v_texCoord + mc.u_origin; }
- let waves = waveSlope(wp, time, waterDist);
- var slope = waves.slope;
+ let shoreTex = textureSample(u_shoreMap, u_shoreMap_s, clamp((v.v_texCoord - mc.u_shoreOrigin) / max(mc.u_shoreSize, vec2f(1e-4)), vec2f(0.0), vec2f(1.0)));
+ let shoreDist = (shoreTex.r - 0.5) * 2.0 * mc.u_shoreRange;
+ let shoreDepth = shoreTex.g * mc.u_shoreRange;
+ var damp = 1.0;
+ if (mc.u_shoreOn > 0.5) { damp = shoreTex.b; }
+ var waves = waveSlope(wp, time, waterDist);
+ waves.crest = waves.crest * damp;
+ var slope = waves.slope * damp;
let rippleFade = clamp(1.0 - waterDist / (mc.u_rippleLength * 180.0), 0.0, 1.0);
let eps = mc.u_rippleLength * 0.1;
let ripple = vec2f(ripples(wp + vec2f(eps, 0.0), time) - ripples(wp - vec2f(eps, 0.0), time),
@@ -1079,6 +1107,9 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
let pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);
var shore = 0.0;
if (haveDepth && mc.u_foamWidth > 0.0) { shore = clamp((1.0 - vertical / (mc.u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.0); }
+ if (mc.u_shoreOn > 0.5 && mc.u_foamWidth > 0.0) {
+ shore = max(shore, clamp((1.0 - min(shoreDist, shoreDepth) / (mc.u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.0));
+ }
var onCrest = 0.0;
if (mc.u_foamCrest > 0.0) { onCrest = smoothstep(1.0 - 0.3 * mc.u_foamCrest, 1.0, waves.crest) * smoothstep(0.35, 0.75, breakup); }
let foam = clamp(max(shore, onCrest * mc.u_foamCrest), 0.0, 1.0);
@@ -1093,6 +1124,7 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
let seen = behind * transmit * (1.0 - fresnel) * (1.0 - foam);
var alpha = 0.85;
if (haveColor) { alpha = 1.0; }
+ if (mc.u_shoreOn > 0.5 && shoreDist < 0.0) { discard; }
#ifdef ES_GBUFFER
var frag : FragOut;
frag.color = vec4f(lit + seen, alpha);
diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.ts
index ab976c1ce..bd2a18901 100644
--- a/sdk/src/water/index.ts
+++ b/sdk/src/water/index.ts
@@ -4,7 +4,8 @@ export {
WaterBody, WaterForm, Waters, WatersRes, WaterPlugin, waterPlugin, type WaterBodyData, type WaterSample,
} from './waterPlugin';
export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './waves';
-export { buildOceanMesh, buildRectMesh, oceanReach, oceanSnap } from './waterMesh';
+export { buildBoxMesh, buildOceanMesh, buildRectMesh, oceanReach, oceanSnap, type RectOptions } from './waterMesh';
+export { ShoreField, UNKNOWN_DEPTH, polygonSdf, shoreDamp, type GroundDepth, type Point2 } from './shore';
// Importing this subpath INSTALLS water — see tilemap/index.ts.
import { registerWaterSupport } from './waterSupport';
diff --git a/sdk/src/water/shore.ts b/sdk/src/water/shore.ts
new file mode 100644
index 000000000..e4605f93d
--- /dev/null
+++ b/sdk/src/water/shore.ts
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file shore.ts
+ * @brief Where a lake ends and how deep it is, baked into a grid the CPU and the Water shader both read.
+ *
+ * @details A lake has an outline (a polygon on its own xz plane) and sits over ground, and the waves know about both: they die away as the
+ * water gets shallow or the edge near, and the shore carries foam. This is that knowledge as a field, sampled on a grid over the
+ * lake's box:
+ * - the signed distance to the outline, positive inside;
+ * - how deep the water is, from the ground under it (infinite where nothing is known).
+ * From the two comes one number, the share of the waves a point keeps: it is written into the mesh's vertices (so the geometry calms
+ * toward the shore) and into a small texture (so the pixels do, the edge is cut where the outline is, and the shore foams), and
+ * {@link ShoreField.damp} answers the same for the CPU. A body without an outline is its rectangle and a body without ground is
+ * as deep as it likes.
+ */
+
+/** The depth of water over ground nothing is known of: deep enough that nothing calms for it, and finite so a grid can be blended. */
+export const UNKNOWN_DEPTH = 1e9;
+
+/** A point on the body's plane. */
+export interface Point2 { x: number; y: number }
+
+/** The signed distance from (x, z) to the polygon's outline, positive inside it, negative outside. Self-intersecting outlines are not judged. */
+export function polygonSdf(poly: readonly Point2[], x: number, z: number): number {
+ let best = Infinity;
+ let inside = false;
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
+ const a = poly[j]!, b = poly[i]!;
+ const ex = b.x - a.x, ez = b.y - a.y;
+ const len2 = ex * ex + ez * ez;
+ let t = len2 > 0 ? ((x - a.x) * ex + (z - a.y) * ez) / len2 : 0;
+ t = Math.min(Math.max(t, 0), 1);
+ const dx = x - (a.x + t * ex), dz = z - (a.y + t * ez);
+ best = Math.min(best, Math.hypot(dx, dz));
+ if ((a.y > z) !== (b.y > z) && x < ((b.x - a.x) * (z - a.y)) / (b.y - a.y) + a.x) inside = !inside;
+ }
+ return inside ? best : -best;
+}
+
+/** The share of the waves kept where the water is `reach` deep or far from the edge: none at the edge, all from `width` in; with no width, all of them everywhere. */
+export function shoreDamp(reach: number, width: number): number {
+ if (width <= 0) return 1;
+ if (reach <= 0) return 0;
+ const t = Math.min(reach / width, 1);
+ return t * t * (3 - 2 * t);
+}
+
+/** The ground under the water: its height in the body's own space at (x, z), or null where none is known. */
+export type GroundDepth = (x: number, z: number) => number | null;
+
+/** The baked field over a lake's box. */
+export class ShoreField {
+ readonly minX: number;
+ readonly minZ: number;
+ readonly sizeX: number;
+ readonly sizeZ: number;
+ readonly res: number;
+ /** How far from the edge, and how deep, the waves take to come to their full height. */
+ readonly width: number;
+ /** Signed distance to the outline per sample, and the depth of the water ({@link UNKNOWN_DEPTH} where the ground is not known). */
+ readonly sdf: Float32Array;
+ readonly depth: Float32Array;
+
+ constructor(poly: readonly Point2[], res: number, width: number, ground?: GroundDepth) {
+ let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;
+ for (const p of poly) { minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x); minZ = Math.min(minZ, p.y); maxZ = Math.max(maxZ, p.y); }
+ this.minX = minX; this.minZ = minZ;
+ this.sizeX = Math.max(maxX - minX, 1e-3); this.sizeZ = Math.max(maxZ - minZ, 1e-3);
+ this.res = res;
+ this.width = width;
+ this.sdf = new Float32Array(res * res);
+ this.depth = new Float32Array(res * res);
+ for (let j = 0; j < res; j++) {
+ for (let i = 0; i < res; i++) {
+ const x = minX + (i / (res - 1)) * this.sizeX, z = minZ + (j / (res - 1)) * this.sizeZ;
+ this.sdf[j * res + i] = polygonSdf(poly, x, z);
+ const ground_ = ground ? ground(x, z) : null;
+ this.depth[j * res + i] = ground_ === null ? UNKNOWN_DEPTH : Math.min(-ground_, UNKNOWN_DEPTH);
+ }
+ }
+ }
+
+ private at(array: Float32Array, x: number, z: number): number {
+ const fx = Math.min(Math.max((x - this.minX) / this.sizeX, 0), 1) * (this.res - 1);
+ const fz = Math.min(Math.max((z - this.minZ) / this.sizeZ, 0), 1) * (this.res - 1);
+ const i = Math.min(Math.floor(fx), this.res - 2), j = Math.min(Math.floor(fz), this.res - 2);
+ const tx = fx - i, tz = fz - j;
+ const v = (a: number, b: number): number => array[b * this.res + a]!;
+ const lo = v(i, j) * (1 - tx) + v(i + 1, j) * tx, hi = v(i, j + 1) * (1 - tx) + v(i + 1, j + 1) * tx;
+ return lo * (1 - tz) + hi * tz;
+ }
+
+ /** The signed distance to the outline at (x, z). */
+ distance(x: number, z: number): number { return this.at(this.sdf, x, z); }
+
+ /** How deep the water is at (x, z). */
+ waterDepth(x: number, z: number): number { return this.at(this.depth, x, z); }
+
+ /** Whether (x, z) is inside the outline: the grid covers the outline's box, and nothing outside it is. */
+ inside(x: number, z: number): boolean {
+ if (x < this.minX || x > this.minX + this.sizeX || z < this.minZ || z > this.minZ + this.sizeZ) return false;
+ return this.distance(x, z) >= 0;
+ }
+
+ /** The share of the waves kept at (x, z). */
+ damp(x: number, z: number): number {
+ return shoreDamp(Math.min(this.distance(x, z), this.waterDepth(x, z)), this.width);
+ }
+
+ /**
+ * The field as RGBA8 for the shader: red the signed distance (0.5 at the edge, `range` away at 0 and 1), green the depth over `range`, blue the share of
+ * the waves kept, alpha 255. `range` is the distance the encoding spans, so the shader needs it too.
+ */
+ encode(range: number): Uint8Array {
+ const out = new Uint8Array(this.res * this.res * 4);
+ for (let k = 0; k < this.res * this.res; k++) {
+ const sdf = this.sdf[k]!, depth = this.depth[k]!;
+ out[k * 4] = Math.round(Math.min(Math.max(sdf / (2 * range) + 0.5, 0), 1) * 255);
+ out[k * 4 + 1] = Math.round(Math.min(Math.max(depth / range, 0), 1) * 255);
+ out[k * 4 + 2] = Math.round(shoreDamp(Math.min(sdf, depth), this.width) * 255);
+ out[k * 4 + 3] = 255;
+ }
+ return out;
+ }
+}
diff --git a/sdk/src/water/waterMesh.ts b/sdk/src/water/waterMesh.ts
index cd985b3fe..1b9e2d668 100644
--- a/sdk/src/water/waterMesh.ts
+++ b/sdk/src/water/waterMesh.ts
@@ -5,8 +5,9 @@
* @brief The geometry of a body of water: a flat grid for a lake, rings of coarsening grids for an ocean.
*
* @details Both lie in the body's xz plane facing up, with the uv the position itself (so the Water shader's body space is local x and
- * z), and the vertex colour's red the number of the ring the vertex is in, in sevenths (`cell * 2^(red * 7)` is its cell
- * size): the Water shader's vertex hook fades the waves a coarse ring cannot draw by it.
+ * z), the vertex colour's red the number of the ring the vertex is in, in sevenths (`cell * 2^(red * 7)` is its cell
+ * size: the Water shader's vertex hook fades the waves a coarse ring cannot draw by it), and its green the share of the waves
+ * the point keeps toward a lake's shore (1 elsewhere).
*
* An ocean is rings, each a grid of the same number of cells with twice the cell size of the one inside it and a hole where that one
* sits. Where two rings meet the coarse one has half the vertices along the edge, so the surfaces can part there by what the waves
@@ -22,20 +23,39 @@ interface Grid {
ring: number;
}
+/** What shapes a lake's grid beyond its box: how much of its waves each point keeps, and which cells are worth drawing at all. */
+export interface RectOptions {
+ /** The share of the waves kept at (x, z), 0 to 1: written into each vertex's green, which the Water shader's vertex hook multiplies the height by. */
+ damp?: (x: number, z: number) => number;
+ /** Whether the cell whose middle is (x, z) is drawn: a lake with a boundary of its own leaves out the cells wholly outside it. */
+ keep?: (x: number, z: number, cell: number) => boolean;
+}
+
/** A flat rectangle of water, `sizeX` by `sizeZ`, centred on its origin. */
-export function buildRectMesh(sizeX: number, sizeZ: number, cellSize: number): MeshData {
+export function buildRectMesh(sizeX: number, sizeZ: number, cellSize: number, options: RectOptions = {}): MeshData {
+ return buildBoxMesh(-sizeX / 2, -sizeZ / 2, sizeX / 2, sizeZ / 2, cellSize, options);
+}
+
+/** A flat grid over the box from (minX, minZ) to (maxX, maxZ), in the body's own space. */
+export function buildBoxMesh(minX: number, minZ: number, maxX: number, maxZ: number, cellSize: number, options: RectOptions = {}): MeshData {
+ const sizeX = maxX - minX, sizeZ = maxZ - minZ;
const cellsX = Math.max(1, Math.round(sizeX / cellSize)), cellsZ = Math.max(1, Math.round(sizeZ / cellSize));
const positions: number[] = [], colors: number[] = [];
for (let j = 0; j <= cellsZ; j++) {
for (let i = 0; i <= cellsX; i++) {
- positions.push(-sizeX / 2 + (i / cellsX) * sizeX, 0, -sizeZ / 2 + (j / cellsZ) * sizeZ);
- colors.push(0, 0, 0, 1);
+ const x = minX + (i / cellsX) * sizeX, z = minZ + (j / cellsZ) * sizeZ;
+ positions.push(x, 0, z);
+ colors.push(0, options.damp ? options.damp(x, z) : 1, 0, 1);
}
}
const indices: number[] = [];
const at = (i: number, j: number): number => j * (cellsX + 1) + i;
+ const cell = Math.max(sizeX / cellsX, sizeZ / cellsZ);
for (let j = 0; j < cellsZ; j++) {
- for (let i = 0; i < cellsX; i++) quad(indices, at(i, j), at(i, j + 1), at(i + 1, j), at(i + 1, j + 1));
+ for (let i = 0; i < cellsX; i++) {
+ if (options.keep && !options.keep(minX + ((i + 0.5) / cellsX) * sizeX, minZ + ((j + 0.5) / cellsZ) * sizeZ, cell)) continue;
+ quad(indices, at(i, j), at(i, j + 1), at(i + 1, j), at(i + 1, j + 1));
+ }
}
return pack(positions, colors, indices);
}
@@ -59,7 +79,7 @@ export function buildOceanMesh(cells: number, rings: number, cellSize: number):
for (let j = 0; j <= n; j++) {
for (let i = 0; i <= n; i++) {
positions.push(-grid.half + i * grid.cell, 0, -grid.half + j * grid.cell);
- colors.push(grid.ring / 7, 0, 0, 1);
+ colors.push(grid.ring / 7, 1, 0, 1);
}
}
for (let j = 0; j < n; j++) {
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index ec6a59f69..7df9bc252 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -23,11 +23,16 @@ import {
import { Assets } from '../asset/AssetPlugin';
import type { MaterialShaderSource } from '../asset/loaders/MaterialShaderAssetLoader';
import { Material, MATERIAL_FORMAT_VERSION } from '../render/material';
+import { createTextureFromPixels } from '../runtime/runtimeAssets';
+import { getResourceManager } from '../wasm/resourceManager';
+import { TextureContent } from '../wasm';
+import { TerrainsRes } from '../terrain/terrainPlugin';
import { BlendMode } from '../render/blend';
import { log } from '../util/logger';
import type { Entity } from '../types';
import { waveHeight, waveSlope, type WaveParams } from './waves';
-import { buildOceanMesh, buildRectMesh, oceanSnap } from './waterMesh';
+import { buildBoxMesh, buildOceanMesh, oceanSnap } from './waterMesh';
+import { ShoreField, type Point2 } from './shore';
/** What a body of water is. River arrives with the spline it follows. */
export const WaterForm = { Ocean: 0, Lake: 1, River: 2 } as const;
@@ -38,9 +43,13 @@ export interface WaterBodyData {
form: number;
/** A material on the Water shader. Empty uses the stock one. */
material: number;
- /** A lake's extent along x and z, centred on its entity. An ocean has none: it follows the camera. */
+ /** 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 follows the camera. */
sizeX: number;
sizeZ: number;
+ /** A lake's outline: three points or more round it on its own xz plane (x, y is x, z). Empty is the rectangle of `sizeX` by `sizeZ`. */
+ boundary: Point2[];
+ /** How far in from the edge, and how deep, the waves take to come to full height; 0 leaves them whole to the edge. */
+ shoreWidth: number;
/** The cell size of the finest ring, and (ocean) how many cells a ring has a side and how many rings there are. */
cellSize: number;
cells: number;
@@ -58,7 +67,7 @@ export interface WaterBodyData {
* @experimental
*/
export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {
- form: WaterForm.Lake, material: 0, sizeX: 100, sizeZ: 100, cellSize: 1, cells: 64, rings: 5,
+ form: WaterForm.Lake, material: 0, sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, cellSize: 1, cells: 64, rings: 5,
waveHeight: 0.3, waveLength: 14, waveSpeed: 1, waveDirection: 30,
}, {
assetFields: [{ field: 'material', type: 'material' }],
@@ -67,6 +76,8 @@ export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyD
material: { category: 'Look', tooltip: 'A material on the Water shader. Empty uses the stock water.' },
sizeX: { min: 1, category: 'Shape', tooltip: 'A lake\'s size along x.' },
sizeZ: { min: 1, category: 'Shape', tooltip: 'A lake\'s size along z.' },
+ boundary: { category: 'Shape', tooltip: 'The outline of a lake: points round it on its own xz plane. Empty is the rectangle of its size.' },
+ shoreWidth: { min: 0, category: 'Shape', tooltip: 'How far in from the edge, and how deep, the waves take to come to full height. 0 leaves them whole to the edge.' },
cellSize: { min: 0.05, category: 'Detail', tooltip: 'The cell size of the finest ring. Waves shorter than six cells are not drawn as geometry there (the shading still shows them).' },
cells: { min: 4, max: 256, step: 4, category: 'Detail', tooltip: 'Cells along a ring\'s side (an ocean).' },
rings: { min: 1, max: 8, step: 1, category: 'Detail', tooltip: 'Rings of an ocean, each twice as coarse as the one inside it.' },
@@ -96,6 +107,9 @@ interface Built {
signature: string;
data: WaterBodyData;
mesh: number;
+ /** A lake's baked shore, and the texture the shader reads it from. */
+ field: ShoreField | null;
+ shoreTexture: number;
child: Entity;
instance: number;
epoch: number;
@@ -123,11 +137,15 @@ export class Waters {
const scale = t.worldScale.y || 1;
const q = toLocal(t, x, y, z, scale);
const d = built.data;
- const inside = d.form === WaterForm.Ocean || (Math.abs(q[0]) <= d.sizeX / 2 && Math.abs(q[2]) <= d.sizeZ / 2);
+ const field = built.field;
+ const inside = d.form === WaterForm.Ocean || (field ? field.inside(q[0], q[2]) : false);
if (!inside) continue;
const params = paramsOf(d);
- const h = waveHeight(params, q[0], q[2], time);
- const [sx, sz] = waveSlope(params, q[0], q[2], time);
+ // The waves a lake keeps toward its shore are the ones its mesh was built with.
+ const damp = field ? field.damp(q[0], q[2]) : 1;
+ const h = waveHeight(params, q[0], q[2], time) * damp;
+ const [rx, rz] = waveSlope(params, q[0], q[2], time);
+ const sx = rx * damp, sz = rz * damp;
const len = Math.hypot(sx, 1, sz);
const normal = rotate(t.worldRotation, -sx / len, 1 / len, -sz / len);
const onSurface = fromLocal(t, q[0], h, q[2], scale);
@@ -153,6 +171,13 @@ export class Waters {
/** The resource the plugin installs. @experimental */
export const WatersRes = defineResource<Waters>(new Waters(), 'Waters');
+/** The outline of a lake: its own boundary when it has three points or more, else the rectangle of its size. */
+function outlineOf(d: WaterBodyData): Point2[] {
+ if (d.boundary.length >= 3) return d.boundary.map((p) => ({ x: p.x, y: p.y }));
+ const hx = d.sizeX / 2, hz = d.sizeZ / 2;
+ return [{ x: -hx, y: -hz }, { x: hx, y: -hz }, { x: hx, y: hz }, { x: -hx, y: hz }];
+}
+
function paramsOf(d: WaterBodyData): WaveParams {
return { height: d.waveHeight, length: d.waveLength, speed: d.waveSpeed, direction: d.waveDirection };
}
@@ -177,8 +202,8 @@ function fromLocal(t: TransformData, x: number, y: number, z: number, scale: num
}
/** What shapes the geometry: when it changes the child is rebuilt; the waves and the material are not part of it. */
-function signatureOf(d: WaterBodyData): string {
- return JSON.stringify([d.form, d.sizeX, d.sizeZ, d.cellSize, d.cells, d.rings, d.material]);
+function signatureOf(d: WaterBodyData, ground: string): string {
+ return JSON.stringify([d.form, d.sizeX, d.sizeZ, d.boundary, d.shoreWidth, d.cellSize, d.cells, d.rings, d.material, ground]);
}
export class WaterPlugin implements Plugin {
@@ -200,11 +225,11 @@ export class WaterPlugin implements Plugin {
const eye = this.eye(app);
for (const entity of app.world.getEntitiesWithComponents([WaterBody, Transform])) {
const data = app.world.get(entity, WaterBody) as WaterBodyData;
- const signature = signatureOf(data);
+ const signature = signatureOf(data, this.groundKey(app, entity, data));
let built = waters.built_.get(entity);
if (!built || built.signature !== signature) {
if (built) this.destroy(app, built);
- built = { signature, data: { ...data }, mesh: 0, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };
+ built = { signature, data: { ...data }, mesh: 0, field: null, shoreTexture: 0, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };
waters.built_.set(entity, built);
}
built.data = { ...data };
@@ -256,14 +281,27 @@ export class WaterPlugin implements Plugin {
if (built.epoch !== epoch || !app.world.valid(entity)) return;
const d = built.data;
const assets = app.getResource(Assets);
- const mesh = assets.createMesh(d.form === WaterForm.Ocean
- ? buildOceanMesh(d.cells, d.rings, d.cellSize)
- : buildRectMesh(d.sizeX, d.sizeZ, d.cellSize));
+ let mesh: number;
+ if (d.form === WaterForm.Ocean) {
+ mesh = assets.createMesh(buildOceanMesh(d.cells, d.rings, d.cellSize));
+ } else {
+ // A lake: its outline (or its rectangle), the ground under it, and what the two say about the waves and the shore.
+ const poly = outlineOf(d);
+ const reach = Math.max(...poly.map((p) => Math.abs(p.x)), ...poly.map((p) => Math.abs(p.y)));
+ const res = Math.min(256, Math.max(32, Math.ceil((reach * 2) / Math.max(d.cellSize * 0.5, 0.05))));
+ built.field = new ShoreField(poly, res, d.shoreWidth, this.groundUnder(app, entity));
+ const field = built.field;
+ mesh = assets.createMesh(buildBoxMesh(field.minX, field.minZ, field.minX + field.sizeX, field.minZ + field.sizeZ, d.cellSize, {
+ damp: (x, z) => field.damp(x, z),
+ keep: (x, z, cell) => field.distance(x, z) > -cell,
+ }));
+ }
if (mesh === 0) { log.warn('water', 'the engine refused the water geometry'); return; }
const instance = Material.createInstance(source);
if (instance === 0) { assets.releaseBuiltMesh(mesh); log.warn('water', 'the water material could not be instanced'); return; }
built.mesh = mesh;
built.instance = instance;
+ if (built.field) this.uploadShore(app, built);
const child = app.world.spawn('Water');
app.world.insert(child, Transform, { position: { x: 0, y: 0, z: 0 } });
app.world.insert(child, MeshRenderer, {
@@ -278,6 +316,46 @@ export class WaterPlugin implements Plugin {
}
}
+ /** Gives the shader a lake's shore: the baked field as a texture, and where over the lake it lies. */
+ private uploadShore(app: App, built: Built): void {
+ const field = built.field!;
+ // The encoding spans a few shore widths either side of the edge; a shore of none still needs a span for the foam.
+ const range = Math.max(built.data.shoreWidth * 4, 16);
+ const pixels = field.encode(range);
+ built.shoreTexture = createTextureFromPixels(app.wasmModule, { width: field.res, height: field.res, pixels }, TextureContent.Retained, false,
+ { filterMode: 'linear', wrapMode: 'clamp' });
+ Material.setUniform(built.instance, 'u_shoreMap', Material.tex(built.shoreTexture));
+ Material.setUniform(built.instance, 'u_shoreOn', 1);
+ Material.setUniform(built.instance, 'u_shoreOrigin', { x: field.minX, y: field.minZ });
+ Material.setUniform(built.instance, 'u_shoreSize', { x: field.sizeX, y: field.sizeZ });
+ Material.setUniform(built.instance, 'u_shoreRange', range);
+ }
+
+ /** The height of the ground under a body's plane, in the body's own space, where a terrain is and the body is level; else nothing is known. */
+ private groundUnder(app: App, entity: Entity): ((x: number, z: number) => number | null) | undefined {
+ if (!app.hasResource(TerrainsRes)) return undefined;
+ const terrains = app.getResource(TerrainsRes);
+ const t = app.world.tryGet(entity, Transform) as TransformData | null;
+ if (!t || terrains.built_.size === 0) return undefined;
+ const level = Math.abs(t.worldRotation.x) < 1e-4 && Math.abs(t.worldRotation.z) < 1e-4;
+ if (!level) return undefined;
+ const scale = t.worldScale.y || 1;
+ const sx = t.worldScale.x || 1, sz = t.worldScale.z || 1;
+ return (x, z) => {
+ const g = terrains.heightAt(t.worldPosition.x + x * sx, t.worldPosition.z + z * sz);
+ return g === null ? null : (g - t.worldPosition.y) / scale;
+ };
+ }
+
+ /** What the ground under a body adds to whether it must be rebuilt: the terrain's revision, and where the body stands over it. */
+ private groundKey(app: App, entity: Entity, data: WaterBodyData): string {
+ if (data.form === WaterForm.Ocean || !app.hasResource(TerrainsRes)) return '';
+ const terrains = app.getResource(TerrainsRes);
+ if (terrains.built_.size === 0) return '';
+ const t = app.world.tryGet(entity, Transform) as TransformData | null;
+ return t ? `${terrains.revision_}:${t.worldPosition.x}:${t.worldPosition.y}:${t.worldPosition.z}:${t.worldScale.x}:${t.worldScale.y}:${t.worldScale.z}` : '';
+ }
+
/** Writes the component into the instance, and moves an ocean's mesh to the camera. */
private update(app: App, entity: Entity, built: Built, eye: [number, number, number] | null, time: number): void {
const d = built.data;
@@ -308,6 +386,9 @@ export class WaterPlugin implements Plugin {
built.epoch++;
if (built.child && app.world.valid(built.child)) app.world.despawn(built.child);
if (built.instance) Material.release(built.instance);
+ if (built.shoreTexture) getResourceManager()?.releaseTexture(built.shoreTexture);
+ built.shoreTexture = 0;
+ built.field = null;
if (built.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.mesh);
built.child = 0 as Entity;
built.instance = 0;
diff --git a/sdk/tests/water-shore.test.ts b/sdk/tests/water-shore.test.ts
new file mode 100644
index 000000000..9b6e2e010
--- /dev/null
+++ b/sdk/tests/water-shore.test.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { ShoreField, polygonSdf, shoreDamp, type Point2 } from '../src/water/shore';
+import { buildBoxMesh } from '../src/water/waterMesh';
+import { MeshChannel } from '../src/asset/meshFormat';
+
+const square: Point2[] = [{ x: -10, y: -10 }, { x: 10, y: -10 }, { x: 10, y: 10 }, { x: -10, y: 10 }];
+// An L: a 20 x 20 square with its upper-right quarter (x > 0, z > 0) taken out.
+const ell: Point2[] = [{ x: -10, y: -10 }, { x: 10, y: -10 }, { x: 10, y: 0 }, { x: 0, y: 0 }, { x: 0, y: 10 }, { x: -10, y: 10 }];
+
+describe('polygonSdf', () => {
+ it('is the distance to the nearest edge, positive inside and negative outside', () => {
+ expect(polygonSdf(square, 0, 0)).toBeCloseTo(10, 10);
+ expect(polygonSdf(square, 7, 0)).toBeCloseTo(3, 10);
+ expect(polygonSdf(square, 13, 0)).toBeCloseTo(-3, 10);
+ expect(polygonSdf(square, 13, 14)).toBeCloseTo(-Math.hypot(3, 4), 10);
+ });
+
+ it('knows the notch of a concave outline is outside', () => {
+ expect(polygonSdf(ell, -5, -5)).toBeGreaterThan(0);
+ expect(polygonSdf(ell, 5, -5)).toBeGreaterThan(0);
+ expect(polygonSdf(ell, -5, 5)).toBeGreaterThan(0);
+ expect(polygonSdf(ell, 5, 5)).toBeLessThan(0);
+ // In the notch, the nearest edge is the one that bounds it.
+ expect(polygonSdf(ell, 5, 5)).toBeCloseTo(-5, 10);
+ });
+});
+
+describe('shoreDamp', () => {
+ it('keeps none of the waves at the edge and all of them from a shore width in', () => {
+ expect(shoreDamp(0, 4)).toBe(0);
+ expect(shoreDamp(-1, 4)).toBe(0);
+ expect(shoreDamp(4, 4)).toBe(1);
+ expect(shoreDamp(40, 4)).toBe(1);
+ expect(shoreDamp(2, 4)).toBeCloseTo(0.5, 10);
+ });
+
+ it('leaves the waves whole with no shore width', () => {
+ expect(shoreDamp(0.01, 0)).toBe(1);
+ expect(shoreDamp(0, 0)).toBe(1);
+ });
+});
+
+describe('ShoreField', () => {
+ it('answers the outline and the damping from its grid', () => {
+ const field = new ShoreField(square, 65, 4);
+ expect(field.inside(0, 0)).toBe(true);
+ expect(field.inside(15, 0)).toBe(false);
+ expect(field.distance(0, 0)).toBeCloseTo(10, 1);
+ expect(field.damp(0, 0)).toBe(1);
+ expect(field.damp(9, 0)).toBeLessThan(0.5);
+ expect(field.damp(10.5, 0)).toBe(0);
+ });
+
+ it('takes the water\'s depth from the ground under it, and calms the waves where it is shallow', () => {
+ // Ground rising from 8 under the water at x = -10 to the surface at x = 10.
+ const ground = (x: number): number => -8 + ((x + 10) / 20) * 8;
+ const field = new ShoreField(square, 65, 4, (x) => ground(x));
+ expect(field.waterDepth(-10, 0)).toBeCloseTo(8, 1);
+ expect(field.waterDepth(10, 0)).toBeCloseTo(0, 1);
+ expect(field.damp(-5, 0)).toBe(1);
+ // At x = 6 the water is 3.2 deep but the edge is 4 away: depth is the nearer limit.
+ expect(field.damp(6, 0)).toBeCloseTo(shoreDamp(Math.min(4, 8 - ((6 + 10) / 20) * 8), 4), 1);
+ expect(field.damp(9.5, 0)).toBeLessThan(0.1);
+ });
+
+ it('is as deep as it likes where nothing is known of the ground', () => {
+ const field = new ShoreField(square, 33, 4);
+ expect(field.waterDepth(0, 0)).toBeGreaterThan(1e6);
+ });
+
+ it('encodes distance, depth and damping for the shader', () => {
+ const field = new ShoreField(square, 33, 4, () => -2);
+ const range = 16;
+ const px = field.encode(range);
+ const at = (i: number, j: number): number[] => Array.from(px.subarray((j * 33 + i) * 4, (j * 33 + i) * 4 + 4));
+ const centre = at(16, 16);
+ // Ten from the edge: 0.5 + 10 / 32 of the way up; two deep: 2 / 16; the waves whole.
+ expect(centre[0]).toBeCloseTo(Math.round((0.5 + 10 / 32) * 255), 0);
+ expect(centre[1]).toBeCloseTo(Math.round((2 / 16) * 255), 0);
+ expect(centre[2]).toBeGreaterThan(0);
+ expect(centre[3]).toBe(255);
+ // A corner is on the edge: half way, and no waves.
+ const corner = at(0, 0);
+ expect(corner[0]).toBeCloseTo(128, 0);
+ expect(corner[2]).toBe(0);
+ });
+});
+
+describe('a lake mesh with a shore', () => {
+ it('writes the damping into each vertex and leaves out the cells wholly outside the outline', () => {
+ const field = new ShoreField(ell, 65, 4);
+ const mesh = buildBoxMesh(field.minX, field.minZ, field.minX + field.sizeX, field.minZ + field.sizeZ, 1, {
+ damp: (x, z) => field.damp(x, z),
+ keep: (x, z, cell) => field.distance(x, z) > -cell,
+ });
+ const full = buildBoxMesh(field.minX, field.minZ, field.minX + field.sizeX, field.minZ + field.sizeZ, 1);
+ expect(mesh.indices.length).toBeLessThan(full.indices.length);
+ // The far corner of the notch has no cell left in it.
+ const channel = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!;
+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);
+ for (let t = 0; t < mesh.indices.length; t += 3) {
+ let sx = 0, sz = 0;
+ for (let k = 0; k < 3; k++) {
+ const v = mesh.indices[t + k]!;
+ sx += view.getFloat32(v * mesh.vertexStride + channel.offset, true) / 3;
+ sz += view.getFloat32(v * mesh.vertexStride + channel.offset + 8, true) / 3;
+ }
+ expect(field.distance(sx, sz)).toBeGreaterThan(-2);
+ }
+ const color = mesh.channels.find((c) => c.semantic === MeshChannel.Color)!;
+ const greens = new Set<number>();
+ for (let i = 0; i < mesh.vertexCount; i++) greens.add(mesh.vertices[i * mesh.vertexStride + color.offset + 1]!);
+ expect(greens.size).toBeGreaterThan(3);
+ expect(Math.max(...greens)).toBe(255);
+ });
+});
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index 24e60bca6..6b2f3e42d 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -123,7 +123,7 @@ const DISPOSITION = {
SceneOwner: ['derived', 'scene loading records which scene an entity came from; authoring it would claim an ownership the loader never granted'],
// — code-only: an example demonstrates it from TypeScript, honestly —
- WaterBody: ['owed', 'no example carries a body of water yet; the first lake with a boundary of its own (the next step of the water work) goes into one'],
+ WaterBody: ['owed', 'no example carries a body of water yet; the first of the water work that is shown off (rivers, with the spline) goes into one'],
Replicated: ['code-only', 'multiplayer-arena declares its replicated set beside the server systems that own it; the wire table is a contract both ends compile against, not scene content'],
// — owed: a creator-facing component nothing in the shipped corpus authors.
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index 1237f2b90..8a06a8e08 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -122,6 +122,7 @@ const DISPOSITION = {
'Foliage.drawDistance': ['no-place', 'a distance from the camera past which nothing is drawn'],
'WaterBody.sizeX': ['owed', 'the lake extent is not outlined in the viewport yet; the lake tools will draw its boundary'],
'WaterBody.sizeZ': ['owed', 'the lake extent is not outlined in the viewport yet; the lake tools will draw its boundary'],
+ 'WaterBody.shoreWidth': ['no-place', 'a distance in from a lake edge over which the waves come to full height, not a region of the entity'],
'WaterBody.cellSize': ['no-place', 'the cell size of the finest ring of geometry, not a region of the entity'],
'WaterBody.waveHeight': ['no-place', 'the height of the tallest wave, not a region of the entity'],
'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index b67765ca3..88ff64b61 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2559,6 +2559,8 @@ export const NOTED = {
{"note":"Cyber Rooftop gets a rebuilt rooftop model and textures, a wet roof material with a planar reflection under a rain sky, rain, fog and bloom in the scene, a larger set of HUD icons and inventory art, and a wider build footprint."},
"feat(water): a WaterBody builds an ocean or a lake whose waves lift the geometry and can be read from code":
{"note":"Water gets a component and a chapter of its own. A WaterBody builds an ocean (without an edge, following the camera, in rings that coarsen with distance) or a rectangular lake, lifts its geometry with the waves, follows its own up when it is tilted, and answers for its surface from code (`Waters.sample`) with the same formula the shader draws. Water is an optional module (`esengine/water`): a 2D game carries none of it."},
+ "feat(water): a lake takes an outline of its own and calms its waves toward the shore":
+ {"note":"A lake can have an outline of its own and knows its shore. `boundary` cuts it to a polygon on its plane (crisp at the pixel, not at the grid's cells), `shoreWidth` calms its waves toward the edge and where it is shallow over a Terrain, and the shore foams along the outline. `Waters.sample` answers with the same calmed waves and says a point in the notch of a concave lake is not inside."},
"chore(tools): the gates run in parallel with --jobs, and the reds a full run gathered are cleared":
{"internal":"tooling for the static gates, and fixes to checks that had drifted from the code they guard"},
"fix(render): a wire narrower than a pixel is no longer painted over by the sky in dashes":