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): every body of water is baked into a zone and drawn as one surface

yhh437cc421b09d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 90b0d3214..bd6126266 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,20 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **Water zones.** Oceans, lakes and rivers are now drawn as one surface. A `WaterBody` says what water is where (its form, outline or Spline, shore width, current and how high its waves stand), and a new `WaterZone` bakes every body over its region into one field: the surface's height, the distance to the shore, the waves' height, the current and the depth over the terrain. One mesh of rings that follows the camera reads it, so a river runs into a lake or the sea at one height with its banks running on into the shore, its current fades into the still water, and no shore foams across its mouth; a lake or a river over the sea is the lake's, not the sea's, and the sea's waves calm and foam where it shallows over the terrain. The zone holds what the bodies share: the material, the waves' length, speed and heading, the mesh's detail and the ripples. A scene without one gets a zone over its lakes and rivers, and the ocean goes on past it. `Waters.sample` reads the same field, so what floats or looks out from under the water meets the surface that is drawn. In the editor the zone's region is outlined in the viewport.
+- **Wind and rain on the water.** The weather drives the wind: each preset has a wind and a wave strength (mist calms, a storm raises the waves to over twice their height), the Water Body's waves and the foliage's sway follow it in play, and a Weather that does not drive the wind (`WeatherDrive.Wind`) leaves them as authored. Rain falls on water that keeps ripples as rings, as hard as the weather rains, and the rain effect no longer lays a wet floor or puddles over the water itself.
+
+### Changed
+
+- **`WaterBody` keeps only what a body says.** Its `material`, `cellSize`, `cells`, `rings`, `waveLength`, `waveSpeed`, `waveDirection` and ripple fields have moved to the new `WaterZone`, which every body shares; `shoreWidth` now calms the waves toward the shore of an ocean and a river as well as a lake. A body of water is no longer tilted with its entity: it is turned about up only. `ShoreField`, `buildRectMesh`, `buildBoxMesh` and `buildRiverMesh` are gone from `esengine/water`.
+
+### Fixed
+
+- **A mesh on a material records its surface.** An opaque mesh whose material has a blend mode of Normal (the default) was drawn blended, so it wrote no surface record, and the effects that read it (screen-space reflections, rain, contact shadows) passed over it, and alpha-to-coverage cut-outs on it had no coverage. It is now drawn opaque. Water and refracting glass write their own record where the device can blend one target and not another (WebGPU, and WebGL2 with `OES_draw_buffers_indexed`).
+- **A terrain's splatmap keeps all four layers.** A splatmap whose fourth layer is in its alpha no longer erases the other three where that layer is thin: it is read as the numbers in the file, not as a colour the browser premultiplies by its alpha.
+
## [0.95.0] - 2026-10-24
### Added
diff --git a/desktop b/desktop
index 8c84b50c8..090f48016 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 8c84b50c83d8274c25662d0c597147ac5f61b45c
+Subproject commit 090f4801634f17c2070a72b5a3918b2cb1c8399f
diff --git a/docs/WATER_DESIGN.md b/docs/WATER_DESIGN.md
index 7a2f4b1c2..55bd25e7b 100644
--- a/docs/WATER_DESIGN.md
+++ b/docs/WATER_DESIGN.md
@@ -1,6 +1,7 @@
# 水体系统设计(RM-138)
-状态:**W0 到 W10 已实现并在本机验收(见 9.1),目标真机未验收**。写于 2026-10-23;下文第 1 到 8 节是当时的设计,保留原样。依据是本仓库当前代码和 RM-138 卡片的正文;竞品一栏只写通用常识,
+状态:**W0 到 W10 已实现并在本机验收(见 9.1),目标真机未验收**。写于 2026-10-23;下文第 1 到 8 节是当时的设计,保留原样。
+**2026-10-24 起,水的结构改为“水体区域”**:水体不再各自建网格,而是作为输入烘进一个 `WaterZone`,由一个跟随相机的网格画出整个水面,见 §3.1;第 3、5 节里“每种形态各出网格”“水体自带材质与波参数”“倾斜水面”的说法已被取代。依据是本仓库当前代码和 RM-138 卡片的正文;竞品一栏只写通用常识,
**未逐条核对官方文档**,上板前需要补来源。涉及编辑器界面的部分,卡片要求先出控件设计稿并获得确认,本文只给范围,不给界面。
## 1. 现状(已核对代码)
@@ -61,6 +62,33 @@ WaterBody { form: Ocean | Lake | River, level, waves[], material, quality… }
3. **着色**:现有 Water 着色器的延伸(流向、水下视角、焦散、交互涟漪作为输入)。
4. **物理交互**:`Floating` 组件只依赖契约和 3D 物理,不依赖渲染模块。
+## 3.1 现行架构:水体区域(2026-10-24 重构)
+
+各形态各建一张网格时,河流流进湖或海的地方是两个表面的接缝:两个高度、两套波浪、河口处横着一条岸线泡沫、河带的边露在湖面上。重构后:
+
+**水体是输入,不是网格。** `WaterBody` 只留 `form`(Ocean/Lake/River)、`sizeX`、`sizeZ`、`boundary`、`shoreWidth`(三种形态都用)、`flowSpeed`(河)、`waveHeight`。
+`material`、`cellSize`、`cells`、`rings`、`waveLength`、`waveSpeed`、`waveDirection`、`ripples`、`rippleSize`、`rippleSpeed`、`rippleDamping`、`foamFade` 移到区域上。
+
+**`WaterZone` 组件**(`sdk/src/water/zone.ts`):`sizeX`、`sizeZ`(以实体为中心的区域,只看 x、z)、`resolution`(较长一边的纹素数)、`material`、
+三个共用波参数、水面网格的 `cellSize`/`cells`/`rings`、涟漪五项。它把区域内所有水体烘成一张 `WaterField`,每个纹素存:
+
+- 水面高度(湖的水位、河流曲线最近处的高度、海平面);
+- 到最近岸线的有符号距离(水上为正),决定裁切与岸边泡沫;
+- 波高(水体 `waveHeight` × 向岸与变浅的平静系数)及平静系数本身;
+- 水流(河流的,在起点和终点各一个河宽内渐入渐出),以及水在地形之上的深度。
+
+两个水体相接处按纹素在各自内部的深浅加权混合(过渡一个半纹素),所以河口与湖、海之间没有接缝;湖和河优先,海取剩下的;没有水的纹素取最近水面的高度。
+场景没有 `WaterZone` 时,自动给一个覆盖所有湖和河的隐式区域(组件默认值,格子放大到能从区域内任何位置覆盖整个区域);只有海时整个水面就是海。
+只用找到的第一个 `WaterZone`、第一个海洋。海在区域外继续延伸(着色器参数 `u_oceanOn`/`u_oceanLevel`/`u_oceanWaves`)。烘焙在 CPU 上,水体、区域或地形变化时整张重烘。
+
+**一个水面。** `buildOceanMesh` 的多圈网格跟随相机,就是整个水面;顶点钩子逐纹素读区域的高度纹理(高低两字节编码,先解码再混合),场纹理(岸线距离、水流、平静系数)按线性过滤读取。
+波由区域共用,每处的高度 = 水体 `waveHeight` × 岸边平静系数 × 天气(`WeatherDrive.Wind`)。
+
+**采样契约不变,数据源变了。** `Waters.sample/disturb/rippleAt/heightAt` 读同一张烘好的场;`WaterSample.entity` 是那里占水最多的水体。涟漪由区域保留(一个跟随相机的窗口),天气驱动下雨时雨滴落进涟漪。
+
+**取消的能力。** 不再支持倾斜水面(水体只能绕上方向旋转);每水体一个材质改为每区域一个材质。移除的公开导出:`ShoreField`、`UNKNOWN_DEPTH`、`GroundDepth`、`buildBoxMesh`、`buildRectMesh`、
+`RectOptions`、`buildRiverMesh`;新增 `WaterZone`、`WaterField`、`currentShare`(移到 `zone.ts`)、`WaterZoneData`、`FieldSample` 类型。
+
## 4. 分期
估时按"一天一张卡、大卡两天"的口径,**是估计,不是承诺**。顺序按依赖排。
@@ -126,7 +154,7 @@ WaterBody {
}
```
-字段名与取值以 W1 的实现为准,上面只定形状。
+字段名与取值以 W1 的实现为准,上面只定形状。现行字段见 §3.1(区域重构后)。
## 6. 与竞品的对照(未核实)
@@ -184,6 +212,8 @@ WaterBody {
湖比海贵是因为它的水面铺满了视口(像素多),不是顶点多;128 格涟漪的 CPU 增量约 0.3 到 0.5 毫秒。反射开关与档位切换的前后对比**没有量**:`water-quality` 只验证档位改变了什么,没有记录它省了多少。
+**注(2026-10-24):**区域重构取消了倾斜水面,验收表“水平与倾斜水面”一行的倾斜部分只是当时的记录;湖、海、河的耗时也是重构前每水体一张网格时量的,重构后没有重测。
+
**导出**(`estella export`,blank 模板加一个 WaterBody 的副本对比原模板,`--minify`,editor 的 wasm,只说量级):
| | 不含水 | 含水 | 差 |
diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdx
index 68ff1ab4e..d9386850e 100644
--- a/docs/astro/src/content/docs/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/graphics/materials.mdx
@@ -49,8 +49,9 @@ shader** yourself.
## Water
-The **Water** shader (`builtin:water`) draws a body of water: refraction by measured depth, reflection and foam. The `WaterBody` component builds an
-ocean or a lake from it, lifts the geometry with waves and answers for the surface from code. All of it is in [Water](/docs/graphics/water/).
+The **Water** shader (`builtin:water`) draws a body of water: refraction by measured depth, reflection and foam. `WaterBody` components say where an
+ocean, a lake or a river is, and a `WaterZone` bakes them into one surface drawn with it, lifts the geometry with waves and answers for the surface from code.
+All of it is in [Water](/docs/graphics/water/).
## Skin and hair
diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdx
index be5df9170..8707e2079 100644
--- a/docs/astro/src/content/docs/graphics/water.mdx
+++ b/docs/astro/src/content/docs/graphics/water.mdx
@@ -1,49 +1,82 @@
---
title: Water
-description: A WaterBody component that builds an ocean or a lake, lifts its geometry with waves the CPU can read back, follows its own up when tilted, and the Water shader that draws it.
+description: WaterBody components that say where an ocean, a lake or a river is, a WaterZone that bakes them into one field and draws one surface from it with waves the CPU can read back, and the Water shader that draws it.
---
-Water has two halves. The **Water shader** (`builtin:water`) is the look: refraction, depth, reflection, foam. The **`WaterBody` component** is the
-body: it builds the geometry, lifts it with waves, and answers questions about its surface from the code, so what a script reads is what is drawn.
-This chapter is both, and what is not there yet.
+Water has three parts. The **Water shader** (`builtin:water`) is the look: refraction, depth, reflection, foam. A **`WaterBody`** says what water is
+where: an ocean, a lake, a river. A **`WaterZone`** bakes every body over its region into one field and draws one surface from it, lifted by waves,
+and answers questions about that surface from the code, so what a script reads is what is drawn. This chapter is all three, and what is not there yet.
Water is an optional module: a package takes it only when a scene authors a `WaterBody` (or a script imports `esengine/water`), so a 2D game
carries none of it.
## The component
-Add a `WaterBody` to an entity. The entity places and tilts the water; its child is the mesh, made when the scene runs and rebuilt when the shape
-changes.
+Add a `WaterBody` to an entity. A body is not drawn on its own: it is an input to the zone ([The zone](#the-zone)), which bakes it with every other body
+into one surface. The entity places the body; it may be turned about its up, not tilted.
| Field | What it does |
|---|---|
-| `form` | **Ocean**: without an edge, follows the camera. **Lake**: a rectangle of `sizeX` by `sizeZ` centred on the entity, or the outline in `boundary`. **River**: follows the `Spline` on the same entity. |
-| `flowSpeed` | A river's current, in world units a second where it is as wide as its widest. |
+| `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. |
+| `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 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. |
-| `waveHeight`, `waveLength`, `waveSpeed`, `waveDirection` | The waves (below). |
+| `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. |
+| `flowSpeed` | A river's current, in world units a second where it is as wide as its widest. |
+| `waveHeight` | The height of the tallest wave, in world units. The waves' length, speed and heading are the zone's, which every body shares. |
+
+Moving a body, editing its fields, its outline or its spline, or changing the terrain under it rebakes the zone, so the water follows at once.
+
+## The zone
+
+A `WaterZone` says where the water is drawn, how finely, and what every body shares. Put one on an entity with a `Transform`: its region is
+`sizeX` by `sizeZ`, centred on the entity (only its x and z count).
+
+| Field | What it does |
+|---|---|
+| `sizeX`, `sizeZ` | The region baked. Water outside it is not drawn; an ocean goes on past it. |
+| `resolution` | Texels along the region's longer side: how finely shores and rivers are traced. |
+| `material` | A material on the Water shader for the whole surface. Empty uses the stock water. |
+| `waveLength`, `waveSpeed`, `waveDirection` | The waves every body shares ([Waves](#waves)). |
+| `cellSize`, `cells`, `rings` | The surface's mesh: the cell size of its finest ring, cells along a ring's side, and how many rings ([Geometry](#geometry)). |
+| `ripples`, `rippleSize`, `rippleSpeed`, `rippleDamping`, `foamFade` | The ripples the zone keeps ([Ripples](#ripples)). |
+
+The zone bakes every body over its region into a grid, each texel holding what the water is there:
+
+- the **height** of its surface: a lake's level, the height of a river's curve at its nearest place, the ocean's level;
+- the signed **distance to the nearest shore**, positive on the water: where the surface is cut and where it foams;
+- how high the **waves** stand there: the body's `waveHeight`, calmed toward its shore and as the water shallows (and the share of it kept, which calms the shading too);
+- the **current** (a river's), and the **depth** of the water over the ground.
+
+Where two bodies meet, each texel weighs what each says by how far inside it the texel is, over a texel and a half, so the values run from one to the other:
+a river is at its lake's level where it runs into it, its current fades into the still water, and its banks run on into the lake's shores with no seam.
+Lakes and rivers come first and the ocean has what they leave, so a lake by the sea is the lake's. A texel no body holds keeps the height of the nearest water,
+so the surface's edge, which the shore cuts, is not pulled down to nothing.
-The body writes its waves, its cell size and its position in space into its own copy of the material every frame, so editing a field moves the
-water at once and several bodies can share one material asset.
+A scene without a `WaterZone` is given one over every lake and river (and a margin for their shores) with the component's defaults, at half the finest cell to a texel
+(32 to 1024 texels along the longer side); its cells grow so the surface reaches over the whole region from wherever the camera is in it. A scene with only an ocean
+needs no region: the whole surface is the ocean. One zone is used: the first `WaterZone` found.
+
+The bake is the CPU's and needs no renderer, so a server or a test that draws nothing can still ask the surface where it is. It is redone whole when a body, the zone or the
+terrain changes, at a cost of the texels times the bodies.
## Waves
Four peaked sines (`exp(sin(theta) - 1)`: a crest narrower than its trough) a few directions apart, each with a length, a height and a speed
-that are shares of the four numbers on the component. They **move the geometry**: the shader lifts each vertex by the wave height, and the
-fragment takes the slope per pixel from the same formula, so the lit surface is the one that is drawn and the silhouette against the sky rises
-and falls with the waves.
+that are shares of the zone's `waveLength`, `waveSpeed` and `waveDirection`. Every body shares them; how high they stand at a place is that place's in the
+field: its body's `waveHeight`, times the share the shore leaves, times the weather's (a `Weather` that drives the wind scales every wave). They **move the geometry**:
+the shader lifts each vertex by the wave height, and the fragment takes the slope per pixel from the same formula, so the lit surface is the one that is drawn and
+the silhouette against the sky rises and falls with the waves.
-The waves are measured in the body's own space, along its surface and up its own up, so a tilted body is tilted water. Parameters are in world
-units: a scene in metres wants the defaults, one in centimetres wants the lengths scaled.
+The waves are measured on the world's xz plane and lift the surface straight up. Parameters are in world units: a scene in metres wants the defaults, one in
+centimetres wants the lengths scaled.
## Geometry
-A **lake** is a grid of `cellSize` cells. An **ocean** is rings of the same number of cells, each twice as coarse as the one inside it with a hole
-where that one sits, so it reaches far and spends its triangles near. It follows the camera on a lattice all its rings line up on, and the
-material's origin moves by as much, so the waves stay put in the world while the mesh moves under them.
+The whole surface is one mesh: rings of the same number of cells (`cells` a side), the finest of `cellSize` cells, each twice as coarse as the one inside it
+with a hole where that one sits, so it reaches `cells * cellSize * 2^(rings - 1) / 2` from its centre and spends its triangles near. It follows the camera on a
+lattice all its rings line up on, and the material's origin moves by as much, so the water stays put in the world while the mesh moves under it. Its vertex hook
+reads the zone's field at each vertex (the heights texel by texel, decoded and then blended) and lifts the vertex to the water's height there plus its waves; the
+pixels where the field says there is no water are cut.
A coarse ring cannot draw a short wave: below three cells to a wavelength it would alias, so its vertices fade out the waves shorter than six of
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
@@ -51,28 +84,30 @@ can part by what the waves do between them; keep `waveLength` at least six of th
## 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.
+A lake is its outline at its entity's height. The zone takes the signed distance to the outline, and with a `Terrain` in the scene the depth of the water over it,
+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.
-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.
+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.
## Rivers
-A river is a ribbon laid along the `Spline` on its own entity ([Splines](#splines)): a row of vertices across the water every `cellSize` along the curve,
-as wide as the curve says there, at the height of the curve under it, so a river runs downhill. Put a `Spline` and a `WaterBody` with `form` River on one
-entity and the river is built when the scene runs.
+A river follows the `Spline` on its own entity ([Splines](#splines)): it is as wide as the curve says there, at the height of the curve at its nearest place,
+so a river runs downhill. Put a `Spline` and a `WaterBody` with `form` River on one entity and the zone bakes it.
- **The current.** `flowSpeed` is how fast the water runs where the river is as wide as its widest; a narrower reach runs faster and a wider one slower,
- within a quarter and double of it, as the same water through a different width does. The direction is the curve's.
+ within a quarter and double of it, as the same water through a different width does. The direction is the curve's. It fades in over a width from the
+ river's start and out over a width into whatever it runs into, so a river's mouth is still water.
- **The surface rides it.** The shader carries the waves and ripples downstream: two copies of the surface are moved along the current a cycle at a time, each
fading in as the other fades out, so the moment one is put back at its start is hidden by the other, and the surface does not stretch where the river bends.
-- **Flat geometry.** A river's geometry is not lifted by the waves (its surface is drawn flat and moved only in the shading), so a river has no waves to read
- back: `Waters.sample` gives its curve's height, a normal of up, and the current in `flow` (world units a second, along the river; zero elsewhere).
-- **Banks.** The edge is the ribbon's own, so it is as crisp as the geometry. Foam where it meets the ground comes from the depth of the scene, as at any shore.
+- **Waves.** A river has its own `waveHeight`, calmed toward its banks over `shoreWidth`, like any body. `Waters.sample` gives the current in `flow`
+ (world units a second, along the river; zero elsewhere).
+- **Banks and mouths.** A bank is where the field's shore distance crosses zero, traced at the zone's resolution. Where a river runs into a lake, the sea or
+ another river, the two are blended over a texel and a half, so there is no seam, no shore across the mouth and no step in height.
## Floating
@@ -98,22 +133,24 @@ toward anything but by the current.
## Ripples
-A body of water keeps what disturbs it when `ripples` is above 0. The water holds a square window of its surface (`rippleSize` world units a side, `ripples` cells along it)
+The zone keeps what disturbs the water when `ripples` is above 0. It holds a square window of the surface (`rippleSize` world units a side, `ripples` cells along it)
as a grid of heights and steps it with the wave equation: every cell is pulled toward its neighbours and carries the velocity it had, so a bump put in spreads as a ring
at `rippleSpeed`, loses `rippleDamping` of its height a second, and is gone. Beside the heights the grid keeps **foam**: a disturbance feeds it where it happened and it fades
at `foamFade` a second, so a splash leaves white water that lingers and thins and does not blink out with the ring.
-- **Who disturbs.** A script calls `Waters.disturb(x, y, z, radius, strength)` (the point goes to the body that holds it; `strength` is a height in world units, negative is a dip),
+- **Who disturbs.** A script calls `Waters.disturb(x, y, z, radius, strength)` (`strength` is a height in world units, negative is a dip; it does nothing where there is no water),
and a `Floating` body does it itself: what goes down into the water, comes up out of it or moves along its surface pushes the water by its speed (`wake` multiplies it).
+ When a `Weather` drives the rain, rain falls on the window as drops: small dips a cell and a half across, as many a second as the rain asks.
- **What it changes.** The shader reads the grid as a texture: the slope of the ripples bends the normal, which is what the light, the reflection and the refraction see, and the foam
whitens the surface. The geometry is not lifted by it. The surface the code reads does carry them: `Waters.sample` adds the ripple's height to the surface, and `Waters.rippleAt(x, y, z)`
gives it alone, so a floating ball is lifted by the ring that passes under it.
-- **Where.** The window follows the active camera, in whole cells, so a lake or an ocean of any size has ripples where they are seen for the price of one grid. What the window leaves behind is
- forgotten, and what it comes to is still water. A wave reaching its edge goes out and is not reflected. The grid is stepped on the CPU, in as many substeps as keep a wave from crossing more than
- half a cell, and uploaded as an RGBA8 texture (red the height, green the foam): the same on every backend.
+- **Where.** The window follows the active camera, in whole cells, so water of any size has ripples where they are seen for the price of one grid, shared by every body. What the window
+ leaves behind is forgotten, and what it comes to is still water. A wave reaching its edge goes out and is not reflected. The grid is stepped on the CPU, in as many substeps as keep a wave
+ from crossing more than half a cell, and uploaded as an RGBA8 texture (red the height, green the foam): the same on every backend.
-The grid can hold as much height as `max(2 * waveHeight, rippleSize / 50)`: a disturbance that goes on (a body moving) saturates there and does not pile up. A cell is `rippleSize / ripples`
-world units, so a ripple narrower than a cell or two is not drawn. Cost is `ripples` squared per substep and one texture upload a frame: 128 is sixteen thousand cells.
+The grid can hold as much height as `max(2 * tallest waves, rippleSize / 50)`, the tallest waves being the highest any place in the field stands to, times the weather's: a disturbance that
+goes on (a body moving) saturates there and does not pile up. A cell is `rippleSize / ripples` world units, so a ripple narrower than a cell or two is not drawn. Cost is `ripples` squared per
+substep and one texture upload a frame: 128 is sixteen thousand cells.
## Under the surface
@@ -161,18 +198,21 @@ end of an open curve it is the end; a closed curve goes round. Splines are an op
## In the editor
-Details shows a water body only what its form uses: a lake has its size, boundary and shore width, an ocean its cells and rings, a river its flow speed; the waves, ripples and
-look are common. A lake's **Boundary** row says how many points its outline has (or that it is the rectangle of its size) and resets it to the rectangle.
+Details shows a water body only what its form uses: a lake has its size and boundary, a river its flow speed, and every form its shore width and wave height. A lake's
+**Boundary** row says how many points its outline has (or that it is the rectangle of its size) and resets it to the rectangle. A `WaterZone` shows its fields in groups:
+Region, Look, Waves, Detail and Ripples.
Select a lake or a river and its points are handles in the viewport, the way a polygon collider's vertices are:
-- **Lake.** A square on each point of the outline and a circle in the middle of each edge. Drag a point to move it on the lake's own plane (the plane of its transform, so a tilted
- lake is edited tilted); drag an edge's circle to insert a point there; press a point and release it in place to delete it. A lake keeps at least three points, and with none the
- four corners of its rectangle are the points: pulling one turns the outline into a boundary of its own.
+- **Lake.** A square on each point of the outline and a circle in the middle of each edge. Drag a point to move it on the lake's own plane; drag an edge's circle to insert a
+ point there; press a point and release it in place to delete it. A lake keeps at least three points, and with none the four corners of its rectangle are the points: pulling one
+ turns the outline into a boundary of its own.
- **River.** The same on the curve of its `Spline`, with a second handle at each point, offset across the river by half its width: drag it to set the width there. A river keeps at least two
points. The point last pressed shows its width in Details under the Spline, where it can be typed.
- Each gesture is one undo step, and the points are written back as they are dragged, so the water follows. The handles are the **Water** entry of the Gizmo menu.
+A zone's region has no handles: set its size in Details.
+
## Quality levels
Water spends what the project's quality level says it may. The five fields are in each level's profile (`project.esproject`, `features.rendering.quality.profiles`), and a project can change what a level means. **Project Settings → Rendering → Level · Water** edits them for the level chosen under Editing level; the group is hidden while quality is off or the project excludes the water module.
@@ -180,41 +220,43 @@ Water spends what the project's quality level says it may. The five fields are i
| Field | Low | Medium | High | What it does |
|---|---|---|---|---|
| `waterWaves` | 2 | 3 | 4 | How many of the four waves are summed: in the geometry, the shading, and what `Waters.sample` answers. |
-| `waterRippleCells` | 32 | 64 | 128 | The most cells along a side of the ripple grid; a body's own `ripples` is held to it, and 0 keeps none. |
-| `waterDisplacement` | off | on | on | Whether the waves lift the geometry. Off is the **lite water**: a flat surface whose waves are in the shading only. |
+| `waterRippleCells` | 32 | 64 | 128 | The most cells along a side of the ripple grid; the zone's own `ripples` is held to it, and 0 keeps none. |
+| `waterDisplacement` | off | on | on | Whether the waves lift the geometry. Off is the **lite water**: a surface at the water's rest height whose waves are in the shading only. |
| `waterMirror` | off | on | on | Whether the surface seen from below mirrors the world under it (the screen-space march). |
| `waterCaustics` | off | on | on | Whether the sun's web of light is drawn on what lies under the water, and, seen from under it, the shafts. |
-What code reads follows what is drawn: at a level without displacement the surface is flat for `Waters.sample`, floating things sit on the rest plane, and fewer waves is fewer
+What code reads follows what is drawn: at a level without displacement the surface is at rest for `Waters.sample`, floating things sit on it, and fewer waves is fewer
waves for both. With a quality policy running, the active level decides; with none, a **minigame** gets the Low profile's water (the least it has to spend), and anything else gets all of it.
The lite water costs no vertex work for the waves, and the shading still moves, so it reads as water at a distance.
## Asking the surface
-`Waters.sample(x, y, z)` (the `WatersRes` resource) answers for the body that holds a point:
+`Waters.sample(x, y, z)` (the `WatersRes` resource) answers from the zone's field, the same numbers the surface is drawn from:
-- `depth`: how far the point is above the surface along the body's up (negative under it), in world units;
+- `entity`: the body that owns most of the water there (where two meet, the one the point is further inside);
+- `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;
-- `inside`: whether the point is over the body's extent: inside a lake's outline or a river's banks (an ocean has none, so it is always);
+- `inside`: whether the point is over water: always, for an answer that is not null;
- `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. 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`.
+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`.
-The surface the code reads is the full wave sum; a coarse far ring of an ocean draws less of it (see above), so near the horizon the two can
+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.
## The Water shader
`builtin:water` also works on its own, on any mesh, which is how a flat plane of water was made before the component. With `u_waveSpace` at its
-default (0) the waves are measured on the world's xz plane, nothing is lifted and the surface is taken to lie flat. The component turns it to 1 (the
-mesh's uv is its local x and z) for the body's own space.
+default (0) the waves are measured on the world's xz plane, nothing is lifted and the surface is taken to lie flat. The zone turns it to 1: the mesh's uv
+is its x and z, `u_origin` is where the mesh was moved to as it follows the camera, and the vertices are lifted to the zone's water and its waves.
- **Caustics.** `u_causticStrength` (0 turns them off), `u_causticScale` (the size of one cell, in world units) and `u_causticSpeed` shape the web of light on what is under the water, seen from
above and, through the effect, from below.
- **Waves.** `u_waveLength`, `u_waveHeight`, `u_waveSpeed`, `u_waveDirection`; small ripples (`u_rippleStrength`, `u_rippleLength`) ride on them and
- fade out with distance, so far water is calm rather than aliased.
+ fade out with distance, so far water is calm rather than aliased. On a zone's surface the zone writes the four every frame (its own length, speed and heading, and
+ the weather's share as the height, which each place's height in the field multiplies), so the material's values for them are not used there.
- **Refraction and depth.** What is under the water is the picture of the opaque scene, shifted by the waves in proportion to how much water there
is. The depth is **measured**: before the water is drawn the frame takes a copy of how far each pixel of the scene is from the eye, so the water at
a pixel is the difference between that and the water's own distance. The light is absorbed along that column, red first (`u_absorption`,
@@ -222,7 +264,13 @@ mesh's uv is its local x and z) for the body's own space.
- **Reflection.** The sky, the lights and the environment reflect off it with a Fresnel term (water is 1.333), so it is clear looking down and
mirror-like at a grazing angle. Add Screen Space Reflections to the volume for reflections of the scene itself.
- **Foam.** Where the column is shallower than `u_foamWidth` (the shore, a rock, a pier's legs) and on the crests of the waves (`u_foamCrest`),
- broken up by moving noise.
+ broken up by moving noise. On a zone's surface the baked shore foams too, within `u_foamWidth` of the shore or of shallow water, so the shore foams where the
+ depth cannot be measured.
+- **Current.** `u_flowCycle` is how long, in seconds, each of the two copies of the surface carried down a current lives before the other takes over.
+- **The zone's numbers.** The zone writes these, and they are not for authoring: `u_zoneOn`, `u_zoneHeights` and `u_zoneField` (the baked field as two textures),
+ `u_zoneOrigin`, `u_zoneSize`, `u_zoneHeight` and `u_zoneRange` (where the region is and what the textures encode over), `u_oceanOn`, `u_oceanLevel` and `u_oceanWaves`
+ (the ocean past the region), `u_cellSize` (the finest ring's cell, for the waves a coarse ring fades), `u_geoWaves` (0 for the lite water), and the ripple and
+ quality ones (`u_rippleOn`, `u_rippleMap`, `u_rippleOrigin`, `u_rippleSize`, `u_rippleTexel`, `u_rippleRange`, `u_waveCount`, `u_mirror`, `u_causticOn`).
## Limits
@@ -230,19 +278,22 @@ What is not there yet, so nobody is surprised:
- It needs the same engine-copied scene as glass (a post-process chain is running) and a device whose render targets can hold floats for the depth.
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.
+ the colour does not change with depth and only the zone's baked shore foams.
- Blended surfaces (a pane, a particle, a leaf card) are ordered against water and glass by the pixel: when a frame has both, it is drawn in layers (the opaque scene, the blended draws
over it for the picture the water refracts, the opaque scene put back and the water drawn, then the blended draws again depth-tested against the water). A blended thing under the surface is
seen through it, one in front lies on it, and where there is no water it is blended once. It costs two more full-screen copies of the scene and a second pass over the blended draws, only in frames
that have both. A blended draw with no depth test, or one that crosses the surface, is drawn whole on both sides of it, and one in front of the water is seen through it a second time, faintly,
as the picture the water refracts holds it.
-- A river does not carve the ground, rapids and falls are not foamed by how fast or steep the water runs, and two bodies do not blend where they meet.
- 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.
+- Water is horizontal: a body may be turned about its up, not tilted, and the surface is one height at each place, so there is no water over water.
+- One zone is used, the first `WaterZone` found, with one material for all of its water, and one ocean, the first found. Water outside the zone's region is not drawn, except the ocean.
+ A shore or a river is traced at the zone's resolution: a river a texel or two wide, or an outline's detail finer than that, is lost, and a large region wants a high `resolution`.
+- The surface reaches `cells * cellSize * 2^(rings - 1) / 2` from the camera; with a `WaterZone` of your own, make that cover what should be seen (a zone you did not author grows its cells to do it).
+- A river does not carve the ground, and rapids and falls are not foamed by how fast or steep the water runs. 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.
- Things float (see [Floating](#floating)) and make a wake (see [Ripples](#ripples)); nothing swims yet.
- Caustics and shafts follow the first directional light only, from a pattern and not a simulation: the web does not respond to the actual shape of the waves. From above the caustics
take what is under the water to face up (the picture holds no normals there), so a wall under the surface is lit as a floor would be.
- The mirror from below is screen-space: it shows only what the frame has on screen, and a ray that leaves the picture or meets nothing finds the water's own colour.
-- The body of water a camera is under is the first the surface query finds at the camera's place: a camera under two overlapping bodies takes the numbers of the first.
-- Ripples only bend the shading and carry foam: they do not lift the geometry, they are one window of a body following the camera (a body far from every camera keeps none), and a
- body keeps one window, so two cameras in a split screen share the first's. Foam that a ripple leaves is not carried by a river's current.
+- Ripples only bend the shading and carry foam: they do not lift the geometry, and they are one window following the camera, so water far from the camera keeps none and two cameras
+ in a split screen share the first's. Foam that a ripple leaves is not carried by a river's current, and the waves the geometry is lifted by are not carried by it either (only the shading's).
- The waves are the four peaked sines, not a spectrum, and they lift the surface without pushing it sideways.
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
index 1ed518f5d..4fb57f4cb 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx
@@ -43,7 +43,7 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一
## 水
-**Water** 着色器(`builtin:water`)画一片水体:按实测水深折射,以及反射和泡沫。`WaterBody` 组件用它构建海洋或湖泊,用波浪抬起几何体,并让代码能查询水面。全部内容在[水](/docs/zh-cn/graphics/water/)一章。
+**Water** 着色器(`builtin:water`)画一片水体:按实测水深折射,以及反射和泡沫。`WaterBody` 组件说明海洋、湖泊或河流在哪里,`WaterZone` 把它们烘成一个用它画出的水面,用波浪抬起几何体,并让代码能查询水面。全部内容在[水](/docs/zh-cn/graphics/water/)一章。
## 皮肤与头发
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 5add19652..c7a5b5905 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx
@@ -1,55 +1,81 @@
---
title: 水
-description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的波浪抬起几何体,倾斜时跟随自己的上方向,以及画出它的 Water 着色器。
+description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一个 WaterZone 把它们烘成一张场,并据此画出一个水面,水面由 CPU 能读回的波浪抬起,以及画出它的 Water 着色器。
---
-水有两半。**Water 着色器**(`builtin:water`)是外观:折射、水深、反射、泡沫。**`WaterBody` 组件**是水体本身:它构建几何体,用波浪抬起它,并让代码能查询它的表面,所以脚本读到的就是画出来的。本章两者都讲,也讲还没有的部分。
+水有三部分。**Water 着色器**(`builtin:water`)是外观:折射、水深、反射、泡沫。**`WaterBody`** 说明哪里有什么水:海洋、湖泊、河流。**`WaterZone`** 把它区域内的所有水体烘成一张场,据此画出一个由波浪抬起的水面,并让代码能查询这个水面,所以脚本读到的就是画出来的。本章三者都讲,也讲还没有的部分。
水是一个可选模块:只有场景里有 `WaterBody`(或脚本导入了 `esengine/water`)时,包才会带上它,所以 2D 游戏不带任何水的代码。
## 组件
-给某个实体加一个 `WaterBody`。实体决定水的位置和倾斜;它的子实体是网格,在场景运行时生成,形状一变就重建。
+给某个实体加一个 `WaterBody`。水体不会单独画出来:它是水体区域([水体区域](#水体区域))的输入,区域把它和其他所有水体一起烘成一个水面。实体决定水体的位置;它可以绕自己的上方向旋转,但不能倾斜。
| 字段 | 作用 |
|---|---|
-| `form` | **海洋**:没有边,跟随相机。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形,或 `boundary` 给出的轮廓。**河流**:沿同一实体上的 `Spline`。 |
-| `flowSpeed` | 河流的流速,世界单位每秒,指河面最宽处的流速。 |
+| `form` | **海洋**:没有边,在地面低于实体高度的地方处处都在这个高度,并一直延伸到区域之外。**湖泊**:以实体为中心、`sizeX` × `sizeZ` 的矩形,或 `boundary` 给出的轮廓,在实体的高度上。**河流**:沿同一实体上的 `Spline`。 |
+| `sizeX`、`sizeZ` | 湖泊没有自己的轮廓时的尺寸。 |
| `boundary` | 湖泊的轮廓:它自己的 xz 平面上围一圈的三个或更多点。留空就是矩形。 |
-| `shoreWidth` | 从岸边往里多远、水多深,波浪才长到完整高度。0 表示波浪一直完整到岸边。 |
-| `material` | 使用 Water 着色器的材质。留空用内置的水。 |
-| `cellSize` | 最细一圈几何体的格子大小。 |
-| `cells`、`rings` | 海洋的圈:每圈一边多少格,以及有几圈。 |
-| `waveHeight`、`waveLength`、`waveSpeed`、`waveDirection` | 波浪(见下)。 |
+| `shoreWidth` | 从岸边往里多远、水多深,波浪才长到完整高度,对所有形态都适用。0 表示波浪一直完整到岸边。 |
+| `flowSpeed` | 河流的流速,世界单位每秒,指河面最宽处的流速。 |
+| `waveHeight` | 最高那道波的高度,世界单位。波浪的波长、速度和方向属于区域,所有水体共用。 |
+
+移动水体、改它的字段、轮廓或样条,或者改它下面的地形,都会让区域重新烘焙,所以水立刻跟着变。
+
+## 水体区域
+
+`WaterZone` 说明水画在哪里、画得多细,以及所有水体共用什么。把它放在一个带 `Transform` 的实体上:它的区域是 `sizeX` × `sizeZ`,以实体为中心(只看实体的 x 和 z)。
+
+| 字段 | 作用 |
+|---|---|
+| `sizeX`、`sizeZ` | 烘焙的区域。区域外的水不画;海洋会延伸到区域之外。 |
+| `resolution` | 区域较长一边上的纹素数:岸线和河流描得有多细。 |
+| `material` | 整个水面使用的 Water 着色器材质。留空用内置的水。 |
+| `waveLength`、`waveSpeed`、`waveDirection` | 所有水体共用的波浪([波浪](#波浪))。 |
+| `cellSize`、`cells`、`rings` | 水面的网格:最细一圈的格子大小、每圈一边多少格,以及有几圈([几何体](#几何体))。 |
+| `ripples`、`rippleSize`、`rippleSpeed`、`rippleDamping`、`foamFade` | 区域保留的涟漪([涟漪](#涟漪))。 |
+
+区域把它范围内的所有水体烘成一张网格,每个纹素记着那里的水是什么样:
+
+- 水面的**高度**:湖的水位、河流曲线在最近处的高度、海的水位;
+- 到最近岸边的**有符号距离**,在水上为正:水面在哪里被裁掉、在哪里起泡沫;
+- 那里的**波浪**有多高:水体的 `waveHeight`,向岸边、随水变浅而变平静(以及保留下来的份额,它也让着色变平静);
+- **水流**(河流的),以及水在地面之上的**深度**。
+
+两个水体相接处,每个纹素按自己在各水体内部有多深来加权它们各自给出的值,过渡宽度是一个半纹素,所以数值从一个平滑过渡到另一个:河流流进湖里的地方就在湖的水位上,它的水流消失在静水里,河岸接上湖岸,没有接缝。湖泊和河流优先,海洋取它们剩下的,所以海边的湖归湖。没有任何水体占据的纹素,保留离它最近的水的高度,这样被岸线裁掉的水面边缘不会被拉低到零。
-水体每帧把自己的波浪、格子大小和空间位置写进自己的那份材质副本,所以改字段水立刻就变,几个水体也可以共用同一个材质资源。
+没有 `WaterZone` 的场景,会得到一个覆盖所有湖泊和河流(外加它们岸线的余量)、使用组件默认值的区域,每纹素是最细格子的一半(较长一边 32 到 1024 个纹素);它的格子会变大,让相机在区域里任何位置时水面都能覆盖整个区域。只有海洋的场景不需要区域:整个水面就是海洋。只使用一个区域:找到的第一个 `WaterZone`。
+
+烘焙在 CPU 上进行,不需要渲染器,所以不画任何东西的服务器或测试也能查询水面在哪里。水体、区域或地形一变,就整张重烘,代价是纹素数乘以水体数。
## 波浪
-四道波峰比波谷更尖的正弦波(`exp(sin(theta) - 1)`),相差几个方向,各自的波长、高度和速度是组件上那四个数的份额。它们会**移动几何体**:着色器按波高抬起每个顶点,片元按同一个公式逐像素取斜率,所以被光照的表面就是画出来的表面,和天空交界的轮廓也随波浪起伏。
+四道波峰比波谷更尖的正弦波(`exp(sin(theta) - 1)`),相差几个方向,各自的波长、高度和速度是区域的 `waveLength`、`waveSpeed`、`waveDirection` 的份额。所有水体共用它们;它们在某处有多高,由场里那一处决定:所在水体的 `waveHeight`,乘以岸线留下的份额,再乘以天气的份额(驱动风的 `Weather` 会缩放所有波浪)。它们会**移动几何体**:着色器按波高抬起每个顶点,片元按同一个公式逐像素取斜率,所以被光照的表面就是画出来的表面,和天空交界的轮廓也随波浪起伏。
-波浪在水体自己的空间里度量,沿着它的表面和它自己的上方向,所以倾斜的水体就是倾斜的水。参数以世界单位计:以米为单位的场景用默认值,以厘米为单位的要把长度相应缩放。
+波浪在世界的 xz 平面上度量,把水面竖直向上抬起。参数以世界单位计:以米为单位的场景用默认值,以厘米为单位的要把长度相应缩放。
## 几何体
-**湖泊**是 `cellSize` 大小格子的网格。**海洋**是一圈圈格子数相同的网格,每圈的格子是里面那圈的两倍,中间留出里面那圈的洞,所以它能伸得很远,又把三角形花在近处。它跟着相机、落在所有圈都对齐的格点上,材质的原点同步移动,所以网格在波浪下面移动,而波浪留在世界里不动。
+整个水面是一个网格:一圈圈格子数相同的网格(每边 `cells` 格),最细一圈是 `cellSize` 的格子,每圈的格子是里面那圈的两倍,中间留出里面那圈的洞,所以它从中心伸出 `cells * cellSize * 2^(rings - 1) / 2` 远,又把三角形花在近处。它跟着相机、落在所有圈都对齐的格点上,材质的原点同步移动,所以网格在水下面移动,而水留在世界里不动。它的顶点钩子在每个顶点读区域的场(高度逐纹素读取,先解码再混合),把顶点抬到那里的水面高度再加上波浪;场说那里没有水的像素会被裁掉。
粗的一圈画不出短的波:一个波长不到三格就会闪烁,所以它的顶点会淡掉比自己六格还短的波(着色仍然逐像素显示它们)。两圈相接处,粗的一圈沿边的顶点少一半,表面可能在顶点之间分开,分开多少取决于波浪在它们之间做了什么;让 `waveLength` 至少是看得到的最粗一圈的六格,接缝就看不出来。
## 湖泊与岸线
-湖泊按它的轮廓裁出形状,波浪知道岸边在哪儿、水有多深。水体在轮廓的包围盒上烘一张小场:到岸边的有符号距离,以及水在它下面的地面之上有多深。从这两个量得出一个点保留多少波浪(在岸边或水很浅处一点不留,从 `shoreWidth` 往里全留),写进网格的顶点,所以几何体向岸边变平静;也写进一张纹理,所以像素也是如此,边缘按轮廓来裁(而不是按网格的格子),岸边还会起泡沫。
+湖泊是位于实体高度上的轮廓。区域取到轮廓的有符号距离,场景里有 `Terrain` 时还取水在地形之上的深度,由这两个量得出一个点保留多少波浪(在岸边或水很浅处一点不留,从 `shoreWidth` 往里全留)。水面按轮廓裁出(按区域的分辨率描出,而不是按网格的格子),几何体和着色都向岸边变平静,岸边还会起泡沫。
+
+水填满低处,在山丘与它相交的地方被山丘截断(深度测试做到这一点),波浪随变浅而消失。没有地形时,湖要多深有多深。轮廓不应自相交。
-场景里有 `Terrain` 且湖面水平时,它下面的地面就是地形:水填满低处,在山丘与它相交的地方被山丘截断(深度测试做到这一点),波浪随变浅而消失。地形一变或湖面一动,这张场就会重建;倾斜的湖,或没有地形的湖,要多深有多深。轮廓不应自相交。
+海洋也同样从地形取岸线:在区域内,地面高出海平面的地方被裁掉,波浪在 `shoreWidth` 的水深内变平静。在区域外,海洋处处在它的水位上,波浪完整。
## 河流
-河流是沿着它自己实体上的 `Spline`([样条](#样条))铺开的一条带子:沿曲线每隔 `cellSize` 一排横跨水面的顶点,宽度取曲线在那里的宽度,高度取曲线在它下面的高度,所以河流是顺着坡往下流的。在同一个实体上放一个 `Spline` 和一个 `form` 为 River 的 `WaterBody`,场景运行时河流就建出来了。
+河流沿着它自己实体上的 `Spline`([样条](#样条)):宽度取曲线在那里的宽度,高度取曲线在最近处的高度,所以河流是顺着坡往下流的。在同一个实体上放一个 `Spline` 和一个 `form` 为 River 的 `WaterBody`,区域就会烘焙它。
-- **水流。** `flowSpeed` 是河面最宽处的流速;窄的河段更快、宽的河段更慢,范围在它的四分之一到两倍之间,和同样的水流过不同宽度时的情形一致。方向就是曲线的方向。
+- **水流。** `flowSpeed` 是河面最宽处的流速;窄的河段更快、宽的河段更慢,范围在它的四分之一到两倍之间,和同样的水流过不同宽度时的情形一致。方向就是曲线的方向。它从河流起点起在一个河宽内渐强,流入别处时在一个河宽内渐弱,所以河口是静水。
- **表面随水流动。** 着色器把波浪和涟漪顺流带走:表面的两份拷贝每次沿水流前进一个周期,一份淡入的同时另一份淡出,所以其中一份被放回起点的那一刻被另一份遮住,河道拐弯处表面也不会被拉长。
-- **几何体是平的。** 河流的几何体不被波浪抬起(表面画成平的,只在着色里流动),所以河流没有可读回的波浪:`Waters.sample` 给出它的曲线高度、向上的法线,以及 `flow` 里的水流(世界单位每秒,沿河道方向;别处为零)。
-- **河岸。** 边缘就是这条带子自己的边,和几何体一样清晰。它和地面相接处的泡沫来自场景深度,和任何岸边一样。
+- **波浪。** 河流有自己的 `waveHeight`,和其他水体一样在 `shoreWidth` 内向河岸变平静。`Waters.sample` 在 `flow` 里给出水流(世界单位每秒,沿河道方向;别处为零)。
+- **河岸与河口。** 河岸是场里岸线距离过零的地方,按区域的分辨率描出。河流流进湖、海或另一条河的地方,两者在一个半纹素内混合,所以没有接缝,河口没有横跨的岸线,也没有高度台阶。
## 漂浮
@@ -69,13 +95,13 @@ description: 一个 WaterBody 组件,构建海洋或湖泊,用 CPU 能读回的
## 涟漪
-`ripples` 大于 0 时,水体会记住扰动它的东西。水保存自己表面的一个方形窗口(边长 `rippleSize` 世界单位,沿边 `ripples` 个格子),作为一张高度网格,用波动方程推进:每个格子被拉向它的邻居,并带着它原有的速度,所以放进去的一个凸起会以 `rippleSpeed` 的速度扩散成一圈圈环,每秒损失 `rippleDamping` 的高度,最后消失。网格旁边还保存着**泡沫**:扰动在哪里发生就往哪里加泡沫,泡沫按每秒 `foamFade` 消退,所以一次水花留下的白水会逗留、变薄,而不是随着环一起突然消失。
+`ripples` 大于 0 时,区域会记住扰动水的东西。它保存水面的一个方形窗口(边长 `rippleSize` 世界单位,沿边 `ripples` 个格子),作为一张高度网格,用波动方程推进:每个格子被拉向它的邻居,并带着它原有的速度,所以放进去的一个凸起会以 `rippleSpeed` 的速度扩散成一圈圈环,每秒损失 `rippleDamping` 的高度,最后消失。网格旁边还保存着**泡沫**:扰动在哪里发生就往哪里加泡沫,泡沫按每秒 `foamFade` 消退,所以一次水花留下的白水会逗留、变薄,而不是随着环一起突然消失。
-- **谁来扰动。** 脚本调用 `Waters.disturb(x, y, z, radius, strength)`(这个点交给容纳它的水体;`strength` 是以世界单位计的高度,负数是下凹),`Floating` 物体也会自己做:落进水里、从水里升出或沿水面运动的东西,会按速度推动水(`wake` 是倍数)。
+- **谁来扰动。** 脚本调用 `Waters.disturb(x, y, z, radius, strength)`(`strength` 是以世界单位计的高度,负数是下凹;没有水的地方什么也不做),`Floating` 物体也会自己做:落进水里、从水里升出或沿水面运动的东西,会按速度推动水(`wake` 是倍数)。`Weather` 驱动雨时,雨会以雨滴落在窗口上:一个半格宽的小下凹,每秒的个数由雨量决定。
- **它改变什么。** 着色器把网格当纹理读:涟漪的斜率弯折法线,光照、反射和折射看到的就是这个法线;泡沫让表面变白。几何体不会被它抬起。代码读到的表面包含它们:`Waters.sample` 把涟漪的高度加到表面上,`Waters.rippleAt(x, y, z)` 单独给出它,所以一个漂浮的球会被从它下面经过的环托起。
-- **在哪里。** 窗口以整格为单位跟随活动相机,所以任意大小的湖或海,在看得见的地方都有涟漪,代价只是一张网格。窗口离开的地方被遗忘,新到的地方是静水。到达边缘的波会出去而不是被反射。网格在 CPU 上推进,子步数以保证波一步不跨过超过半个格子为准,并作为 RGBA8 纹理上传(红是高度,绿是泡沫):各后端一致。
+- **在哪里。** 窗口以整格为单位跟随活动相机,所以任意大小的水,在看得见的地方都有涟漪,代价只是一张网格,由所有水体共用。窗口离开的地方被遗忘,新到的地方是静水。到达边缘的波会出去而不是被反射。网格在 CPU 上推进,子步数以保证波一步不跨过超过半个格子为准,并作为 RGBA8 纹理上传(红是高度,绿是泡沫):各后端一致。
-网格最多能容纳 `max(2 * waveHeight, rippleSize / 50)` 的高度:持续的扰动(运动的物体)会在这里饱和,而不会无限堆积。一个格子是 `rippleSize / ripples` 世界单位,所以窄于一两个格子的涟漪画不出来。代价是每个子步 `ripples` 的平方,加每帧一次纹理上传:128 是一万多个格子。
+网格最多能容纳 `max(2 * 最高波浪, rippleSize / 50)` 的高度,最高波浪是场里任何一处波浪能达到的最高高度乘以天气的份额:持续的扰动(运动的物体)会在这里饱和,而不会无限堆积。一个格子是 `rippleSize / ripples` 世界单位,所以窄于一两个格子的涟漪画不出来。代价是每个子步 `ripples` 的平方,加每帧一次纹理上传:128 是一万多个格子。
## 水面之下
@@ -108,14 +134,16 @@ curve.nearest(x, z); // 在 xz 平面上离它最近的地方:s、距离、在
## 在编辑器里
-Details 只显示水体这种形态用得到的字段:湖有尺寸、边界和岸线宽度,海有格子数和环数,河有流速;波浪、涟漪和外观是共有的。湖的 **边界** 一行说明它的轮廓有多少个点(或者说它就是按尺寸画出的矩形),并可以重置回矩形。
+Details 只显示水体这种形态用得到的字段:湖有尺寸和边界,河有流速,所有形态都有岸线宽度和波高。湖的 **边界** 一行说明它的轮廓有多少个点(或者说它就是按尺寸画出的矩形),并可以重置回矩形。`WaterZone` 的字段按组显示:区域、外观、波浪、细节和涟漪。
选中湖或河,它的点就成为视口里的手柄,和多边形碰撞体的顶点一样:
-- **湖。** 轮廓每个点上一个方块,每条边中间一个圆。拖动点,在湖自己的平面上移动它(也就是它的变换所在的平面,所以倾斜的湖是倾斜着编辑的);拖动边上的圆,在那里插入一个点;按住一个点、原地松开,删除它。湖至少保留三个点;没有点时,矩形的四个角就是这些点:拉动其中一个,轮廓就变成它自己的边界。
+- **湖。** 轮廓每个点上一个方块,每条边中间一个圆。拖动点,在湖自己的平面上移动它;拖动边上的圆,在那里插入一个点;按住一个点、原地松开,删除它。湖至少保留三个点;没有点时,矩形的四个角就是这些点:拉动其中一个,轮廓就变成它自己的边界。
- **河。** 在它的 `Spline` 曲线上同样操作,每个点上还有第二个手柄,沿河的横向偏出宽度的一半:拖动它来设置那里的宽度。河至少保留两个点。最后按下的点,会在 Details 的 Spline 下显示它的宽度,可以直接输入。
- 每次手势是一步撤销,点是边拖边写回的,所以水会跟着变。这些手柄是 Gizmo 菜单里的 **Water** 一项。
+区域的范围没有手柄:在 Details 里设置它的尺寸。
+
## 画质档位
水只花项目画质档位允许它花的。五个字段在每个档位的配置里(`project.esproject`,`features.rendering.quality.profiles`),项目可以改变一个档位的含义。**项目设置 → 渲染 → 档位 · 水体**为“正在编辑的档位”编辑它们;画质关闭或项目排除了水体模块时,这一组不显示:
@@ -123,47 +151,52 @@ Details 只显示水体这种形态用得到的字段:湖有尺寸、边界和
| 字段 | 低 | 中 | 高 | 作用 |
|---|---|---|---|---|
| `waterWaves` | 2 | 3 | 4 | 四道波里累加几道:几何、着色以及 `Waters.sample` 的回答都按它。 |
-| `waterRippleCells` | 32 | 64 | 128 | 涟漪网格每边最多多少格;水体自己的 `ripples` 会被限制到它,0 表示不保留。 |
-| `waterDisplacement` | 关 | 开 | 开 | 波浪是否抬起几何体。关就是**轻量水**:平的表面,波浪只在着色里。 |
+| `waterRippleCells` | 32 | 64 | 128 | 涟漪网格每边最多多少格;区域自己的 `ripples` 会被限制到它,0 表示不保留。 |
+| `waterDisplacement` | 关 | 开 | 开 | 波浪是否抬起几何体。关就是**轻量水**:位于水面静止高度的表面,波浪只在着色里。 |
| `waterMirror` | 关 | 开 | 开 | 从下面看水面时,是否映出它下面的世界(屏幕空间步进)。 |
| `waterCaustics` | 关 | 开 | 开 | 阳光的光网是否画在水下的东西上,以及从水下看时的光束。 |
-代码读到的跟画出来的一致:没有位移的档位里,`Waters.sample` 看到的是平面,漂浮物停在静止平面上,波数少对两者同样生效。有画质策略运行时由当前档位决定;没有时,**小游戏**得到低档的水(它能花的最少),其他情况得到全部。轻量水不为波浪做任何顶点计算,着色仍然在动,所以远看仍是水。
+代码读到的跟画出来的一致:没有位移的档位里,`Waters.sample` 看到的是静止的水面,漂浮物停在它上面,波数少对两者同样生效。有画质策略运行时由当前档位决定;没有时,**小游戏**得到低档的水(它能花的最少),其他情况得到全部。轻量水不为波浪做任何顶点计算,着色仍然在动,所以远看仍是水。
## 查询表面
-`Waters.sample(x, y, z)`(资源 `WatersRes`)为包含这个点的水体作答:
+`Waters.sample(x, y, z)`(资源 `WatersRes`)从区域的场作答,和画水面用的是同一组数:
-- `depth`:这个点沿水体上方向高出表面多少(在下面则为负),世界单位;
+- `entity`:那里占水最多的水体(两个水体相接处,是这个点在其内部更深的那个);
+- `depth`:这个点高出表面多少(在下面则为负),世界单位;
- `normal`:表面在那里的法线,世界空间;
- `surface`:这个点正上方或正下方、表面上的世界坐标;
-- `inside`:这个点是否在水体范围之上:在湖泊轮廓之内或河岸之间(海洋没有轮廓,所以总是);
+- `inside`:这个点是否在水上:只要回答不是 null,就总是;
- `flow`:水在那里怎么流动,世界单位每秒(河流的水流;静水为零)。
-它读的是着色器画的同一个公式,取这一帧的时间。水体的位置、旋转和均匀缩放都被考虑进去。`Waters.heightAt(x, z)` 是未倾斜水体的简写。点上方没有水则返回 `null`。
+它读的是着色器画的同一个公式,取这一帧的时间,带上那里波浪的高度和涟漪。`Waters.heightAt(x, z)` 只给出水面的高度。点上方没有水(在所有岸线之外,或在区域之外且没有海洋)则返回 `null`。
-代码读到的是完整的波浪和;海洋远处的粗圈画得少一些(见上),所以在接近地平线处两者可能相差那些短波,它们本来就很小。
+代码读到的是完整的波浪和;远处的粗圈画得少一些(见上),所以在接近地平线处两者可能相差那些短波,它们本来就很小。
## Water 着色器
-`builtin:water` 也可以单独用在任何网格上,这是组件出现之前做一块平水面的方式。`u_waveSpace` 取默认值(0)时,波浪按世界的 xz 平面度量,什么也不抬起,表面被当作是平的。组件把它设为 1(网格的 uv 是它的局部 x 和 z),使用水体自己的空间。
+`builtin:water` 也可以单独用在任何网格上,这是组件出现之前做一块平水面的方式。`u_waveSpace` 取默认值(0)时,波浪按世界的 xz 平面度量,什么也不抬起,表面被当作是平的。区域把它设为 1:网格的 uv 是它的 x 和 z,`u_origin` 是网格跟随相机移到的位置,顶点被抬到区域的水面和它的波浪上。
- **焦散。** `u_causticStrength`(0 关掉它)、`u_causticScale`(一格的大小,世界单位)和 `u_causticSpeed` 决定水下东西上那张光网的样子,从上面看是这样,通过效果从下面看也是这样。
-- **波浪。** `u_waveLength`、`u_waveHeight`、`u_waveSpeed`、`u_waveDirection`;小涟漪(`u_rippleStrength`、`u_rippleLength`)骑在它们上面,并随距离淡出,所以远处的水是平静的而不是闪烁的。
+- **波浪。** `u_waveLength`、`u_waveHeight`、`u_waveSpeed`、`u_waveDirection`;小涟漪(`u_rippleStrength`、`u_rippleLength`)骑在它们上面,并随距离淡出,所以远处的水是平静的而不是闪烁的。在区域的水面上,这四个由区域每帧写入(它自己的波长、速度和方向,高度则是天气的份额,再乘以场里每一处的高度),所以材质里这四个值在那里不起作用。
- **折射与水深。** 水下看到的是不透明场景的画面,被波浪按水量多少偏移。水深是**量出来的**:绘制水之前,帧会拷贝一份场景每个像素离眼睛多远,水在某个像素处的深度就是那个距离与水面自己的距离之差。光沿着这段水柱被吸收——红色最先(`u_absorption`、`u_density`)——水再还给你它自己的颜色,随水变深从 `u_shallowColor` 过渡到 `u_deepColor`。
- **反射。** 天空、灯光和环境按菲涅尔项反射(水是 1.333),所以俯视时清澈、掠射时像镜子。想要场景本身的倒影,在体积里加上屏幕空间反射。
-- **泡沫。** 水柱浅于 `u_foamWidth` 的地方(岸边、礁石、桥墩脚下)和波峰上(`u_foamCrest`)出现泡沫,由流动的噪声打散。
+- **泡沫。** 水柱浅于 `u_foamWidth` 的地方(岸边、礁石、桥墩脚下)和波峰上(`u_foamCrest`)出现泡沫,由流动的噪声打散。在区域的水面上,烘好的岸线也起泡沫,范围是离岸边或浅水 `u_foamWidth` 以内,所以量不出深度的地方岸边也有泡沫。
+- **水流。** `u_flowCycle` 是沿水流带走的两份表面拷贝,每份存活多少秒后由另一份接替。
+- **区域的数值。** 下面这些由区域写入,不是给作者设的:`u_zoneOn`、`u_zoneHeights` 和 `u_zoneField`(烘好的场,两张纹理),`u_zoneOrigin`、`u_zoneSize`、`u_zoneHeight` 和 `u_zoneRange`(区域在哪里、纹理按什么范围编码),`u_oceanOn`、`u_oceanLevel` 和 `u_oceanWaves`(区域之外的海洋),`u_cellSize`(最细一圈的格子,用来算粗圈要淡掉的波),`u_geoWaves`(轻量水为 0),以及涟漪和画质相关的(`u_rippleOn`、`u_rippleMap`、`u_rippleOrigin`、`u_rippleSize`、`u_rippleTexel`、`u_rippleRange`、`u_waveCount`、`u_mirror`、`u_causticOn`)。
## 限制
还没有的部分,免得让人意外:
-- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以没有岸边泡沫,颜色也不随水深变化。
+- 它需要与玻璃相同的、由引擎拷贝的场景(有后处理链在运行),以及渲染目标能存浮点数的设备来存深度。没有链时,水作为半透明表面画在场景上;没有浮点目标时,深度处处是 `u_fallbackDepth`,所以颜色不随水深变化,只有区域烘好的岸线会起泡沫。
- 混合(半透明)表面(玻璃板、粒子、叶片卡片)与水和玻璃是按像素排序的:一帧里两者都有时,场景分层绘制(不透明场景;在其上画混合物体,作为水折射的画面;把不透明场景放回去再画水;最后把混合物体按水的深度再画一遍)。水下的混合物体能透过水看到,水前的躺在水面上,没有水的地方只混合一次。代价是多两次全屏场景拷贝和对混合物体的第二遍绘制,只在同时有两者的帧里发生。没有深度测试的混合物体,或横跨水面的,在水面两侧都整个画出;水前面的物体会因为水折射的画面里包含它,而在水里被淡淡地再看到一次。
-- 河流不会切削地面,急流和瀑布不会按水流的快慢或陡度起泡沫,两个水体相接处也不会融合。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。
+- 水是水平的:水体可以绕自己的上方向旋转,但不能倾斜;水面在每一处只有一个高度,所以没有水上之水。
+- 只使用一个区域,即找到的第一个 `WaterZone`,它的所有水共用一个材质;也只使用一个海洋,即找到的第一个。区域范围之外的水不画,海洋除外。岸线和河流按区域的分辨率描出:只有一两个纹素宽的河,或比这更细的轮廓细节会丢失,大的区域需要高的 `resolution`。
+- 水面从相机伸出 `cells * cellSize * 2^(rings - 1) / 2` 远;自己放了 `WaterZone` 时,要让这个距离覆盖应该看到的范围(不是你放的区域会自己把格子变大来做到这一点)。
+- 河流不会切削地面,急流和瀑布不会按水流的快慢或陡度起泡沫。湖泊的轮廓是平面上的多边形:它不跟随弯曲的岸线,波浪向岸边消失而不是在岸上破碎。
- 东西可以漂浮(见[漂浮](#漂浮)),也会激起尾迹(见[涟漪](#涟漪));还没有东西能游泳。
- 焦散和光束只跟随第一盏平行光,来自一个图案而不是模拟:这张网并不响应波浪的真实形状。从上面看时,焦散把水下的东西当作朝上的面(画面里那里没有法线),所以水面下的一面墙会像地板一样被照亮。
- 从下面看的镜子是屏幕空间的:它只显示帧里在屏幕上的东西,射线离开画面或什么也没碰到时,找到的是水自己的颜色。
-- 相机所在的水体,是水面查询在相机所在处找到的第一个:同时在两个重叠水体之下的相机,用的是第一个的数值。
-- 涟漪只弯折着色并携带泡沫:不会抬起几何体;它们只是水体跟随相机的一个窗口(离所有相机都很远的水体什么也不保留),一个水体只有一个窗口,所以分屏时两个相机共用第一个的。涟漪留下的泡沫不会被河流的水流带走。
+- 涟漪只弯折着色并携带泡沫:不会抬起几何体;它们是跟随相机的一个窗口,所以离相机远的水什么也不保留,分屏时两个相机共用第一个的。涟漪留下的泡沫不会被河流的水流带走,抬起几何体的波浪也不会(只有着色里的会)。
- 波浪是这四道波峰尖的正弦,不是波谱,并且只把表面抬起,不会把它推向一侧。
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 514ec94cc..198515c11 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -91,7 +91,8 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
Foliage: { category: 'graphics', summary: 'Scatters grass or a mesh across an area and over a terrain, drawn a cell at a time, swaying in the wind and thinning out with distance.', doc: 'graphics/foliage', anchor: 'the-component', anchorZh: '组件' },
Floating: { category: 'graphics', summary: 'Holds a RigidBody3D up in water and carries it with the current, by forces at a few points of the body.', doc: 'graphics/water', anchor: 'floating', anchorZh: '漂浮' },
Spline: { category: 'graphics', summary: 'A curve through points, each with a width, read by what follows it (a river\'s WaterBody on the same entity); measured by the distance along it.', doc: 'graphics/water', anchor: 'splines', anchorZh: '样条' },
- WaterBody: { category: 'graphics', summary: 'An ocean or a lake: geometry lifted by waves the code can read back, tilting with the entity, drawn by the Water shader.', doc: 'graphics/water', anchor: 'the-component', anchorZh: '组件' },
+ WaterBody: { category: 'graphics', summary: 'An ocean, a lake or a river: where the water is, how high its waves stand and how it flows; drawn as part of its zone\'s one surface.', doc: 'graphics/water', anchor: 'the-component', anchorZh: '组件' },
+ WaterZone: { category: 'graphics', summary: 'The region the bodies of water are baked over and drawn from as one surface: the waves they share, the material, the mesh and the ripples.', doc: 'graphics/water', anchor: 'the-zone', anchorZh: '水体区域' },
LODGroup: { category: 'graphics', summary: 'Cheaper stand-in meshes for a MeshRenderer, chosen by how much of the screen the object covers.', doc: 'performance/level-of-detail', anchor: 'the-lodgroup-component', anchorZh: 'lodgroup-组件' },
ReflectionProbe: { category: 'graphics', summary: 'A box inside which reflections come from a bake rather than from the sky — the specular half of what a light probe volume answers.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },
PlanarReflection: { category: 'graphics', summary: 'Captures a mirrored view for flat lit surfaces, with layer filtering, capture quality and update controls.', doc: 'graphics/lighting' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 9584278f6..43f0acc3c 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1622,7 +1622,7 @@
"key": "wake",
"type": "number",
"default": "1",
- "doc": "How much of a ripple the body makes in water that keeps ripples (WaterBody Ripples). 0 makes none.",
+ "doc": "How much of a ripple the body makes in water that keeps ripples (WaterZone Ripples). 0 makes none.",
"range": "0–10"
}
],
@@ -7216,19 +7216,13 @@
"key": "form",
"type": "enum",
"default": "Lake",
- "doc": "An ocean is without edge and follows the camera; a lake is a rectangle or an outline of its own; a river follows the Spline on the same entity.",
+ "doc": "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.",
"values": [
"Ocean",
"Lake",
"River"
]
},
- {
- "key": "material",
- "type": "Asset<material>",
- "default": "none",
- "doc": "A material on the Water shader. Empty uses the stock water."
- },
{
"key": "sizeX",
"type": "number",
@@ -7253,50 +7247,70 @@
"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.",
+ "doc": "How far in from the shore, and how deep, the waves take to come to full height. 0 leaves them whole to the edge.",
"range": "≥ 0"
},
{
- "key": "cellSize",
+ "key": "flowSpeed",
"type": "number",
- "default": "1",
- "doc": "The cell size of the finest ring. Waves shorter than six cells are not drawn as geometry there (the shading still shows them).",
- "range": "≥ 0.05"
+ "default": "2",
+ "doc": "A river's current, in world units a second where it is as wide as its widest. A narrower reach runs faster.",
+ "range": "0–5000"
},
{
- "key": "cells",
+ "key": "waveHeight",
"type": "number",
- "default": "64",
- "doc": "Cells along a ring's side (an ocean).",
- "range": "4–256, step 4"
- },
+ "default": "0.3",
+ "doc": "The height of the tallest wave, in world units. Their length, speed and heading are the zone's.",
+ "range": "0–800"
+ }
+ ],
+ "animatable": [
+ "form",
+ "sizeX",
+ "sizeZ",
+ "shoreWidth",
+ "flowSpeed",
+ "waveHeight"
+ ]
+ },
+ {
+ "name": "WaterZone",
+ "source": "ts",
+ "fields": [
{
- "key": "rings",
+ "key": "sizeX",
"type": "number",
- "default": "5",
- "doc": "Rings of an ocean, each twice as coarse as the one inside it.",
- "range": "1–8, step 1"
+ "default": "200",
+ "doc": "The region baked along x, centred on the entity. Water outside it is not drawn; an ocean goes on past it.",
+ "range": "≥ 1"
},
{
- "key": "flowSpeed",
+ "key": "sizeZ",
"type": "number",
- "default": "2",
- "doc": "A river's current, in world units a second where it is as wide as its widest. A narrower reach runs faster.",
- "range": "0–50"
+ "default": "200",
+ "doc": "The region baked along z, centred on the entity.",
+ "range": "≥ 1"
},
{
- "key": "waveHeight",
+ "key": "resolution",
"type": "number",
- "default": "0.3",
- "doc": "The height of the tallest wave, in world units.",
- "range": "0–8"
+ "default": "256",
+ "doc": "Texels along the longer side of the region: how finely shores and rivers are traced.",
+ "range": "32–1024, step 32"
+ },
+ {
+ "key": "material",
+ "type": "Asset<material>",
+ "default": "none",
+ "doc": "A material on the Water shader for the whole surface. Empty uses the stock water."
},
{
"key": "waveLength",
"type": "number",
"default": "14",
- "doc": "The length of the longest wave.",
- "range": "0.5–300"
+ "doc": "The length of the longest wave. Every body shares the waves; each sets how high they stand.",
+ "range": "0.5–3000"
},
{
"key": "waveSpeed",
@@ -7312,11 +7326,32 @@
"doc": "The heading of the waves, in degrees.",
"range": "0–360"
},
+ {
+ "key": "cellSize",
+ "type": "number",
+ "default": "1",
+ "doc": "The cell size of the finest ring of the surface. Waves shorter than six cells are not drawn as geometry there (the shading still shows them).",
+ "range": "≥ 0.05"
+ },
+ {
+ "key": "cells",
+ "type": "number",
+ "default": "64",
+ "doc": "Cells along a ring's side.",
+ "range": "4–256, step 4"
+ },
+ {
+ "key": "rings",
+ "type": "number",
+ "default": "5",
+ "doc": "Rings of the surface, each twice as coarse as the one inside it.",
+ "range": "1–10, step 1"
+ },
{
"key": "ripples",
"type": "number",
"default": "0",
- "doc": "Cells along a side of the grid that keeps what disturbs the water: bodies moving in it, and what a script disturbs. 0 keeps none.",
+ "doc": "Cells along a side of the grid that keeps what disturbs the water: bodies moving in it, rain, and what a script disturbs. 0 keeps none.",
"range": "0–256, step 8"
},
{
@@ -7331,7 +7366,7 @@
"type": "number",
"default": "6",
"doc": "How fast a ripple spreads, in world units a second.",
- "range": "0.1–40"
+ "range": "0.1–4000"
},
{
"key": "rippleDamping",
@@ -7349,19 +7384,16 @@
}
],
"animatable": [
- "form",
- "material",
"sizeX",
"sizeZ",
- "shoreWidth",
- "cellSize",
- "cells",
- "rings",
- "flowSpeed",
- "waveHeight",
+ "resolution",
+ "material",
"waveLength",
"waveSpeed",
"waveDirection",
+ "cellSize",
+ "cells",
+ "rings",
"ripples",
"rippleSize",
"rippleSpeed",
@@ -7424,7 +7456,7 @@
{
"key": "drive",
"type": "number",
- "default": "127"
+ "default": "255"
},
{
"key": "soundSource",
diff --git a/examples/terrain-water/assets/materials/crate.esmaterial b/examples/terrain-water/assets/materials/crate.esmaterial
new file mode 100644
index 000000000..27f34e707
--- /dev/null
+++ b/examples/terrain-water/assets/materials/crate.esmaterial
@@ -0,0 +1,13 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "builtin:model",
+ "blendMode": 0,
+ "depthTest": true,
+ "depthWrite": true,
+ "cull": 0,
+ "properties": {
+ "u_metallic": 0,
+ "u_roughness": 0.8
+ }
+}
diff --git a/examples/terrain-water/assets/materials/crate.esmaterial.meta b/examples/terrain-water/assets/materials/crate.esmaterial.meta
new file mode 100644
index 000000000..8f690e3bf
--- /dev/null
+++ b/examples/terrain-water/assets/materials/crate.esmaterial.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "0e114cf3-dd30-40c9-96a7-348b0984797b",
+ "version": "2.0",
+ "type": "material",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/materials/flowers.esmaterial b/examples/terrain-water/assets/materials/flowers.esmaterial
new file mode 100644
index 000000000..72b9e3a5e
--- /dev/null
+++ b/examples/terrain-water/assets/materials/flowers.esmaterial
@@ -0,0 +1,29 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "builtin:foliage",
+ "blendMode": 0,
+ "depthTest": true,
+ "depthWrite": true,
+ "cull": 0,
+ "properties": {
+ "u_baseColor": {
+ "r": 0.12,
+ "g": 0.22,
+ "b": 0.06,
+ "a": 1
+ },
+ "u_tipColor": {
+ "r": 0.98,
+ "g": 0.84,
+ "b": 0.3,
+ "a": 1
+ },
+ "u_windStrength": 6,
+ "u_windSpeed": 1.2,
+ "u_windDirection": 30,
+ "u_gustScale": 0.0015,
+ "u_flutter": 0.35,
+ "u_translucency": 0.5
+ }
+}
diff --git a/examples/terrain-water/assets/materials/flowers.esmaterial.meta b/examples/terrain-water/assets/materials/flowers.esmaterial.meta
new file mode 100644
index 000000000..e6ad29a08
--- /dev/null
+++ b/examples/terrain-water/assets/materials/flowers.esmaterial.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "a10f1a20-6a3c-4592-a38b-55edfce4428f",
+ "version": "2.0",
+ "type": "material",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/materials/ground.esmaterial b/examples/terrain-water/assets/materials/ground.esmaterial
new file mode 100644
index 000000000..31097f6a7
--- /dev/null
+++ b/examples/terrain-water/assets/materials/ground.esmaterial
@@ -0,0 +1,46 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "builtin:terrain",
+ "blendMode": 0,
+ "depthTest": true,
+ "depthWrite": true,
+ "cull": 0,
+ "properties": {
+ "u_layer0": "assets/textures/grass.png",
+ "u_layer1": "assets/textures/sand.png",
+ "u_layer2": "assets/textures/snow.png",
+ "u_layer3": "assets/textures/rock.png",
+ "u_tint0": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "u_tint1": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "u_tint2": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "u_tint3": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "u_tile0": 900,
+ "u_tile1": 700,
+ "u_tile2": 1100,
+ "u_tile3": 1400,
+ "u_macroVariation": 0.45,
+ "u_sharpness": 2,
+ "u_roughness": 0.95
+ }
+}
diff --git a/examples/terrain-water/assets/materials/ground.esmaterial.meta b/examples/terrain-water/assets/materials/ground.esmaterial.meta
new file mode 100644
index 000000000..c377d2945
--- /dev/null
+++ b/examples/terrain-water/assets/materials/ground.esmaterial.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "00810e87-a1f2-4adb-8450-b86f2c7ccbe6",
+ "version": "2.0",
+ "type": "material",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/materials/meadow.esmaterial b/examples/terrain-water/assets/materials/meadow.esmaterial
new file mode 100644
index 000000000..da9fbf7b9
--- /dev/null
+++ b/examples/terrain-water/assets/materials/meadow.esmaterial
@@ -0,0 +1,29 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "builtin:foliage",
+ "blendMode": 0,
+ "depthTest": true,
+ "depthWrite": true,
+ "cull": 0,
+ "properties": {
+ "u_baseColor": {
+ "r": 0.1,
+ "g": 0.2,
+ "b": 0.05,
+ "a": 1
+ },
+ "u_tipColor": {
+ "r": 0.5,
+ "g": 0.66,
+ "b": 0.22,
+ "a": 1
+ },
+ "u_windStrength": 6,
+ "u_windSpeed": 1.2,
+ "u_windDirection": 30,
+ "u_gustScale": 0.0015,
+ "u_flutter": 0.35,
+ "u_translucency": 0.5
+ }
+}
diff --git a/examples/terrain-water/assets/materials/meadow.esmaterial.meta b/examples/terrain-water/assets/materials/meadow.esmaterial.meta
new file mode 100644
index 000000000..bfd44028c
--- /dev/null
+++ b/examples/terrain-water/assets/materials/meadow.esmaterial.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "e52f2ae5-9650-4508-86e7-343999780d8d",
+ "version": "2.0",
+ "type": "material",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/materials/pine.esmaterial b/examples/terrain-water/assets/materials/pine.esmaterial
new file mode 100644
index 000000000..8bce7df00
--- /dev/null
+++ b/examples/terrain-water/assets/materials/pine.esmaterial
@@ -0,0 +1,32 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "builtin:foliage",
+ "blendMode": 0,
+ "depthTest": true,
+ "depthWrite": true,
+ "cull": 0,
+ "properties": {
+ "u_albedo": "assets/textures/pine.png",
+ "u_useTexture": 1,
+ "u_baseColor": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "u_tipColor": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "u_windStrength": 9,
+ "u_windSpeed": 0.9,
+ "u_windDirection": 30,
+ "u_gustScale": 0.0006,
+ "u_flutter": 0.1,
+ "u_translucency": 0.15,
+ "u_roughness": 0.9
+ }
+}
diff --git a/examples/terrain-water/assets/materials/pine.esmaterial.meta b/examples/terrain-water/assets/materials/pine.esmaterial.meta
new file mode 100644
index 000000000..5f7183769
--- /dev/null
+++ b/examples/terrain-water/assets/materials/pine.esmaterial.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "b863e686-da7e-417d-8a28-57886a1e184f",
+ "version": "2.0",
+ "type": "material",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/materials/reeds.esmaterial b/examples/terrain-water/assets/materials/reeds.esmaterial
new file mode 100644
index 000000000..7bbbd7a02
--- /dev/null
+++ b/examples/terrain-water/assets/materials/reeds.esmaterial
@@ -0,0 +1,29 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "builtin:foliage",
+ "blendMode": 0,
+ "depthTest": true,
+ "depthWrite": true,
+ "cull": 0,
+ "properties": {
+ "u_baseColor": {
+ "r": 0.16,
+ "g": 0.2,
+ "b": 0.08,
+ "a": 1
+ },
+ "u_tipColor": {
+ "r": 0.62,
+ "g": 0.58,
+ "b": 0.32,
+ "a": 1
+ },
+ "u_windStrength": 10,
+ "u_windSpeed": 1.2,
+ "u_windDirection": 30,
+ "u_gustScale": 0.0015,
+ "u_flutter": 0.35,
+ "u_translucency": 0.5
+ }
+}
diff --git a/examples/terrain-water/assets/materials/reeds.esmaterial.meta b/examples/terrain-water/assets/materials/reeds.esmaterial.meta
new file mode 100644
index 000000000..69c33bf19
--- /dev/null
+++ b/examples/terrain-water/assets/materials/reeds.esmaterial.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "bc35dbd2-86e6-4fff-b633-10e9fad136b5",
+ "version": "2.0",
+ "type": "material",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/materials/water.esmaterial b/examples/terrain-water/assets/materials/water.esmaterial
new file mode 100644
index 000000000..cae6bbd28
--- /dev/null
+++ b/examples/terrain-water/assets/materials/water.esmaterial
@@ -0,0 +1,20 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "builtin:water",
+ "blendMode": 0,
+ "depthTest": true,
+ "depthWrite": true,
+ "cull": 0,
+ "properties": {
+ "u_density": 0.0011,
+ "u_rippleLength": 220,
+ "u_rippleStrength": 0.3,
+ "u_distortionRange": 900,
+ "u_foamWidth": 45,
+ "u_foamCrest": 0.4,
+ "u_fallbackDepth": 400,
+ "u_causticScale": 220,
+ "u_roughness": 0.04
+ }
+}
diff --git a/examples/terrain-water/assets/materials/water.esmaterial.meta b/examples/terrain-water/assets/materials/water.esmaterial.meta
new file mode 100644
index 000000000..95b268891
--- /dev/null
+++ b/examples/terrain-water/assets/materials/water.esmaterial.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "57c304e5-c6ff-4987-b3a1-8c632c9bbc47",
+ "version": "2.0",
+ "type": "material",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/models/pine.esmesh b/examples/terrain-water/assets/models/pine.esmesh
new file mode 100644
index 000000000..3ad9c7c1b
Binary files /dev/null and b/examples/terrain-water/assets/models/pine.esmesh differ
diff --git a/examples/terrain-water/assets/models/pine.esmesh.meta b/examples/terrain-water/assets/models/pine.esmesh.meta
new file mode 100644
index 000000000..183609c94
--- /dev/null
+++ b/examples/terrain-water/assets/models/pine.esmesh.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "85689922-3d9a-4e3e-badd-a82c2ab45ccb",
+ "version": "2.0",
+ "type": "mesh",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/scenes/main.esscene b/examples/terrain-water/assets/scenes/main.esscene
new file mode 100644
index 000000000..007d8279a
--- /dev/null
+++ b/examples/terrain-water/assets/scenes/main.esscene
@@ -0,0 +1,1711 @@
+{
+ "version": 4,
+ "name": "Terrain & Water",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 3400,
+ "y": 3600,
+ "z": 15500
+ },
+ "rotation": {
+ "x": -0.09975356056184054,
+ "y": 0.03978955408239594,
+ "z": 0.003992271861283497,
+ "w": 0.9942082680739206
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 0,
+ "fov": 55,
+ "nearPlane": 10,
+ "farPlane": 120000,
+ "isActive": true,
+ "priority": 0
+ }
+ },
+ {
+ "type": "PostProcessVolume",
+ "data": {
+ "isGlobal": true,
+ "priority": 0,
+ "weight": 1,
+ "effects": [
+ {
+ "type": "skyAtmosphere",
+ "enabled": true,
+ "uniforms": {
+ "u_intensity": 1,
+ "u_haze": 0.9,
+ "u_sunBrightness": 40,
+ "u_clouds": 0.4,
+ "u_cloudShadow": 0.6,
+ "u_unitsPerKm": 100000,
+ "u_windSpeed": 0.03
+ }
+ },
+ {
+ "type": "gtao",
+ "enabled": true,
+ "uniforms": {
+ "u_radius": 300,
+ "u_intensity": 0.8
+ }
+ },
+ {
+ "type": "heightFog",
+ "enabled": true,
+ "colors": {
+ "u_fogColor": {
+ "r": 0.66,
+ "g": 0.76,
+ "b": 0.88,
+ "a": 1
+ },
+ "u_sunColor": {
+ "r": 1,
+ "g": 0.9,
+ "b": 0.7,
+ "a": 1
+ }
+ },
+ "uniforms": {
+ "u_density": 0.000004,
+ "u_heightFalloff": 0.0003,
+ "u_baseHeight": 0,
+ "u_inscatter": 0.5,
+ "u_skyFog": 0.4
+ }
+ },
+ {
+ "type": "autoExposure",
+ "enabled": true,
+ "uniforms": {
+ "u_bias": 0,
+ "u_minEV": -2,
+ "u_maxEV": 2
+ }
+ },
+ {
+ "type": "colorGrade",
+ "enabled": true,
+ "uniforms": {
+ "u_contrast": 1.06,
+ "u_saturation": 1.1
+ }
+ },
+ {
+ "type": "bloom",
+ "enabled": true,
+ "uniforms": {
+ "u_threshold": 1,
+ "u_intensity": 0.3,
+ "u_radius": 1
+ }
+ },
+ {
+ "type": "fxaa",
+ "enabled": true,
+ "uniforms": {
+ "u_intensity": 1
+ }
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Clock",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "TimeOfDay",
+ "data": {
+ "hour": 15.5,
+ "daySeconds": 0,
+ "latitude": 40,
+ "declination": 15,
+ "north": 180,
+ "drive": 31
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Sun",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 1,
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "intensity": 3,
+ "enabled": true,
+ "meshShadows": true,
+ "shadowExtent": 16000,
+ "shadowStrength": 1,
+ "sourceAngle": 0.5
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Sky",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 2,
+ "color": {
+ "r": 0.8,
+ "g": 0.88,
+ "b": 1,
+ "a": 1
+ },
+ "intensity": 0.6,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 4,
+ "name": "Ground",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": -1400,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Terrain",
+ "data": {
+ "sizeX": 28000,
+ "sizeZ": 28000,
+ "height": 7400,
+ "chunks": 16,
+ "chunkCells": 32,
+ "lodLevels": 4,
+ "detail": 3,
+ "heightmap": "assets/textures/height.png",
+ "splatmap": "assets/textures/splat.png",
+ "material": "assets/materials/ground.esmaterial"
+ }
+ }
+ ]
+ },
+ {
+ "id": 5,
+ "name": "Water",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "WaterZone",
+ "data": {
+ "sizeX": 28000,
+ "sizeZ": 28000,
+ "resolution": 1024,
+ "material": "assets/materials/water.esmaterial",
+ "waveLength": 1600,
+ "waveSpeed": 1,
+ "waveDirection": 200,
+ "cellSize": 100,
+ "cells": 64,
+ "rings": 7,
+ "ripples": 128,
+ "rippleSize": 6000,
+ "rippleSpeed": 600,
+ "rippleDamping": 0.8,
+ "foamFade": 0.4
+ }
+ }
+ ]
+ },
+ {
+ "id": 6,
+ "name": "Sea",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "WaterBody",
+ "data": {
+ "form": 0,
+ "waveHeight": 55,
+ "shoreWidth": 400
+ }
+ }
+ ]
+ },
+ {
+ "id": 7,
+ "name": "Lake",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 600,
+ "y": 700,
+ "z": -1200
+ }
+ }
+ },
+ {
+ "type": "WaterBody",
+ "data": {
+ "form": 1,
+ "sizeX": 9600,
+ "sizeZ": 6480,
+ "boundary": [
+ {
+ "x": 3833,
+ "y": 0
+ },
+ {
+ "x": 3690,
+ "y": 328
+ },
+ {
+ "x": 3511,
+ "y": 635
+ },
+ {
+ "x": 3294,
+ "y": 921
+ },
+ {
+ "x": 3035,
+ "y": 1183
+ },
+ {
+ "x": 2747,
+ "y": 1423
+ },
+ {
+ "x": 2438,
+ "y": 1646
+ },
+ {
+ "x": 2098,
+ "y": 1846
+ },
+ {
+ "x": 1730,
+ "y": 2023
+ },
+ {
+ "x": 1339,
+ "y": 2183
+ },
+ {
+ "x": 929,
+ "y": 2340
+ },
+ {
+ "x": 463,
+ "y": 2371
+ },
+ {
+ "x": 0,
+ "y": 2341
+ },
+ {
+ "x": -453,
+ "y": 2321
+ },
+ {
+ "x": -901,
+ "y": 2270
+ },
+ {
+ "x": -1346,
+ "y": 2194
+ },
+ {
+ "x": -1765,
+ "y": 2064
+ },
+ {
+ "x": -2143,
+ "y": 1885
+ },
+ {
+ "x": -2531,
+ "y": 1708
+ },
+ {
+ "x": -2882,
+ "y": 1493
+ },
+ {
+ "x": -3198,
+ "y": 1246
+ },
+ {
+ "x": -3412,
+ "y": 954
+ },
+ {
+ "x": -3515,
+ "y": 636
+ },
+ {
+ "x": -3623,
+ "y": 322
+ },
+ {
+ "x": -3687,
+ "y": 0
+ },
+ {
+ "x": -3698,
+ "y": -329
+ },
+ {
+ "x": -3728,
+ "y": -674
+ },
+ {
+ "x": -3690,
+ "y": -1032
+ },
+ {
+ "x": -3522,
+ "y": -1373
+ },
+ {
+ "x": -3202,
+ "y": -1659
+ },
+ {
+ "x": -2794,
+ "y": -1886
+ },
+ {
+ "x": -2393,
+ "y": -2105
+ },
+ {
+ "x": -1953,
+ "y": -2283
+ },
+ {
+ "x": -1457,
+ "y": -2375
+ },
+ {
+ "x": -962,
+ "y": -2423
+ },
+ {
+ "x": -484,
+ "y": -2483
+ },
+ {
+ "x": 0,
+ "y": -2501
+ },
+ {
+ "x": 486,
+ "y": -2492
+ },
+ {
+ "x": 972,
+ "y": -2450
+ },
+ {
+ "x": 1455,
+ "y": -2371
+ },
+ {
+ "x": 1961,
+ "y": -2292
+ },
+ {
+ "x": 2412,
+ "y": -2122
+ },
+ {
+ "x": 2772,
+ "y": -1871
+ },
+ {
+ "x": 3068,
+ "y": -1589
+ },
+ {
+ "x": 3418,
+ "y": -1332
+ },
+ {
+ "x": 3637,
+ "y": -1017
+ },
+ {
+ "x": 3798,
+ "y": -687
+ },
+ {
+ "x": 3859,
+ "y": -343
+ }
+ ],
+ "shoreWidth": 300,
+ "waveHeight": 15
+ }
+ }
+ ]
+ },
+ {
+ "id": 8,
+ "name": "River In",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Spline",
+ "data": {
+ "points": [
+ {
+ "x": -3800,
+ "y": 2350,
+ "z": -12500,
+ "width": 420
+ },
+ {
+ "x": -2300,
+ "y": 2000,
+ "z": -10300,
+ "width": 500
+ },
+ {
+ "x": -3000,
+ "y": 1550,
+ "z": -8000,
+ "width": 620
+ },
+ {
+ "x": -1500,
+ "y": 1100,
+ "z": -5900,
+ "width": 740
+ },
+ {
+ "x": -300,
+ "y": 760,
+ "z": -4300,
+ "width": 860
+ },
+ {
+ "x": 200,
+ "y": 700,
+ "z": -3200,
+ "width": 960
+ }
+ ],
+ "closed": false
+ }
+ },
+ {
+ "type": "WaterBody",
+ "data": {
+ "form": 2,
+ "flowSpeed": 220,
+ "waveHeight": 6,
+ "shoreWidth": 60
+ }
+ }
+ ]
+ },
+ {
+ "id": 9,
+ "name": "River Out",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Spline",
+ "data": {
+ "points": [
+ {
+ "x": 1400,
+ "y": 700,
+ "z": 1100,
+ "width": 900
+ },
+ {
+ "x": 2100,
+ "y": 600,
+ "z": 2800,
+ "width": 1000
+ },
+ {
+ "x": 1200,
+ "y": 420,
+ "z": 4500,
+ "width": 1150
+ },
+ {
+ "x": 2000,
+ "y": 200,
+ "z": 6300,
+ "width": 1300
+ },
+ {
+ "x": 1800,
+ "y": 30,
+ "z": 7900,
+ "width": 1500
+ },
+ {
+ "x": 1900,
+ "y": -40,
+ "z": 8900,
+ "width": 1700
+ }
+ ],
+ "closed": false
+ }
+ },
+ {
+ "type": "WaterBody",
+ "data": {
+ "form": 2,
+ "flowSpeed": 220,
+ "waveHeight": 6,
+ "shoreWidth": 60
+ }
+ }
+ ]
+ },
+ {
+ "id": 10,
+ "name": "Weather",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {}
+ },
+ {
+ "type": "Weather",
+ "data": {
+ "preset": 0,
+ "target": -1,
+ "progress": 0,
+ "duration": 8,
+ "sequence": "clear,overcast,rain,storm,rain,clear",
+ "hold": 25,
+ "drive": 255
+ }
+ }
+ ]
+ },
+ {
+ "id": 11,
+ "name": "Meadow",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 1000,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Foliage",
+ "data": {
+ "material": "assets/materials/meadow.esmaterial",
+ "sizeX": 18000,
+ "sizeZ": 16000,
+ "cellSize": 500,
+ "seed": 3,
+ "minScale": 0.7,
+ "maxScale": 1.4,
+ "minUp": 0.85,
+ "lodDistance": 2400,
+ "drawDistance": 7000,
+ "count": 1100,
+ "heightMin": 860,
+ "heightMax": 3400,
+ "bladeHeight": 55,
+ "bladeWidth": 6
+ }
+ }
+ ]
+ },
+ {
+ "id": 12,
+ "name": "Flowers",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 1000,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Foliage",
+ "data": {
+ "material": "assets/materials/flowers.esmaterial",
+ "sizeX": 18000,
+ "sizeZ": 16000,
+ "cellSize": 500,
+ "seed": 11,
+ "minScale": 0.7,
+ "maxScale": 1.4,
+ "minUp": 0.85,
+ "lodDistance": 2400,
+ "drawDistance": 7000,
+ "count": 70,
+ "heightMin": 900,
+ "heightMax": 2200,
+ "bladeHeight": 45,
+ "bladeWidth": 9
+ }
+ }
+ ]
+ },
+ {
+ "id": 13,
+ "name": "Reeds",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 1000,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Foliage",
+ "data": {
+ "material": "assets/materials/reeds.esmaterial",
+ "sizeX": 18000,
+ "sizeZ": 16000,
+ "cellSize": 500,
+ "seed": 5,
+ "minScale": 0.7,
+ "maxScale": 1.4,
+ "minUp": 0.75,
+ "lodDistance": 2400,
+ "drawDistance": 7000,
+ "count": 600,
+ "heightMin": 660,
+ "heightMax": 840,
+ "bladeHeight": 150,
+ "bladeWidth": 4
+ }
+ }
+ ]
+ },
+ {
+ "id": 14,
+ "name": "Pines",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": -3000
+ }
+ }
+ },
+ {
+ "type": "Foliage",
+ "data": {
+ "mesh": "assets/models/pine.esmesh",
+ "material": "assets/materials/pine.esmaterial",
+ "sizeX": 28000,
+ "sizeZ": 20000,
+ "cellSize": 1200,
+ "count": 2,
+ "seed": 8,
+ "minScale": 8,
+ "maxScale": 13,
+ "minUp": 0.8,
+ "heightMin": 1600,
+ "heightMax": 3850,
+ "lodDistance": 7000,
+ "drawDistance": 60000,
+ "cardU0": 0.2,
+ "cardV0": 0.22,
+ "cardU1": 0.8,
+ "cardV1": 0.95,
+ "cardTent": 1
+ }
+ }
+ ]
+ },
+ {
+ "id": 15,
+ "name": "Crate 1",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -500,
+ "y": 740,
+ "z": -700
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.7397701334966527,
+ "z": 0,
+ "w": 0.672859680458225
+ },
+ "scale": {
+ "x": 1.2792593247674544,
+ "y": 1.2792593247674544,
+ "z": 1.2792593247674544
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.6561583939371999,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 63.962966238372715,
+ "y": 63.962966238372715,
+ "z": 63.962966238372715
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 63.962966238372715,
+ "wake": 1,
+ "points": [
+ {
+ "x": -51.170372990698176,
+ "y": -31.981483119186358,
+ "z": -51.170372990698176
+ },
+ {
+ "x": 51.170372990698176,
+ "y": -31.981483119186358,
+ "z": -51.170372990698176
+ },
+ {
+ "x": -51.170372990698176,
+ "y": -31.981483119186358,
+ "z": 51.170372990698176
+ },
+ {
+ "x": 51.170372990698176,
+ "y": -31.981483119186358,
+ "z": 51.170372990698176
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 16,
+ "name": "Crate 2",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 1300,
+ "y": 740,
+ "z": -1800
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.4486129726466718,
+ "z": 0,
+ "w": 0.8937261329809689
+ },
+ "scale": {
+ "x": 1.2059741558753825,
+ "y": 1.2059741558753825,
+ "z": 1.2059741558753825
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.684444482294946,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 60.298707793769125,
+ "y": 60.298707793769125,
+ "z": 60.298707793769125
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 60.298707793769125,
+ "wake": 1,
+ "points": [
+ {
+ "x": -48.238966235015305,
+ "y": -30.149353896884563,
+ "z": -48.238966235015305
+ },
+ {
+ "x": 48.238966235015305,
+ "y": -30.149353896884563,
+ "z": -48.238966235015305
+ },
+ {
+ "x": -48.238966235015305,
+ "y": -30.149353896884563,
+ "z": 48.238966235015305
+ },
+ {
+ "x": 48.238966235015305,
+ "y": -30.149353896884563,
+ "z": 48.238966235015305
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 17,
+ "name": "Crate 3",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 1900,
+ "y": 740,
+ "z": -400
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.1248152552362316,
+ "z": 0,
+ "w": 0.9921799998288185
+ },
+ "scale": {
+ "x": 1.4357637664153622,
+ "y": 1.4357637664153622,
+ "z": 1.4357637664153622
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.6465671328004838,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 71.78818832076811,
+ "y": 71.78818832076811,
+ "z": 71.78818832076811
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 71.78818832076811,
+ "wake": 1,
+ "points": [
+ {
+ "x": -57.43055065661449,
+ "y": -35.89409416038406,
+ "z": -57.43055065661449
+ },
+ {
+ "x": 57.43055065661449,
+ "y": -35.89409416038406,
+ "z": -57.43055065661449
+ },
+ {
+ "x": -57.43055065661449,
+ "y": -35.89409416038406,
+ "z": 57.43055065661449
+ },
+ {
+ "x": 57.43055065661449,
+ "y": -35.89409416038406,
+ "z": 57.43055065661449
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 18,
+ "name": "Crate 4",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -1300,
+ "y": 740,
+ "z": -1500
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.9934228784822762,
+ "z": 0,
+ "w": 0.11450320741354239
+ },
+ "scale": {
+ "x": 1.1399706244561754,
+ "y": 1.1399706244561754,
+ "z": 1.1399706244561754
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.6461535709086231,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 56.998531222808765,
+ "y": 56.998531222808765,
+ "z": 56.998531222808765
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 56.998531222808765,
+ "wake": 1,
+ "points": [
+ {
+ "x": -45.598824978247016,
+ "y": -28.499265611404383,
+ "z": -45.598824978247016
+ },
+ {
+ "x": 45.598824978247016,
+ "y": -28.499265611404383,
+ "z": -45.598824978247016
+ },
+ {
+ "x": -45.598824978247016,
+ "y": -28.499265611404383,
+ "z": 45.598824978247016
+ },
+ {
+ "x": 45.598824978247016,
+ "y": -28.499265611404383,
+ "z": 45.598824978247016
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 19,
+ "name": "Crate 5",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -600,
+ "y": 40,
+ "z": 8900
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.7193170160288058,
+ "z": 0,
+ "w": 0.6946819635282139
+ },
+ "scale": {
+ "x": 1.3152566176409033,
+ "y": 1.3152566176409033,
+ "z": 1.3152566176409033
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.6493487923055302,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 65.76283088204517,
+ "y": 65.76283088204517,
+ "z": 65.76283088204517
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 65.76283088204517,
+ "wake": 1,
+ "points": [
+ {
+ "x": -52.61026470563613,
+ "y": -32.88141544102258,
+ "z": -52.61026470563613
+ },
+ {
+ "x": 52.61026470563613,
+ "y": -32.88141544102258,
+ "z": -52.61026470563613
+ },
+ {
+ "x": -52.61026470563613,
+ "y": -32.88141544102258,
+ "z": 52.61026470563613
+ },
+ {
+ "x": 52.61026470563613,
+ "y": -32.88141544102258,
+ "z": 52.61026470563613
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 20,
+ "name": "Crate 6",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 3400,
+ "y": 40,
+ "z": 9200
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.9754032685724614,
+ "z": 0,
+ "w": 0.22042791034294784
+ },
+ "scale": {
+ "x": 1.1052781294112277,
+ "y": 1.1052781294112277,
+ "z": 1.1052781294112277
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.6235033379223904,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 55.26390647056138,
+ "y": 55.26390647056138,
+ "z": 55.26390647056138
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 55.26390647056138,
+ "wake": 1,
+ "points": [
+ {
+ "x": -44.21112517644911,
+ "y": -27.63195323528069,
+ "z": -44.21112517644911
+ },
+ {
+ "x": 44.21112517644911,
+ "y": -27.63195323528069,
+ "z": -44.21112517644911
+ },
+ {
+ "x": -44.21112517644911,
+ "y": -27.63195323528069,
+ "z": 44.21112517644911
+ },
+ {
+ "x": 44.21112517644911,
+ "y": -27.63195323528069,
+ "z": 44.21112517644911
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 21,
+ "name": "Crate 7",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 800,
+ "y": 40,
+ "z": 9800
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.4439473454367952,
+ "z": 0,
+ "w": 0.8960528748235914
+ },
+ "scale": {
+ "x": 1.454046957277238,
+ "y": 1.454046957277238,
+ "z": 1.454046957277238
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.6515100745138502,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 72.7023478638619,
+ "y": 72.7023478638619,
+ "z": 72.7023478638619
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 72.7023478638619,
+ "wake": 1,
+ "points": [
+ {
+ "x": -58.16187829108952,
+ "y": -36.35117393193095,
+ "z": -58.16187829108952
+ },
+ {
+ "x": 58.16187829108952,
+ "y": -36.35117393193095,
+ "z": -58.16187829108952
+ },
+ {
+ "x": -58.16187829108952,
+ "y": -36.35117393193095,
+ "z": 58.16187829108952
+ },
+ {
+ "x": 58.16187829108952,
+ "y": -36.35117393193095,
+ "z": 58.16187829108952
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 22,
+ "name": "Crate 8",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 5200,
+ "y": 40,
+ "z": 9600
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.9840973949857003,
+ "z": 0,
+ "w": 0.17762971931058924
+ },
+ "scale": {
+ "x": 1.455841544167102,
+ "y": 1.455841544167102,
+ "z": 1.455841544167102
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.7065403637724323,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 72.7920772083551,
+ "y": 72.7920772083551,
+ "z": 72.7920772083551
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 72.7920772083551,
+ "wake": 1,
+ "points": [
+ {
+ "x": -58.23366176668408,
+ "y": -36.39603860417755,
+ "z": -58.23366176668408
+ },
+ {
+ "x": 58.23366176668408,
+ "y": -36.39603860417755,
+ "z": -58.23366176668408
+ },
+ {
+ "x": -58.23366176668408,
+ "y": -36.39603860417755,
+ "z": 58.23366176668408
+ },
+ {
+ "x": 58.23366176668408,
+ "y": -36.39603860417755,
+ "z": 58.23366176668408
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {
+ "id": 23,
+ "name": "Crate 9",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 2300,
+ "y": 40,
+ "z": 10400
+ },
+ "rotation": {
+ "x": 0,
+ "y": 0.8673768719354216,
+ "z": 0,
+ "w": 0.49765184821471664
+ },
+ "scale": {
+ "x": 1.1735947644509364,
+ "y": 1.1735947644509364,
+ "z": 1.1735947644509364
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "mesh": "builtin:cube",
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "material": "assets/materials/crate.esmaterial",
+ "color": {
+ "r": 0.643824075079482,
+ "g": 0.42,
+ "b": 0.24,
+ "a": 1
+ }
+ }
+ },
+ {
+ "type": "RigidBody3D",
+ "data": {
+ "bodyType": 2,
+ "linearDamping": 0.05,
+ "angularDamping": 0.3
+ }
+ },
+ {
+ "type": "BoxCollider3D",
+ "data": {
+ "halfExtents": {
+ "x": 58.67973822254682,
+ "y": 58.67973822254682,
+ "z": 58.67973822254682
+ },
+ "friction": 0.5
+ }
+ },
+ {
+ "type": "Floating",
+ "data": {
+ "buoyancy": 2,
+ "drag": 1,
+ "radius": 58.67973822254682,
+ "wake": 1,
+ "points": [
+ {
+ "x": -46.94379057803746,
+ "y": -29.33986911127341,
+ "z": -46.94379057803746
+ },
+ {
+ "x": 46.94379057803746,
+ "y": -29.33986911127341,
+ "z": -46.94379057803746
+ },
+ {
+ "x": -46.94379057803746,
+ "y": -29.33986911127341,
+ "z": 46.94379057803746
+ },
+ {
+ "x": 46.94379057803746,
+ "y": -29.33986911127341,
+ "z": 46.94379057803746
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/examples/terrain-water/assets/scenes/main.esscene.meta b/examples/terrain-water/assets/scenes/main.esscene.meta
new file mode 100644
index 000000000..4979bd9e3
--- /dev/null
+++ b/examples/terrain-water/assets/scenes/main.esscene.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "9140a7e3-0215-4b8a-8950-07b5d9280df5",
+ "version": "2.0",
+ "type": "scene",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/textures/grass.png b/examples/terrain-water/assets/textures/grass.png
new file mode 100644
index 000000000..f50d3f784
Binary files /dev/null and b/examples/terrain-water/assets/textures/grass.png differ
diff --git a/examples/terrain-water/assets/textures/grass.png.meta b/examples/terrain-water/assets/textures/grass.png.meta
new file mode 100644
index 000000000..aa9a63149
--- /dev/null
+++ b/examples/terrain-water/assets/textures/grass.png.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "8e58cf02-51eb-4ba0-83e7-6e12e63c515e",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {
+ "wrapMode": "repeat"
+ }
+}
diff --git a/examples/terrain-water/assets/textures/height.png b/examples/terrain-water/assets/textures/height.png
new file mode 100644
index 000000000..ae1935448
Binary files /dev/null and b/examples/terrain-water/assets/textures/height.png differ
diff --git a/examples/terrain-water/assets/textures/height.png.meta b/examples/terrain-water/assets/textures/height.png.meta
new file mode 100644
index 000000000..6c67f44ac
--- /dev/null
+++ b/examples/terrain-water/assets/textures/height.png.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "0d7023d1-e881-442b-ad45-bd79685554c4",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/textures/pine.png b/examples/terrain-water/assets/textures/pine.png
new file mode 100644
index 000000000..90a41eccb
Binary files /dev/null and b/examples/terrain-water/assets/textures/pine.png differ
diff --git a/examples/terrain-water/assets/textures/pine.png.meta b/examples/terrain-water/assets/textures/pine.png.meta
new file mode 100644
index 000000000..02ae3f7b2
--- /dev/null
+++ b/examples/terrain-water/assets/textures/pine.png.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "c78bcfbc-288f-4a3c-8493-4401c5c4ce5d",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {}
+}
diff --git a/examples/terrain-water/assets/textures/rock.png b/examples/terrain-water/assets/textures/rock.png
new file mode 100644
index 000000000..d26246dfd
Binary files /dev/null and b/examples/terrain-water/assets/textures/rock.png differ
diff --git a/examples/terrain-water/assets/textures/rock.png.meta b/examples/terrain-water/assets/textures/rock.png.meta
new file mode 100644
index 000000000..109bccba5
--- /dev/null
+++ b/examples/terrain-water/assets/textures/rock.png.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "e96c955c-22e5-451c-a4ef-e4ca23043c6e",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {
+ "wrapMode": "repeat"
+ }
+}
diff --git a/examples/terrain-water/assets/textures/sand.png b/examples/terrain-water/assets/textures/sand.png
new file mode 100644
index 000000000..fd6838c78
Binary files /dev/null and b/examples/terrain-water/assets/textures/sand.png differ
diff --git a/examples/terrain-water/assets/textures/sand.png.meta b/examples/terrain-water/assets/textures/sand.png.meta
new file mode 100644
index 000000000..ef3fc884d
--- /dev/null
+++ b/examples/terrain-water/assets/textures/sand.png.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "785e28d9-6365-469a-92e2-b9d3b240e60f",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {
+ "wrapMode": "repeat"
+ }
+}
diff --git a/examples/terrain-water/assets/textures/snow.png b/examples/terrain-water/assets/textures/snow.png
new file mode 100644
index 000000000..b992319cf
Binary files /dev/null and b/examples/terrain-water/assets/textures/snow.png differ
diff --git a/examples/terrain-water/assets/textures/snow.png.meta b/examples/terrain-water/assets/textures/snow.png.meta
new file mode 100644
index 000000000..37ad9c345
--- /dev/null
+++ b/examples/terrain-water/assets/textures/snow.png.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "616a6143-9232-4602-9f23-6fd73425ff78",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {
+ "wrapMode": "repeat"
+ }
+}
diff --git a/examples/terrain-water/assets/textures/splat.png b/examples/terrain-water/assets/textures/splat.png
new file mode 100644
index 000000000..8ea9ec35e
Binary files /dev/null and b/examples/terrain-water/assets/textures/splat.png differ
diff --git a/examples/terrain-water/assets/textures/splat.png.meta b/examples/terrain-water/assets/textures/splat.png.meta
new file mode 100644
index 000000000..7cf0a5023
--- /dev/null
+++ b/examples/terrain-water/assets/textures/splat.png.meta
@@ -0,0 +1,6 @@
+{
+ "uuid": "0c55d4d3-c1dd-4088-8a9e-742e9c17d05e",
+ "version": "2.0",
+ "type": "texture",
+ "importer": {}
+}
diff --git a/examples/terrain-water/project.esproject b/examples/terrain-water/project.esproject
new file mode 100644
index 000000000..940e62de0
--- /dev/null
+++ b/examples/terrain-water/project.esproject
@@ -0,0 +1,19 @@
+{
+ "formatVersion": "1",
+ "name": "Terrain & Water",
+ "description": "A watershed made from numbers: a river out of snowy hills into a lake, a second river down to a beach, and the sea to the horizon. Waves, shores, floating crates and the view from under the surface.",
+ "tag": "3D",
+ "version": "0.1.0",
+ "defaultScene": "assets/scenes/main.esscene",
+ "designResolution": {
+ "width": 1480,
+ "height": 920
+ },
+ "spineVersion": "none",
+ "features": {
+ "rendering": {
+ "colorSpace": "linear",
+ "outputTransform": "neutral"
+ }
+ }
+}
diff --git a/examples/terrain-water/src/main.ts b/examples/terrain-water/src/main.ts
new file mode 100644
index 000000000..59eae6e0c
--- /dev/null
+++ b/examples/terrain-water/src/main.ts
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// The scene is authored; keys poke at it: W weather, R a shower, Space a wave per crate, C viewpoint, U dive, 1/2/3 quality.
+import { addPlugin, defineSystem, Res, Query, Mut, Input, Time, Transform, Camera, Quality, Weather,
+ WEATHER_CLEAR, WEATHER_MIST, WEATHER_OVERCAST, WEATHER_RAIN, WEATHER_STORM } from 'esengine';
+import { WatersRes, Floating } from 'esengine/water';
+
+type Pose = { position: { x: number; y: number; z: number }; rotation: { x: number; y: number; z: number; w: number } };
+
+/** A camera turned `yaw` radians left of north (-z) and `pitch` up. */
+function pose(x: number, y: number, z: number, yaw: number, pitch: number): Pose {
+ const cy = Math.cos(yaw / 2), sy = Math.sin(yaw / 2), cp = Math.cos(pitch / 2), sp = Math.sin(pitch / 2);
+ return { position: { x, y, z }, rotation: { x: cy * sp, y: sy * cp, z: -sy * sp, w: cy * cp } };
+}
+
+/** The other places to look from; the first viewpoint is the scene's own camera. */
+/** What W steps through. */
+const WEATHERS = [WEATHER_CLEAR, WEATHER_MIST, WEATHER_OVERCAST, WEATHER_RAIN, WEATHER_STORM];
+
+const VIEWS: Pose[] = [
+ pose(5600, 2100, 700, 1.25, -0.2),
+ pose(-700, 3000, -4300, 0.35, -0.16),
+];
+
+addPlugin({
+ name: 'water-showcase',
+ build(app) {
+ let under = false;
+ // Rain falls on the water in front of the shore camera: [x, surface, z] at the middle of where it lands.
+ const rainAt = [2000, 0, 9800];
+ let shore: Pose | null = null;
+ let start: Pose | null = null;
+ let view = 0;
+ let rain = 0;
+ app.addSystem(defineSystem([
+ Res(Input), Res(Time), Res(Quality), Query(Mut(Transform), Camera), Query(Transform, Floating), Query(Mut(Weather)),
+ ], (input, time, quality, cameras, crates, weathers) => {
+ if (input.isKeyPressed('KeyW')) {
+ for (const [, w] of weathers) {
+ // Turn from where it is toward the next one, and stop the cycle so it stays there.
+ const at = w.target >= 0 && w.progress > 0.5 ? w.target : w.preset;
+ const next = WEATHERS[(Math.max(0, WEATHERS.indexOf(at)) + 1) % WEATHERS.length]!;
+ w.preset = at;
+ w.target = next;
+ w.progress = 0;
+ w.sequence = '';
+ }
+ }
+ const waters = app.hasResource(WatersRes) ? app.getResource(WatersRes) : null;
+ if (input.isKeyPressed('KeyR')) rain = 2;
+ if (waters && rain > 0) {
+ rain -= time.delta;
+ for (let k = 0; k < 6; k++) {
+ const x = rainAt[0] + (Math.random() - 0.5) * 5000, z = rainAt[2] + (Math.random() - 0.5) * 4000;
+ waters.disturb(x, rainAt[1], z, 60, -6);
+ }
+ }
+ if (waters && input.isKeyPressed('Space')) {
+ for (const [, t] of crates) waters.disturb(t.position.x, t.position.y, t.position.z, 260, -40);
+ }
+ if (input.isKeyPressed('KeyC') && !under) {
+ for (const [, t] of cameras) {
+ start ??= { position: { ...t.position }, rotation: { ...t.rotation } };
+ view = (view + 1) % (VIEWS.length + 1);
+ const next = view === 0 ? start : VIEWS[view - 1]!;
+ t.position = { ...next.position };
+ t.rotation = { ...next.rotation };
+ }
+ }
+ if (input.isKeyPressed('KeyU')) {
+ for (const [, t] of cameras) {
+ if (!under) {
+ shore = { position: { ...t.position }, rotation: { ...t.rotation } };
+ // Two metres down among the crates off the beach, looking up at the surface and the light through it.
+ t.position = { x: 1800, y: -160, z: 11000 };
+ t.rotation = { x: 0.13, y: 0.04, z: -0.005, w: 0.991 };
+ } else if (shore) {
+ t.position = shore.position;
+ t.rotation = shore.rotation;
+ }
+ }
+ under = !under;
+ }
+ for (const [key, mode] of [['Digit1', 'low'], ['Digit2', 'medium'], ['Digit3', 'high']] as const) {
+ if (input.isKeyPressed(key)) quality?.setMode(mode);
+ }
+ }, { name: 'WaterShowcase' }));
+ },
+});
diff --git a/examples/terrain-water/tools/build.mjs b/examples/terrain-water/tools/build.mjs
new file mode 100644
index 000000000..7aac5b447
--- /dev/null
+++ b/examples/terrain-water/tools/build.mjs
@@ -0,0 +1,530 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file build.mjs — writes the Terrain & Water project's generated assets and scene.
+ *
+ * One watershed made from numbers: a river runs out of snowy hills into a lake in the valley, a second river leaves the lake and
+ * crosses the meadows to a beach, and the sea goes out to the horizon. The ground is cut to the water, so each river runs in its
+ * bed, the lake fills a basin and the beach shelves into the sea. Run it after changing a number:
+ *
+ * node examples/terrain-water/tools/build.mjs
+ *
+ * It needs the SDK built (`node build-tools/cli.js sdk`), for the spline the rivers and their beds are both laid along and for the
+ * mesh format of the pine. The world is in centimetres, the scale 3D physics takes by default: a crate is about 120 units.
+ */
+import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import path from 'node:path';
+import zlib from 'node:zlib';
+import { fileURLToPath } from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = path.resolve(HERE, '..');
+const SDK = new URL('../../../sdk/dist/', import.meta.url);
+const { SplineCurve } = await import(new URL('spline/index.js', SDK).href);
+const { MeshChannel, MeshChannelType, packChannels, encodeMesh } = await import(new URL('index.node.js', SDK).href);
+
+/** The place, in one table, in world units (centimetres). North is -z; the sea is to the south. */
+const WORLD = {
+ size: 28000,
+ /** The ground spans `base` to `base + height`: below the sea's level for the sea floor, up to the snow on the hills. */
+ base: -1400,
+ height: 7400,
+ resolution: 513,
+ sea: 0,
+ coast: 7600,
+ lake: { x: 600, z: -1200, rx: 4000, rz: 2700, level: 700, floor: 180 },
+ /** Out of the hills and into the lake: x, y (its surface), z, width. */
+ inflow: [
+ { x: -3800, y: 2350, z: -12500, width: 420 },
+ { x: -2300, y: 2000, z: -10300, width: 500 },
+ { x: -3000, y: 1550, z: -8000, width: 620 },
+ { x: -1500, y: 1100, z: -5900, width: 740 },
+ { x: -300, y: 760, z: -4300, width: 860 },
+ { x: 200, y: 700, z: -3200, width: 960 },
+ ],
+ /** Out of the lake and down to the sea. */
+ outflow: [
+ { x: 1400, y: 700, z: 1100, width: 900 },
+ { x: 2100, y: 600, z: 2800, width: 1000 },
+ { x: 1200, y: 420, z: 4500, width: 1150 },
+ { x: 2000, y: 200, z: 6300, width: 1300 },
+ { x: 1800, y: 30, z: 7900, width: 1500 },
+ { x: 1900, y: -40, z: 8900, width: 1700 },
+ ],
+ snow: 4000,
+ crates: { lake: [[-500, -700], [1300, -1800], [1900, -400], [-1300, -1500]], sea: [[-600, 8900], [3400, 9200], [800, 9800], [5200, 9600], [2300, 10400]] },
+};
+
+// ── files ──────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+function write(rel, data) {
+ const file = path.join(PROJECT, rel);
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, data);
+ return file;
+}
+
+/** The `.meta` an asset carries once the editor has seen it, kept when it exists so a rebuild does not rename the asset. */
+function meta(rel, type, importer = {}) {
+ if (existsSync(path.join(PROJECT, `${rel}.meta`))) return;
+ write(`${rel}.meta`, `${JSON.stringify({ uuid: randomUUID(), version: '2.0', type, importer }, null, 2)}\n`);
+}
+
+// ── images and noise ───────────────────────────────────────────────────────────────────────────────────────────────────
+
+function png(width, height, pixel) {
+ const raw = Buffer.alloc((width * 4 + 1) * height);
+ for (let y = 0; y < height; y++) {
+ const row = y * (width * 4 + 1);
+ for (let x = 0; x < width; x++) {
+ const p = pixel(x, y);
+ for (let k = 0; k < 4; k++) raw[row + 1 + x * 4 + k] = Math.max(0, Math.min(255, Math.round(p[k])));
+ }
+ }
+ const table = new Int32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c; });
+ const crc = (buf) => { let c = -1; for (const b of buf) c = table[(c ^ b) & 255] ^ (c >>> 8); return (c ^ -1) >>> 0; };
+ const chunk = (type, data) => {
+ const head = Buffer.alloc(8); head.writeUInt32BE(data.length, 0); head.write(type, 4);
+ const tail = Buffer.alloc(4); tail.writeUInt32BE(crc(Buffer.concat([head.subarray(4), data])), 0);
+ return Buffer.concat([head, data, tail]);
+ };
+ const header = Buffer.alloc(13); header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4); header[8] = 8; header[9] = 6;
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', header), chunk('IDAT', zlib.deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]);
+}
+
+const hash = (x, y, s) => {
+ let h = (Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(s, 2147483647)) | 0;
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967295;
+};
+
+/** Value noise that wraps every `period` cells, so a texture tiles without a seam. */
+function tiled(x, y, period, seed) {
+ const ix = Math.floor(x), iy = Math.floor(y);
+ const fx = x - ix, fy = y - iy;
+ const sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy);
+ const at = (i, j) => hash(((i % period) + period) % period, ((j % period) + period) % period, seed);
+ const a = at(ix, iy), b = at(ix + 1, iy), c = at(ix, iy + 1), d = at(ix + 1, iy + 1);
+ return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy;
+}
+
+function fractal(u, v, seed, octaves = 5, base = 4) {
+ let sum = 0, amp = 0.5, norm = 0;
+ for (let o = 0; o < octaves; o++) {
+ const period = base << o;
+ sum += amp * tiled(u * period, v * period, period, seed + o * 17);
+ norm += amp;
+ amp *= 0.5;
+ }
+ return sum / norm;
+}
+
+const smooth = (a, b, x) => { const t = Math.min(Math.max((x - a) / (b - a), 0), 1); return t * t * (3 - 2 * t); };
+const lerp = (a, b, t) => a + (b - a) * t;
+
+function noise(x, y, seed) {
+ const ix = Math.floor(x), iy = Math.floor(y);
+ const fx = x - ix, fy = y - iy;
+ const sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy);
+ const a = hash(ix, iy, seed), b = hash(ix + 1, iy, seed), c = hash(ix, iy + 1, seed), d = hash(ix + 1, iy + 1, seed);
+ return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy;
+}
+
+function fbm(x, y, seed, octaves, ridged = false) {
+ let sum = 0, amp = 0.5, norm = 0;
+ for (let o = 0; o < octaves; o++) {
+ let n = noise(x, y, seed + o * 31);
+ if (ridged) n = 1 - Math.abs(n * 2 - 1);
+ sum += n * amp; norm += amp; amp *= 0.5; x *= 2.07; y *= 2.07;
+ }
+ return sum / norm;
+}
+
+// ── the ground ─────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+const rivers = [new SplineCurve(WORLD.inflow, false), new SplineCurve(WORLD.outflow, false)];
+
+/** The land before the water cut into it: meadows in the valley, hills rising to the north and along both sides, the shore to the south. */
+function naturalHeight(x, z) {
+ const u = x / WORLD.size, v = z / WORLD.size;
+ const meadow = 850 + 300 * fbm(u * 7 + 3, v * 7 + 1, 11, 4);
+ const north = smooth(-3500, -13500, z);
+ const hills = north * (3400 + 2600 * fbm(u * 4 + 9, v * 4 + 2, 23, 5, true));
+ const sides = smooth(6000, 12500, Math.abs(x)) * smooth(9000, 4000, z) * (1200 + 800 * fbm(u * 5 + 1, v * 5 + 7, 37, 4, true));
+ // Toward the sea the meadows fall to a beach and the beach shelves under the water.
+ const warp = (fbm(u * 6 + 5, v * 3, 41, 3) - 0.5) * 1400;
+ const along = z + warp;
+ const coast = lerp(meadow, 140, smooth(WORLD.coast - 2600, WORLD.coast, along));
+ const shelf = lerp(140, WORLD.base + 200, smooth(WORLD.coast, WORLD.coast + 4200, along));
+ const land = along < WORLD.coast ? coast : shelf;
+ return land + hills + sides;
+}
+
+function lakeDistance(x, z) {
+ const warp = (fbm(x / 3000, z / 3000, 51, 3) - 0.5) * 0.28;
+ return Math.hypot((x - WORLD.lake.x) / WORLD.lake.rx, (z - WORLD.lake.z) / WORLD.lake.rz) + warp;
+}
+
+/** Each river as dense samples along it (x, z, its surface, its half width), so a bed is carved from every place on it at once. */
+const riverSamples = rivers.map((curve) => {
+ const out = [];
+ for (let at = 0; at <= curve.length; at += 80) {
+ const p = curve.position(at);
+ out.push([p[0], p[2], p[1], curve.width(at) / 2]);
+ }
+ return out;
+});
+
+/**
+ * The land with a river's bed and banks cut into it. Every piece of the river cuts its own valley (a bed under its surface, sides that
+ * widen the deeper they run into the hill) and the ground keeps the lowest: a minimum of smooth cuts is smooth, where taking the
+ * nearest place on the curve jumped from one leg of a bend to the other and left a cliff between them.
+ */
+function carve(h, natural, samples, x, z) {
+ let low = h;
+ // Between each pair of samples the river is a straight piece, its surface and width eased along it: the distance to the piece, not to
+ // the sample points, so the valley's sides are smooth and not a row of scallops.
+ for (let i = 0; i + 1 < samples.length; i++) {
+ const [ax, az, as, ah] = samples[i], [bx, bz, bs, bh] = samples[i + 1];
+ const ex = bx - ax, ez = bz - az;
+ const t = Math.min(1, Math.max(0, ((x - ax) * ex + (z - az) * ez) / (ex * ex + ez * ez || 1)));
+ const px = ax + ex * t, pz = az + ez * t;
+ const surface = as + (bs - as) * t, half = ah + (bh - ah) * t;
+ const outer = 1.25 + Math.max(0, natural - surface) / 140;
+ const dx = x - px, dz = z - pz;
+ const reach = (outer + 2) * half;
+ if (dx * dx + dz * dz >= reach * reach) continue;
+ const across = Math.sqrt(dx * dx + dz * dz) / half;
+ const bed = surface - 170;
+ const bank = Math.max(natural, surface + 60);
+ const cut = lerp(lerp(bed, bank, smooth(0.55, outer, across)), natural, smooth(outer + 0.2, outer + 2, across));
+ if (cut < low) low = cut;
+ }
+ return low;
+}
+
+/** The land with the lake's basin cut into it, before the rivers: where the lake's own shore is. */
+function basinHeight(x, z) {
+ const floor = WORLD.lake.floor + 140 * fbm(x / 1500, z / 1500, 61, 3);
+ return lerp(floor, naturalHeight(x, z), smooth(0.62, 1.12, lakeDistance(x, z)));
+}
+
+/** The ground as the scene has it: the land, the lake's basin cut into it, and both rivers' beds laid along their splines. */
+function groundHeight(x, z) {
+ let h = basinHeight(x, z);
+ const natural = naturalHeight(x, z);
+ for (const samples of riverSamples) h = carve(h, natural, samples, x, z);
+ return h;
+}
+
+/** The ground at every texel of the maps, computed once: the heightmap and the splatmap's slopes both read it. */
+const grid = (() => {
+ const n = WORLD.resolution;
+ const out = new Float64Array(n * n);
+ for (let py = 0; py < n; py++) for (let px = 0; px < n; px++) {
+ out[py * n + px] = groundHeight((px / (n - 1) - 0.5) * WORLD.size, (py / (n - 1) - 0.5) * WORLD.size);
+ }
+ return out;
+})();
+const gridAt = (px, py) => {
+ const n = WORLD.resolution;
+ return grid[Math.min(n - 1, Math.max(0, py)) * n + Math.min(n - 1, Math.max(0, px))];
+};
+
+/** Sixteen bits across red (high) and green (low), over `base` to `base + height`. */
+function heightmap() {
+ const n = WORLD.resolution;
+ const image = png(n, n, (px, py) => {
+ const value = Math.round(Math.min(1, Math.max(0, (gridAt(px, py) - WORLD.base) / WORLD.height)) * 65535);
+ return [value >> 8, value & 255, 0, 255];
+ });
+ write('assets/textures/height.png', image);
+ meta('assets/textures/height.png', 'texture');
+}
+
+/**
+ * The paint, as a splatmap: red grass, green sand, blue snow, alpha rock. Sand on the beach and the sea floor, round the lake and in
+ * the rivers' beds; snow on the high ground; rock where it is steep; grass everywhere else.
+ */
+function splatmap() {
+ const n = WORLD.resolution;
+ const step = WORLD.size / (n - 1);
+ const image = png(n, n, (px, py) => {
+ const x = (px / (n - 1) - 0.5) * WORLD.size, z = (py / (n - 1) - 0.5) * WORLD.size;
+ const h = gridAt(px, py);
+ const slope = Math.hypot(gridAt(px + 1, py) - gridAt(px - 1, py), gridAt(px, py + 1) - gridAt(px, py - 1)) / (2 * step);
+ const grain = fbm(x / 600, z / 600, 71, 3);
+ const beach = 1 - smooth(180, 380, h - WORLD.sea + grain * 120);
+ const lakeside = 1 - smooth(30, 140, Math.abs(h - WORLD.lake.level - 40) - 40);
+ const banks = Math.max(...rivers.map((curve) => {
+ const near = curve.nearest(x, z);
+ return 1 - smooth(1.1, 2, near.distance / (curve.width(near.s) / 2));
+ }));
+ const sand = Math.max(beach, lakeDistance(x, z) < 1.25 ? lakeside : 0, banks) * (0.8 + 0.2 * grain);
+ const snow = smooth(WORLD.snow - 200, WORLD.snow + 300, h + (grain - 0.5) * 500) * (1 - smooth(0.6, 1.1, slope));
+ const rock = smooth(0.55, 0.95, slope) * (1 - sand);
+ const grass = Math.max(0, 1 - sand - snow - rock);
+ const sum = grass + sand + snow + rock || 1;
+ return [255 * grass / sum, 255 * sand / sum, 255 * snow / sum, 255 * rock / sum];
+ });
+ write('assets/textures/splat.png', image);
+ meta('assets/textures/splat.png', 'texture');
+}
+
+const mix = (a, b, t) => a.map((c, i) => c + (b[i] - c) * t);
+
+function texture(name, seed, shade) {
+ const size = 512;
+ const image = png(size, size, (x, y) => {
+ const u = x / size, v = y / size;
+ const rgb = shade(u, v, (s, o, b) => fractal(u, v, seed + s, o, b));
+ return [rgb[0], rgb[1], rgb[2], 255];
+ });
+ write(`assets/textures/${name}.png`, image);
+ // Tiled by world position across the whole ground: it must repeat, or every texel past the first tile is its edge stretched.
+ meta(`assets/textures/${name}.png`, 'texture', { wrapMode: 'repeat' });
+}
+
+function textures() {
+ texture('grass', 1, (u, v, n) => {
+ const broad = n(0, 4, 3), fine = n(40, 5, 24), blade = n(80, 2, 96);
+ return mix(mix([52, 82, 30], [104, 140, 52], broad), [70, 108, 38], fine * 0.6).map((c) => c * (0.8 + 0.42 * blade));
+ });
+ texture('sand', 2, (u, v, n) => {
+ const broad = n(0, 4, 3), fine = n(30, 5, 32), pebble = n(70, 2, 64);
+ return mix([168, 150, 116], [214, 196, 158], broad).map((c) => c * (0.88 + 0.2 * fine) * (pebble > 0.72 ? 0.84 : 1));
+ });
+ texture('snow', 3, (u, v, n) => mix([222, 228, 238], [250, 252, 255], n(0, 4, 8)));
+ texture('rock', 4, (u, v, n) => {
+ const broad = n(0, 4, 4), ridge = 1 - Math.abs(n(20, 5, 6) * 2 - 1), fine = n(60, 4, 32);
+ return mix([62, 64, 68], [112, 114, 118], broad * 0.7 + ridge * 0.4).map((c) => c * (0.82 + 0.36 * fine));
+ });
+ // The pine's colour: bark at the foot, then needles that darken toward the shade under each tier.
+ const strip = png(8, 128, (x, y) => {
+ const v = 1 - y / 127;
+ if (v < 0.2) return mix([70, 50, 34], [96, 70, 48], hash(x, y, 7)).concat(255);
+ const needles = 0.8 + 0.4 * hash(x, y, 9);
+ return mix([22, 52, 30], [58, 104, 52], (v - 0.2) / 0.8).map((c) => c * needles).concat(255);
+ });
+ write('assets/textures/pine.png', strip);
+ meta('assets/textures/pine.png', 'texture');
+}
+
+// ── the pine ───────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+/** A pine: a trunk and five tiers of cone, ninety units tall at scale 1, with uv.y running up it (the strip's bark is its first fifth). */
+function pine() {
+ const pos = [], uv = [], nrm = [], idx = [];
+ const vert = (x, y, z, nx, ny, nz, v) => { pos.push(x, y, z); uv.push(0.5, v); nrm.push(nx, ny, nz); return pos.length / 3 - 1; };
+ const SIDES = 10, H = 90;
+ const rings = [[0, 4.2], [20, 3.4], [60, 1.8]].map(([y, r]) => Array.from({ length: SIDES + 1 }, (_, k) => {
+ const a = (k / SIDES) * Math.PI * 2;
+ return vert(Math.sin(a) * r, y, Math.cos(a) * r, Math.sin(a), 0.1, Math.cos(a), (y / H) * 0.19);
+ }));
+ for (let i = 0; i < rings.length - 1; i++) for (let k = 0; k < SIDES; k++) {
+ const a = rings[i][k], b = rings[i][k + 1], c = rings[i + 1][k], d = rings[i + 1][k + 1];
+ idx.push(a, c, b, b, c, d);
+ }
+ for (const [low, high, radius] of [[16, 30, 26], [30, 44, 21], [44, 58, 16.5], [58, 72, 12], [70, 90, 7.5]]) {
+ const slope = radius / (high - low), len = Math.hypot(1, slope);
+ const ring = (y, r, v) => Array.from({ length: SIDES + 1 }, (_, k) => {
+ const a = (k / SIDES) * Math.PI * 2;
+ return vert(Math.sin(a) * r, y, Math.cos(a) * r, Math.sin(a) / len, slope / len, Math.cos(a) / len, v);
+ });
+ const skirt = ring(low, radius, 0.22 + (low / H) * 0.75), tip = ring(high, 0, 0.22 + (high / H) * 0.77);
+ for (let k = 0; k < SIDES; k++) idx.push(skirt[k], tip[k], skirt[k + 1]);
+ const centre = vert(0, low, 0, 0, -1, 0, 0.22);
+ const under = Array.from({ length: SIDES + 1 }, (_, k) => {
+ const a = (k / SIDES) * Math.PI * 2;
+ return vert(Math.sin(a) * radius, low, Math.cos(a) * radius, 0, -1, 0, 0.22);
+ });
+ for (let k = 0; k < SIDES; k++) idx.push(centre, under[k], under[k + 1]);
+ }
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },
+ ]);
+ const count = pos.length / 3;
+ const vertices = new Uint8Array(count * vertexStride);
+ const view = new DataView(vertices.buffer);
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < count; i++) {
+ const at = i * vertexStride;
+ for (let k = 0; k < 3; k++) {
+ view.setFloat32(at + channels[0].offset + k * 4, pos[i * 3 + k], true);
+ view.setFloat32(at + channels[3].offset + k * 4, nrm[i * 3 + k], true);
+ min[k] = Math.min(min[k], pos[i * 3 + k]);
+ max[k] = Math.max(max[k], pos[i * 3 + k]);
+ }
+ view.setFloat32(at + channels[1].offset, uv[i * 2], true);
+ view.setFloat32(at + channels[1].offset + 4, uv[i * 2 + 1], true);
+ view.setUint32(at + channels[2].offset, 0xffffffff, true);
+ }
+ write('assets/models/pine.esmesh', Buffer.from(encodeMesh({ channels, vertexStride, vertexCount: count, vertices, indices: new Uint32Array(idx), aabbMin: min, aabbMax: max })));
+ meta('assets/models/pine.esmesh', 'mesh');
+}
+
+// ── materials ──────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+function material(name, shader, properties) {
+ write(`assets/materials/${name}.esmaterial`, `${JSON.stringify({ version: '1.0', type: 'material', shader, blendMode: 0, depthTest: true, depthWrite: true, cull: 0, properties }, null, 2)}\n`);
+ meta(`assets/materials/${name}.esmaterial`, 'material');
+}
+
+function materials() {
+ const white = { r: 1, g: 1, b: 1, a: 1 };
+ material('ground', 'builtin:terrain', {
+ u_layer0: 'assets/textures/grass.png', u_layer1: 'assets/textures/sand.png', u_layer2: 'assets/textures/snow.png', u_layer3: 'assets/textures/rock.png',
+ u_tint0: white, u_tint1: white, u_tint2: white, u_tint3: white,
+ u_tile0: 900, u_tile1: 700, u_tile2: 1100, u_tile3: 1400, u_macroVariation: 0.45, u_sharpness: 2, u_roughness: 0.95,
+ });
+ // The stock water, scaled from metres to this world's centimetres: the same colours, absorbed over a hundred times the distance.
+ const water = { u_density: 0.0011, u_rippleLength: 220, u_rippleStrength: 0.3, u_distortionRange: 900, u_foamWidth: 45, u_foamCrest: 0.4,
+ u_fallbackDepth: 400, u_causticScale: 220, u_roughness: 0.04 };
+ material('water', 'builtin:water', water);
+ material('crate', 'builtin:model', { u_metallic: 0, u_roughness: 0.8 });
+ const grass = (base, tip, wind) => ({ u_baseColor: base, u_tipColor: tip, u_windStrength: wind, u_windSpeed: 1.2, u_windDirection: 30,
+ u_gustScale: 0.0015, u_flutter: 0.35, u_translucency: 0.5 });
+ material('meadow', 'builtin:foliage', grass({ r: 0.1, g: 0.2, b: 0.05, a: 1 }, { r: 0.5, g: 0.66, b: 0.22, a: 1 }, 6));
+ material('flowers', 'builtin:foliage', grass({ r: 0.12, g: 0.22, b: 0.06, a: 1 }, { r: 0.98, g: 0.84, b: 0.3, a: 1 }, 6));
+ material('reeds', 'builtin:foliage', grass({ r: 0.16, g: 0.2, b: 0.08, a: 1 }, { r: 0.62, g: 0.58, b: 0.32, a: 1 }, 10));
+ material('pine', 'builtin:foliage', {
+ u_albedo: 'assets/textures/pine.png', u_useTexture: 1, u_baseColor: white, u_tipColor: white,
+ u_windStrength: 9, u_windSpeed: 0.9, u_windDirection: 30, u_gustScale: 0.0006, u_flutter: 0.1, u_translucency: 0.15, u_roughness: 0.9,
+ });
+}
+
+// ── the scene ──────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+function quat(yaw, pitch) {
+ const cy = Math.cos(yaw / 2), sy = Math.sin(yaw / 2), cp = Math.cos(pitch / 2), sp = Math.sin(pitch / 2);
+ return { x: cy * sp, y: sy * cp, z: -sy * sp, w: cy * cp };
+}
+
+/**
+ * The lake's outline in its own space: where its basin crosses the water's level, walked round from its middle. The basin's, not the
+ * ground's: the rivers' beds run below the level too, and the engine ends each river at this shore and opens the shore there.
+ */
+function lakeOutline() {
+ const points = [];
+ for (let k = 0; k < 48; k++) {
+ const a = (k / 48) * Math.PI * 2;
+ let lo = 0, hi = 1.15;
+ for (let i = 0; i < 30; i++) {
+ const r = (lo + hi) / 2;
+ const x = WORLD.lake.x + Math.cos(a) * WORLD.lake.rx * r, z = WORLD.lake.z + Math.sin(a) * WORLD.lake.rz * r;
+ if (basinHeight(x, z) < WORLD.lake.level) lo = r; else hi = r;
+ }
+ points.push({ x: Math.round(Math.cos(a) * WORLD.lake.rx * (lo + 0.02)), y: Math.round(Math.sin(a) * WORLD.lake.rz * (lo + 0.02)) });
+ }
+ return points;
+}
+
+function scene() {
+ const white = { r: 1, g: 1, b: 1, a: 1 };
+ const entities = [];
+ const add = (name, components) => entities.push({ id: entities.length, name, parent: null, children: [], visible: true, components });
+ const post = [
+ { type: 'skyAtmosphere', enabled: true, uniforms: { u_intensity: 1, u_haze: 0.9, u_sunBrightness: 40, u_clouds: 0.4, u_cloudShadow: 0.6, u_unitsPerKm: 100000, u_windSpeed: 0.03 } },
+ { type: 'gtao', enabled: true, uniforms: { u_radius: 300, u_intensity: 0.8 } },
+ { type: 'heightFog', enabled: true, colors: { u_fogColor: { r: 0.66, g: 0.76, b: 0.88, a: 1 }, u_sunColor: { r: 1, g: 0.9, b: 0.7, a: 1 } },
+ uniforms: { u_density: 0.000004, u_heightFalloff: 0.0003, u_baseHeight: WORLD.sea, u_inscatter: 0.5, u_skyFog: 0.4 } },
+ { type: 'autoExposure', enabled: true, uniforms: { u_bias: 0, u_minEV: -2, u_maxEV: 2 } },
+ { type: 'colorGrade', enabled: true, uniforms: { u_contrast: 1.06, u_saturation: 1.1 } },
+ { type: 'bloom', enabled: true, uniforms: { u_threshold: 1, u_intensity: 0.3, u_radius: 1 } },
+ { type: 'fxaa', enabled: true, uniforms: { u_intensity: 1 } },
+ ].filter((e) => !(process.env.TW_NOPOST ?? '').split(',').includes(e.type));
+ // Over the sea, looking north: the waves and the crates, the beach, the river mouth, the lake, the river out of the hills, the snow.
+ add('Camera', [
+ { type: 'Transform', data: process.env.TW_TOP ? { position: { x: 1000, y: 30000, z: 1000 }, rotation: { x: -0.7071, y: 0, z: 0, w: 0.7071 } }
+ : { position: { x: 3400, y: 3600, z: 15500 }, rotation: quat(0.08, -0.2) } },
+ { type: 'Camera', data: { projectionType: 0, fov: 55, nearPlane: 10, farPlane: 120000, isActive: true, priority: 0 } },
+ { type: 'PostProcessVolume', data: { isGlobal: true, priority: 0, weight: 1, effects: post } },
+ ]);
+ add('Clock', [{ type: 'Transform', data: {} }, { type: 'TimeOfDay', data: { hour: 15.5, daySeconds: 0, latitude: 40, declination: 15, north: 180, drive: 31 } }]);
+ add('Sun', [{ type: 'Transform', data: {} },
+ { type: 'Light', data: { type: 1, color: white, intensity: 3, enabled: true, meshShadows: true, shadowExtent: 16000, shadowStrength: 1, sourceAngle: 0.5 } }]);
+ add('Sky', [{ type: 'Transform', data: {} }, { type: 'Light', data: { type: 2, color: { r: 0.8, g: 0.88, b: 1, a: 1 }, intensity: 0.6, enabled: true } }]);
+ add('Ground', [
+ { type: 'Transform', data: { position: { x: 0, y: WORLD.base, z: 0 } } },
+ { type: 'Terrain', data: {
+ sizeX: WORLD.size, sizeZ: WORLD.size, height: WORLD.height, chunks: 16, chunkCells: 32, lodLevels: 4, detail: 3,
+ heightmap: 'assets/textures/height.png', splatmap: 'assets/textures/splat.png', material: 'assets/materials/ground.esmaterial' } },
+ ]);
+ // The water: one zone over the whole island, which the sea, the lake and the two rivers are baked into and drawn from as one surface.
+ add('Water', [
+ { type: 'Transform', data: {} },
+ { type: 'WaterZone', data: { sizeX: WORLD.size, sizeZ: WORLD.size, resolution: 1024, material: 'assets/materials/water.esmaterial',
+ waveLength: 1600, waveSpeed: 1, waveDirection: 200, cellSize: 100, cells: 64, rings: 7,
+ ripples: 128, rippleSize: 6000, rippleSpeed: 600, rippleDamping: 0.8, foamFade: 0.4 } },
+ ]);
+ add('Sea', [
+ { type: 'Transform', data: { position: { x: 0, y: WORLD.sea, z: 0 } } },
+ { type: 'WaterBody', data: { form: 0, waveHeight: 55, shoreWidth: 400 } },
+ ]);
+ add('Lake', [
+ { type: 'Transform', data: { position: { x: WORLD.lake.x, y: WORLD.lake.level, z: WORLD.lake.z } } },
+ { type: 'WaterBody', data: { form: 1, sizeX: WORLD.lake.rx * 2.4, sizeZ: WORLD.lake.rz * 2.4, boundary: lakeOutline(), shoreWidth: 300, waveHeight: 15 } },
+ ]);
+ for (const [name, points] of [['River In', WORLD.inflow], ['River Out', WORLD.outflow]]) {
+ add(name, [
+ { type: 'Transform', data: {} },
+ { type: 'Spline', data: { points, closed: false } },
+ { type: 'WaterBody', data: { form: 2, flowSpeed: 220, waveHeight: 6, shoreWidth: 60 } },
+ ]);
+ }
+ // The weather turns by itself through the day's sky; W in the example turns it at once. TW_WEATHER=storm previews one.
+ const presets = ['clear', 'mist', 'overcast', 'rain', 'storm'];
+ add('Weather', [
+ { type: 'Transform', data: {} },
+ { type: 'Weather', data: { preset: Math.max(0, presets.indexOf(process.env.TW_WEATHER ?? 'clear')), target: -1, progress: 0, duration: 8,
+ sequence: process.env.TW_WEATHER ? '' : 'clear,overcast,rain,storm,rain,clear', hold: 25, drive: 255 } },
+ ]);
+ // The plants: a meadow over the valley, flowers scattered in it, reeds where the ground is low by the lake and the rivers.
+ const plants = (name, material, extra) => add(name, [
+ { type: 'Transform', data: { position: { x: 1000, y: 0, z: 0 } } },
+ { type: 'Foliage', data: { material, sizeX: 18000, sizeZ: 16000, cellSize: 500, seed: 3, minScale: 0.7, maxScale: 1.4, minUp: 0.85,
+ lodDistance: 2400, drawDistance: 7000, ...extra } },
+ ]);
+ plants('Meadow', 'assets/materials/meadow.esmaterial', { count: 1100, heightMin: WORLD.lake.level + 160, heightMax: WORLD.snow - 600, bladeHeight: 55, bladeWidth: 6 });
+ plants('Flowers', 'assets/materials/flowers.esmaterial', { count: 70, seed: 11, heightMin: WORLD.lake.level + 200, heightMax: 2200, bladeHeight: 45, bladeWidth: 9 });
+ plants('Reeds', 'assets/materials/reeds.esmaterial', { count: 600, seed: 5, minUp: 0.75, heightMin: WORLD.lake.level - 40, heightMax: WORLD.lake.level + 140,
+ bladeHeight: 150, bladeWidth: 4 });
+ add('Pines', [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: -3000 } } },
+ { type: 'Foliage', data: {
+ mesh: 'assets/models/pine.esmesh', material: 'assets/materials/pine.esmaterial', sizeX: WORLD.size, sizeZ: 20000, cellSize: 1200, count: 2, seed: 8,
+ minScale: 8, maxScale: 13, minUp: 0.8, heightMin: WORLD.lake.level + 900, heightMax: WORLD.snow - 150, lodDistance: 7000, drawDistance: 60000,
+ cardU0: 0.2, cardV0: 0.22, cardU1: 0.8, cardV1: 0.95, cardTent: 1 } },
+ ]);
+ const crates = [...WORLD.crates.lake.map(([x, z]) => [x, z, WORLD.lake.level]), ...WORLD.crates.sea.map(([x, z]) => [x, z, WORLD.sea])];
+ crates.forEach(([x, z, level], i) => {
+ const size = 110 + 40 * hash(i, 3, 5);
+ const half = size / 2;
+ add(`Crate ${i + 1}`, [
+ { type: 'Transform', data: { position: { x, y: level + 40, z }, rotation: quat(hash(i, 7, 9) * Math.PI, 0), scale: { x: size / 100, y: size / 100, z: size / 100 } } },
+ { type: 'MeshRenderer', data: { mesh: 'builtin:cube', lit: true, opaque: true, cullBackfaces: true, material: 'assets/materials/crate.esmaterial',
+ color: { r: 0.62 + 0.1 * hash(i, 1, 2), g: 0.42, b: 0.24, a: 1 } } },
+ { type: 'RigidBody3D', data: { bodyType: 2, linearDamping: 0.05, angularDamping: 0.3 } },
+ { type: 'BoxCollider3D', data: { halfExtents: { x: half, y: half, z: half }, friction: 0.5 } },
+ { type: 'Floating', data: { buoyancy: 2, drag: 1, radius: half, wake: 1,
+ points: [[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([a, b]) => ({ x: a * half * 0.8, y: -half * 0.5, z: b * half * 0.8 })) } },
+ ]);
+ });
+ // For looking at one thing at a time: TW_DROP=Lake,Pines leaves those out.
+ const drop = (process.env.TW_DROP ?? '').split(',');
+ const kept = entities.filter((e) => !drop.includes(e.name)).map((e, id) => ({ ...e, id }));
+ write('assets/scenes/main.esscene', `${JSON.stringify({ version: 4, name: 'Terrain & Water', entities: kept }, null, 1)}\n`);
+ meta('assets/scenes/main.esscene', 'scene');
+}
+
+heightmap();
+splatmap();
+textures();
+pine();
+materials();
+scene();
+console.log('terrain-water: written');
diff --git a/examples/terrain-water/tsconfig.json b/examples/terrain-water/tsconfig.json
new file mode 100644
index 000000000..a83df0e80
--- /dev/null
+++ b/examples/terrain-water/tsconfig.json
@@ -0,0 +1,34 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": false,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "paths": {
+ "esengine": [
+ "./.esengine/sdk/index.d.ts"
+ ],
+ "estella-plugin-*": [
+ "./.esengine/packages/*"
+ ],
+ "esengine/wasm": [
+ "./.esengine/sdk/wasm.d.ts"
+ ],
+ "esengine/water": [
+ "./.esengine/sdk/water/index.d.ts"
+ ]
+ }
+ },
+ "include": [
+ "src/**/*"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
+}
diff --git a/pipeline/src/project/targetSupport.ts b/pipeline/src/project/targetSupport.ts
index 3cffa1403..86cfc2198 100644
--- a/pipeline/src/project/targetSupport.ts
+++ b/pipeline/src/project/targetSupport.ts
@@ -46,7 +46,7 @@ export const SUBSYSTEM_COMPONENTS: Readonly<Record<Subsystem, readonly string[]>
fxAtmosphere: ['Weather', 'TimeOfDay'],
fxLighting: [],
foliage: ['Foliage'],
- water: ['WaterBody', 'Floating'],
+ water: ['WaterBody', 'WaterZone', 'Floating'],
spline: ['Spline'],
// Hair, Skin and Eye are shaders, not components: a character's materials are what name them (see SHADER_SUBSYSTEM).
characterShaders: [],
diff --git a/sdk/etc/foliage.api.md b/sdk/etc/foliage.api.md
index 81581ee45..4c4a28297 100644
--- a/sdk/etc/foliage.api.md
+++ b/sdk/etc/foliage.api.md
@@ -52,6 +52,7 @@ sizeZ: number
## FoliageField — class @experimental
```
+@internal authoredWind_: Map<number, number>
@internal built_: Map<number, BuiltFoliage>
cellCount: number
pending: number
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2eb5c2d7d..1f4b56293 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 · 1749 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1746 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3879,6 +3879,18 @@ tooltip: string | undefined
unit: string | undefined
```
+## FieldSample — interface @experimental
+```
+amp: number
+calm: number
+depth: number
+flowX: number
+flowZ: number
+height: number
+key: number
+shore: number
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -4073,6 +4085,7 @@ sizeZ: number
## FoliageField — class @experimental
```
+@internal authoredWind_: Map<number, number>
@internal built_: Map<number, BuiltFoliage>
cellCount: number
pending: number
@@ -4453,11 +4466,6 @@ 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
@@ -7236,12 +7244,6 @@ 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
@@ -8325,25 +8327,6 @@ 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
@@ -10884,11 +10867,6 @@ SolidColor = 1
Tiled = 4
```
-## UNKNOWN_DEPTH — const @experimental
-```
-1000000000
-```
-
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11243,24 +11221,33 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
boundary: Point2[]
-cellSize: number
-cells: number
flowSpeed: number
-foamFade: number
form: number
-material: number
-rings: number
-rippleDamping: number
-rippleSize: number
-rippleSpeed: number
-ripples: number
shoreWidth: number
sizeX: number
sizeZ: number
-waveDirection: number
waveHeight: number
-waveLength: number
-waveSpeed: number
+```
+
+## WaterField — class @experimental
+```
+amp: Float32Array<ArrayBufferLike>
+at: (x: number, z: number) => FieldSample | null
+calm: Float32Array<ArrayBufferLike>
+depth: Float32Array<ArrayBufferLike>
+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }
+flowX: Float32Array<ArrayBufferLike>
+flowZ: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+height: Float32Array<ArrayBufferLike>
+ocean: ZoneOcean | null
+owner: Int32Array<ArrayBufferLike>
+ranges: () => ZoneRanges
+sample: (x: number, z: number) => FieldSample | null
+shore: Float32Array<ArrayBufferLike>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
+static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
+static prototype: WaterField
```
## WaterForm — const @experimental
@@ -11287,14 +11274,41 @@ normal: [number, number, number]
surface: [number, number, number]
```
+## WaterZone — const @experimental
+```
+ComponentDef<WaterZoneData>
+```
+
+## WaterZoneData — interface @experimental
+```
+cellSize: number
+cells: number
+foamFade: number
+material: number
+resolution: number
+rings: number
+rippleDamping: number
+rippleSize: number
+rippleSpeed: number
+ripples: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveLength: number
+waveSpeed: number
+```
+
## Waters — class @experimental
```
@internal app_: App | null
-@internal built_: Map<number, Built>
+@internal field_: WaterField | null
+@internal instance_: number
+@internal ripples_: RippleField | null
+@internal zone_: WaterZoneData
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
-rippleAt: (x: number, y: number, z: number) => number
+rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
static new (): Waters
static prototype: Waters
@@ -11350,7 +11364,7 @@ target: number
## WeatherDrive — const @experimental
```
-{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly Wind: 128; readonly All: 255; }
```
## WeatherPreset — type @experimental
@@ -11380,7 +11394,9 @@ sound: number
ssr: number
sun: number
sunTint: [number, number, number]
+waves: number
wetness: number
+wind: number
```
## WebAppOptions — interface @experimental
@@ -12056,11 +12072,6 @@ 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
@@ -12086,16 +12097,6 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
-## buildRectMesh — function @experimental
-```
-(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
-```
-
-## buildRiverMesh — function @experimental
-```
-(curve: SplineCurve, step: number, across: number): MeshData
-```
-
## buildText — function @experimental
```
(init?: TextInit): TextData
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 1b18d9235..24589b4bd 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 · 1768 experimental · 3 deprecated
+Symbols: 115 public · 164 beta · 1765 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3887,6 +3887,18 @@ tooltip: string | undefined
unit: string | undefined
```
+## FieldSample — interface @experimental
+```
+amp: number
+calm: number
+depth: number
+flowX: number
+flowZ: number
+height: number
+key: number
+shore: number
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -4081,6 +4093,7 @@ sizeZ: number
## FoliageField — class @experimental
```
+@internal authoredWind_: Map<number, number>
@internal built_: Map<number, BuiltFoliage>
cellCount: number
pending: number
@@ -4461,11 +4474,6 @@ 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
@@ -7449,12 +7457,6 @@ 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
@@ -8538,25 +8540,6 @@ 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
@@ -11097,11 +11080,6 @@ SolidColor = 1
Tiled = 4
```
-## UNKNOWN_DEPTH — const @experimental
-```
-1000000000
-```
-
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11456,24 +11434,33 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
boundary: Point2[]
-cellSize: number
-cells: number
flowSpeed: number
-foamFade: number
form: number
-material: number
-rings: number
-rippleDamping: number
-rippleSize: number
-rippleSpeed: number
-ripples: number
shoreWidth: number
sizeX: number
sizeZ: number
-waveDirection: number
waveHeight: number
-waveLength: number
-waveSpeed: number
+```
+
+## WaterField — class @experimental
+```
+amp: Float32Array<ArrayBufferLike>
+at: (x: number, z: number) => FieldSample | null
+calm: Float32Array<ArrayBufferLike>
+depth: Float32Array<ArrayBufferLike>
+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }
+flowX: Float32Array<ArrayBufferLike>
+flowZ: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+height: Float32Array<ArrayBufferLike>
+ocean: ZoneOcean | null
+owner: Int32Array<ArrayBufferLike>
+ranges: () => ZoneRanges
+sample: (x: number, z: number) => FieldSample | null
+shore: Float32Array<ArrayBufferLike>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
+static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
+static prototype: WaterField
```
## WaterForm — const @experimental
@@ -11500,14 +11487,41 @@ normal: [number, number, number]
surface: [number, number, number]
```
+## WaterZone — const @experimental
+```
+ComponentDef<WaterZoneData>
+```
+
+## WaterZoneData — interface @experimental
+```
+cellSize: number
+cells: number
+foamFade: number
+material: number
+resolution: number
+rings: number
+rippleDamping: number
+rippleSize: number
+rippleSpeed: number
+ripples: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveLength: number
+waveSpeed: number
+```
+
## Waters — class @experimental
```
@internal app_: App | null
-@internal built_: Map<number, Built>
+@internal field_: WaterField | null
+@internal instance_: number
+@internal ripples_: RippleField | null
+@internal zone_: WaterZoneData
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
-rippleAt: (x: number, y: number, z: number) => number
+rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
static new (): Waters
static prototype: Waters
@@ -11563,7 +11577,7 @@ target: number
## WeatherDrive — const @experimental
```
-{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly Wind: 128; readonly All: 255; }
```
## WeatherPreset — type @experimental
@@ -11593,7 +11607,9 @@ sound: number
ssr: number
sun: number
sunTint: [number, number, number]
+waves: number
wetness: number
+wind: number
```
## WebAppOptions — interface @experimental
@@ -12284,11 +12300,6 @@ 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
@@ -12314,16 +12325,6 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
-## buildRectMesh — function @experimental
-```
-(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
-```
-
-## buildRiverMesh — function @experimental
-```
-(curve: SplineCurve, step: number, across: number): MeshData
-```
-
## buildText — function @experimental
```
(init?: TextInit): TextData
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a943763e2..d0c8e9024 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 · 1748 experimental · 3 deprecated
+Symbols: 115 public · 161 beta · 1745 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3874,6 +3874,18 @@ tooltip: string | undefined
unit: string | undefined
```
+## FieldSample — interface @experimental
+```
+amp: number
+calm: number
+depth: number
+flowX: number
+flowZ: number
+height: number
+key: number
+shore: number
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -4068,6 +4080,7 @@ sizeZ: number
## FoliageField — class @experimental
```
+@internal authoredWind_: Map<number, number>
@internal built_: Map<number, BuiltFoliage>
cellCount: number
pending: number
@@ -4448,11 +4461,6 @@ 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
@@ -7231,12 +7239,6 @@ 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
@@ -8320,25 +8322,6 @@ 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
@@ -10879,11 +10862,6 @@ SolidColor = 1
Tiled = 4
```
-## UNKNOWN_DEPTH — const @experimental
-```
-1000000000
-```
-
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11238,24 +11216,33 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
boundary: Point2[]
-cellSize: number
-cells: number
flowSpeed: number
-foamFade: number
form: number
-material: number
-rings: number
-rippleDamping: number
-rippleSize: number
-rippleSpeed: number
-ripples: number
shoreWidth: number
sizeX: number
sizeZ: number
-waveDirection: number
waveHeight: number
-waveLength: number
-waveSpeed: number
+```
+
+## WaterField — class @experimental
+```
+amp: Float32Array<ArrayBufferLike>
+at: (x: number, z: number) => FieldSample | null
+calm: Float32Array<ArrayBufferLike>
+depth: Float32Array<ArrayBufferLike>
+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }
+flowX: Float32Array<ArrayBufferLike>
+flowZ: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+height: Float32Array<ArrayBufferLike>
+ocean: ZoneOcean | null
+owner: Int32Array<ArrayBufferLike>
+ranges: () => ZoneRanges
+sample: (x: number, z: number) => FieldSample | null
+shore: Float32Array<ArrayBufferLike>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
+static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
+static prototype: WaterField
```
## WaterForm — const @experimental
@@ -11282,14 +11269,41 @@ normal: [number, number, number]
surface: [number, number, number]
```
+## WaterZone — const @experimental
+```
+ComponentDef<WaterZoneData>
+```
+
+## WaterZoneData — interface @experimental
+```
+cellSize: number
+cells: number
+foamFade: number
+material: number
+resolution: number
+rings: number
+rippleDamping: number
+rippleSize: number
+rippleSpeed: number
+ripples: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveLength: number
+waveSpeed: number
+```
+
## Waters — class @experimental
```
@internal app_: App | null
-@internal built_: Map<number, Built>
+@internal field_: WaterField | null
+@internal instance_: number
+@internal ripples_: RippleField | null
+@internal zone_: WaterZoneData
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
-rippleAt: (x: number, y: number, z: number) => number
+rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
static new (): Waters
static prototype: Waters
@@ -11345,7 +11359,7 @@ target: number
## WeatherDrive — const @experimental
```
-{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly Wind: 128; readonly All: 255; }
```
## WeatherPreset — type @experimental
@@ -11375,7 +11389,9 @@ sound: number
ssr: number
sun: number
sunTint: [number, number, number]
+waves: number
wetness: number
+wind: number
```
## WebAppOptions — interface @experimental
@@ -12051,11 +12067,6 @@ 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
@@ -12081,16 +12092,6 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
-## buildRectMesh — function @experimental
-```
-(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
-```
-
-## buildRiverMesh — function @experimental
-```
-(curve: SplineCurve, step: number, across: number): MeshData
-```
-
## buildText — function @experimental
```
(init?: TextInit): TextData
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 81d35c385..5b7e6f621 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 · 1770 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1767 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3874,6 +3874,18 @@ tooltip: string | undefined
unit: string | undefined
```
+## FieldSample — interface @experimental
+```
+amp: number
+calm: number
+depth: number
+flowX: number
+flowZ: number
+height: number
+key: number
+shore: number
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -4068,6 +4080,7 @@ sizeZ: number
## FoliageField — class @experimental
```
+@internal authoredWind_: Map<number, number>
@internal built_: Map<number, BuiltFoliage>
cellCount: number
pending: number
@@ -4448,11 +4461,6 @@ 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
@@ -7524,12 +7532,6 @@ 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
@@ -8613,25 +8615,6 @@ 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
@@ -11172,11 +11155,6 @@ SolidColor = 1
Tiled = 4
```
-## UNKNOWN_DEPTH — const @experimental
-```
-1000000000
-```
-
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11537,24 +11515,33 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
boundary: Point2[]
-cellSize: number
-cells: number
flowSpeed: number
-foamFade: number
form: number
-material: number
-rings: number
-rippleDamping: number
-rippleSize: number
-rippleSpeed: number
-ripples: number
shoreWidth: number
sizeX: number
sizeZ: number
-waveDirection: number
waveHeight: number
-waveLength: number
-waveSpeed: number
+```
+
+## WaterField — class @experimental
+```
+amp: Float32Array<ArrayBufferLike>
+at: (x: number, z: number) => FieldSample | null
+calm: Float32Array<ArrayBufferLike>
+depth: Float32Array<ArrayBufferLike>
+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }
+flowX: Float32Array<ArrayBufferLike>
+flowZ: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+height: Float32Array<ArrayBufferLike>
+ocean: ZoneOcean | null
+owner: Int32Array<ArrayBufferLike>
+ranges: () => ZoneRanges
+sample: (x: number, z: number) => FieldSample | null
+shore: Float32Array<ArrayBufferLike>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
+static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
+static prototype: WaterField
```
## WaterForm — const @experimental
@@ -11581,14 +11568,41 @@ normal: [number, number, number]
surface: [number, number, number]
```
+## WaterZone — const @experimental
+```
+ComponentDef<WaterZoneData>
+```
+
+## WaterZoneData — interface @experimental
+```
+cellSize: number
+cells: number
+foamFade: number
+material: number
+resolution: number
+rings: number
+rippleDamping: number
+rippleSize: number
+rippleSpeed: number
+ripples: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveLength: number
+waveSpeed: number
+```
+
## Waters — class @experimental
```
@internal app_: App | null
-@internal built_: Map<number, Built>
+@internal field_: WaterField | null
+@internal instance_: number
+@internal ripples_: RippleField | null
+@internal zone_: WaterZoneData
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
-rippleAt: (x: number, y: number, z: number) => number
+rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
static new (): Waters
static prototype: Waters
@@ -11644,7 +11658,7 @@ target: number
## WeatherDrive — const @experimental
```
-{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly Wind: 128; readonly All: 255; }
```
## WeatherPreset — type @experimental
@@ -11674,7 +11688,9 @@ sound: number
ssr: number
sun: number
sunTint: [number, number, number]
+waves: number
wetness: number
+wind: number
```
## WebAppOptions — interface @experimental
@@ -12350,11 +12366,6 @@ 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
@@ -12380,16 +12391,6 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
-## buildRectMesh — function @experimental
-```
-(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
-```
-
-## buildRiverMesh — function @experimental
-```
-(curve: SplineCurve, step: number, across: number): MeshData
-```
-
## buildText — function @experimental
```
(init?: TextInit): TextData
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index ebcabec63..ec7bfa2db 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -1,7 +1,19 @@
# API surface — esengine/water
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 0 beta · 37 experimental · 0 deprecated
+Symbols: 0 public · 0 beta · 34 experimental · 0 deprecated
+
+## FieldSample — interface @experimental
+```
+amp: number
+calm: number
+depth: number
+flowX: number
+flowZ: number
+height: number
+key: number
+shore: number
+```
## Floating — const @experimental
```
@@ -39,23 +51,12 @@ static new (): FloatingPlugin
static prototype: FloatingPlugin
```
-## 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
-```
-
## RippleField — class @experimental
```
cell: number
@@ -68,6 +69,7 @@ n: number
originX: number
originZ: number
peak: () => number
+rainOwed: number
recenter: (x: number, z: number) => boolean
size: number
step: (dt: number, speed: number, damping: number, foamFade: number) => void
@@ -75,30 +77,6 @@ static new (n: number, size: number): RippleField
static prototype: RippleField
```
-## 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
-```
-
## UnderwaterPlugin — class @experimental
```
build: (app: App) => void
@@ -121,24 +99,33 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
boundary: Point2[]
-cellSize: number
-cells: number
flowSpeed: number
-foamFade: number
form: number
-material: number
-rings: number
-rippleDamping: number
-rippleSize: number
-rippleSpeed: number
-ripples: number
shoreWidth: number
sizeX: number
sizeZ: number
-waveDirection: number
waveHeight: number
-waveLength: number
-waveSpeed: number
+```
+
+## WaterField — class @experimental
+```
+amp: Float32Array<ArrayBufferLike>
+at: (x: number, z: number) => FieldSample | null
+calm: Float32Array<ArrayBufferLike>
+depth: Float32Array<ArrayBufferLike>
+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }
+flowX: Float32Array<ArrayBufferLike>
+flowZ: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+height: Float32Array<ArrayBufferLike>
+ocean: ZoneOcean | null
+owner: Int32Array<ArrayBufferLike>
+ranges: () => ZoneRanges
+sample: (x: number, z: number) => FieldSample | null
+shore: Float32Array<ArrayBufferLike>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
+static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
+static prototype: WaterField
```
## WaterForm — const @experimental
@@ -165,14 +152,41 @@ normal: [number, number, number]
surface: [number, number, number]
```
+## WaterZone — const @experimental
+```
+ComponentDef<WaterZoneData>
+```
+
+## WaterZoneData — interface @experimental
+```
+cellSize: number
+cells: number
+foamFade: number
+material: number
+resolution: number
+rings: number
+rippleDamping: number
+rippleSize: number
+rippleSpeed: number
+ripples: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveLength: number
+waveSpeed: number
+```
+
## Waters — class @experimental
```
@internal app_: App | null
-@internal built_: Map<number, Built>
+@internal field_: WaterField | null
+@internal instance_: number
+@internal ripples_: RippleField | null
+@internal zone_: WaterZoneData
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
-rippleAt: (x: number, y: number, z: number) => number
+rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
static new (): Waters
static prototype: Waters
@@ -192,26 +206,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
```
-## buildRectMesh — function @experimental
-```
-(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
-```
-
-## buildRiverMesh — function @experimental
-```
-(curve: SplineCurve, step: number, across: number): MeshData
-```
-
## currentShare — function @experimental
```
(width: number, widest: number): number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index c266687f8..a24187754 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 · 1761 experimental · 3 deprecated
+Symbols: 115 public · 159 beta · 1758 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3874,6 +3874,18 @@ tooltip: string | undefined
unit: string | undefined
```
+## FieldSample — interface @experimental
+```
+amp: number
+calm: number
+depth: number
+flowX: number
+flowZ: number
+height: number
+key: number
+shore: number
+```
+
## FillMethod — enum @beta
```
Horizontal = 0
@@ -4068,6 +4080,7 @@ sizeZ: number
## FoliageField — class @experimental
```
+@internal authoredWind_: Map<number, number>
@internal built_: Map<number, BuiltFoliage>
cellCount: number
pending: number
@@ -4448,11 +4461,6 @@ 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
@@ -7238,12 +7246,6 @@ 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
@@ -8327,25 +8329,6 @@ 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
@@ -10886,11 +10869,6 @@ SolidColor = 1
Tiled = 4
```
-## UNKNOWN_DEPTH — const @experimental
-```
-1000000000
-```
-
## UniformValue — type @experimental
```
number | Vec2 | Vec3 | Vec4 | number[] | TextureRef
@@ -11245,24 +11223,33 @@ ComponentDef<WaterBodyData>
## WaterBodyData — interface @experimental
```
boundary: Point2[]
-cellSize: number
-cells: number
flowSpeed: number
-foamFade: number
form: number
-material: number
-rings: number
-rippleDamping: number
-rippleSize: number
-rippleSpeed: number
-ripples: number
shoreWidth: number
sizeX: number
sizeZ: number
-waveDirection: number
waveHeight: number
-waveLength: number
-waveSpeed: number
+```
+
+## WaterField — class @experimental
+```
+amp: Float32Array<ArrayBufferLike>
+at: (x: number, z: number) => FieldSample | null
+calm: Float32Array<ArrayBufferLike>
+depth: Float32Array<ArrayBufferLike>
+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }
+flowX: Float32Array<ArrayBufferLike>
+flowZ: Float32Array<ArrayBufferLike>
+grid: ZoneGrid
+height: Float32Array<ArrayBufferLike>
+ocean: ZoneOcean | null
+owner: Int32Array<ArrayBufferLike>
+ranges: () => ZoneRanges
+sample: (x: number, z: number) => FieldSample | null
+shore: Float32Array<ArrayBufferLike>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
+static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
+static prototype: WaterField
```
## WaterForm — const @experimental
@@ -11289,14 +11276,41 @@ normal: [number, number, number]
surface: [number, number, number]
```
+## WaterZone — const @experimental
+```
+ComponentDef<WaterZoneData>
+```
+
+## WaterZoneData — interface @experimental
+```
+cellSize: number
+cells: number
+foamFade: number
+material: number
+resolution: number
+rings: number
+rippleDamping: number
+rippleSize: number
+rippleSpeed: number
+ripples: number
+sizeX: number
+sizeZ: number
+waveDirection: number
+waveLength: number
+waveSpeed: number
+```
+
## Waters — class @experimental
```
@internal app_: App | null
-@internal built_: Map<number, Built>
+@internal field_: WaterField | null
+@internal instance_: number
+@internal ripples_: RippleField | null
+@internal zone_: WaterZoneData
disturb: (x: number, y: number, z: number, radius: number, strength: number) => boolean
heightAt: (x: number, z: number) => number | null
quality: WaterQuality
-rippleAt: (x: number, y: number, z: number) => number
+rippleAt: (x: number, _y: number, z: number) => number
sample: (x: number, y: number, z: number) => WaterSample | null
static new (): Waters
static prototype: Waters
@@ -11376,7 +11390,7 @@ target: number
## WeatherDrive — const @experimental
```
-{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly All: 127; }
+{ readonly Lights: 1; readonly Fog: 2; readonly Rain: 4; readonly Grade: 8; readonly Exposure: 16; readonly Reflections: 32; readonly Sound: 64; readonly Wind: 128; readonly All: 255; }
```
## WeatherPreset — type @experimental
@@ -11406,7 +11420,9 @@ sound: number
ssr: number
sun: number
sunTint: [number, number, number]
+waves: number
wetness: number
+wind: number
```
## WebAppOptions — interface @experimental
@@ -12082,11 +12098,6 @@ 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
@@ -12112,16 +12123,6 @@ MotionDriver<AnimatorBlend2DMotion>
(cells: number, rings: number, cellSize: number): MeshData
```
-## buildRectMesh — function @experimental
-```
-(sizeX: number, sizeZ: number, cellSize: number, options?: RectOptions): MeshData
-```
-
-## buildRiverMesh — function @experimental
-```
-(curve: SplineCurve, step: number, across: number): MeshData
-```
-
## buildText — function @experimental
```
(init?: TextInit): TextData
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index ec7be22d4..01498f46c 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -806,9 +806,9 @@ 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 { buildRiverMesh, currentShare } from './water/riverMesh';
-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 { 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 {
scatterCell, buildGrassMesh, buildInstancedMesh, buildBillboardMesh, rng,
type Plant, type Ground, type ScatterParams, type BladeParams, type CardRect,
diff --git a/sdk/src/water/floating.ts b/sdk/src/water/floating.ts
index ee180229a..a45a820aa 100644
--- a/sdk/src/water/floating.ts
+++ b/sdk/src/water/floating.ts
@@ -55,7 +55,7 @@ export const Floating: ComponentDef<FloatingData> = defineComponent<FloatingData
drag: { min: 0, max: 20, category: 'Water', tooltip: 'How hard the water resists the body moving through it, per second.' },
radius: { min: 0.01, category: 'Water', tooltip: 'How deep under the surface, in world units, a point of the body is wholly wet.' },
points: { category: 'Water', tooltip: 'Points of the body, in its own space, the water is asked about: spread them (the corners of a hull) and waves tip it. Empty is the one at its origin.' },
- wake: { min: 0, max: 10, category: 'Water', tooltip: 'How much of a ripple the body makes in water that keeps ripples (WaterBody Ripples). 0 makes none.' },
+ wake: { min: 0, max: 10, category: 'Water', tooltip: 'How much of a ripple the body makes in water that keeps ripples (WaterZone Ripples). 0 makes none.' },
},
});
diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.ts
index 17473cea6..43141eb40 100644
--- a/sdk/src/water/index.ts
+++ b/sdk/src/water/index.ts
@@ -7,9 +7,9 @@ export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './wa
export { UnderwaterPlugin, registerUnderwaterEffect } from './underwater';
export { RippleField } from './ripples';
export { Floating, FloatingPlugin, floatingForce, wakeStrength, type FloatingBody, type FloatingData, type FloatingForce } from './floating';
-export { buildRiverMesh, currentShare } from './riverMesh';
-export { buildBoxMesh, buildOceanMesh, buildRectMesh, oceanReach, oceanSnap, type RectOptions } from './waterMesh';
-export { ShoreField, UNKNOWN_DEPTH, polygonSdf, shoreDamp, type GroundDepth, type Point2 } from './shore';
+export { WaterZone, WaterField, currentShare, type WaterZoneData, type FieldSample } from './zone';
+export { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';
+export { polygonSdf, shoreDamp, type Point2 } from './shore';
// Importing this subpath INSTALLS water — see tilemap/index.ts.
import { registerWaterSupport } from './waterSupport';
diff --git a/sdk/src/water/riverMesh.ts b/sdk/src/water/riverMesh.ts
deleted file mode 100644
index 309ea48ab..000000000
--- a/sdk/src/water/riverMesh.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file riverMesh.ts
- * @brief The geometry of a river: a ribbon laid along a curve, as wide as the curve says at every point.
- *
- * @details Stations are cut along the curve a `step` apart and each is a row of vertices across the width, from one bank to the other, in the
- * body's own space with the height of the curve under them (a river runs downhill). The uv is the position, as for a lake, so the Water
- * shader's body space is the same. The vertex colour carries the current: red and green the direction of travel on the xz plane (0.5
- * is none), blue how fast the water runs there against its nominal speed, half being the nominal: a narrow reach is quick and a wide one slow,
- * which is what the same water through a different width does.
- */
-import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';
-import type { SplineCurve } from '../spline/curve';
-
-/** What the current is at a station: the speed against the nominal one, for a reach this wide against the curve's widest. */
-export function currentShare(width: number, widest: number): number {
- return Math.min(Math.max(widest / Math.max(width, 1e-3), 0.25), 2) / 2;
-}
-
-/** A river along `curve`, a station every `step` along it and `across` cells from bank to bank. */
-export function buildRiverMesh(curve: SplineCurve, step: number, across: number): MeshData {
- const stations = Math.max(2, Math.ceil(curve.length / Math.max(step, 1e-3)) + 1);
- const cells = Math.max(1, Math.floor(across));
- let widest = 0;
- for (let i = 0; i < stations; i++) widest = Math.max(widest, curve.width((i / (stations - 1)) * curve.length));
- const positions: number[] = [], colors: number[] = [];
- for (let i = 0; i < stations; i++) {
- const s = (i / (stations - 1)) * curve.length;
- const [cx, cy, cz] = curve.position(s);
- const [tx, , tz] = curve.tangent(s);
- const along = Math.hypot(tx, tz) || 1;
- const dx = tx / along, dz = tz / along;
- // The bank to the right of the heading (looking along it from above, +x right, +z toward the viewer): the perpendicular (-dz, dx).
- const nx = -dz, nz = dx;
- const half = curve.width(s) / 2;
- const share = currentShare(half * 2, widest);
- for (let k = 0; k <= cells; k++) {
- const v = (k / cells) * 2 - 1;
- positions.push(cx + nx * v * half, cy, cz + nz * v * half);
- colors.push(dx * 0.5 + 0.5, dz * 0.5 + 0.5, share, 1);
- }
- }
- const stride = cells + 1;
- const indices: number[] = [];
- for (let i = 0; i < stations - 1; i++) {
- for (let k = 0; k < cells; k++) {
- const a = i * stride + k, b = i * stride + k + 1, c = (i + 1) * stride + k, d = (i + 1) * stride + k + 1;
- // Facing up for a heading along +x with the right bank toward +z: (a, b, c) turns the way the lake's cells do.
- indices.push(a, b, c, c, b, d);
- }
- }
- return pack(positions, colors, indices);
-}
-
-function pack(positions: number[], colors: number[], indices: number[]): MeshData {
- const { channels, vertexStride } = packChannels([
- { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
- { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
- { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
- { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },
- ]);
- const vertexCount = positions.length / 3;
- const vertices = new Uint8Array(vertexCount * vertexStride);
- const view = new DataView(vertices.buffer);
- const posAt = channels[0]!.offset, uvAt = channels[1]!.offset, colorAt = channels[2]!.offset, normalAt = channels[3]!.offset;
- const min: [number, number, number] = [Infinity, Infinity, Infinity];
- const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
- for (let i = 0; i < vertexCount; i++) {
- const base = i * vertexStride;
- for (let k = 0; k < 3; k++) {
- const value = positions[i * 3 + k]!;
- view.setFloat32(base + posAt + k * 4, value, true);
- if (value < min[k]!) min[k] = value;
- if (value > max[k]!) max[k] = value;
- }
- view.setFloat32(base + normalAt, 0, true);
- view.setFloat32(base + normalAt + 4, 1, true);
- view.setFloat32(base + normalAt + 8, 0, true);
- view.setFloat32(base + uvAt, positions[i * 3]!, true);
- view.setFloat32(base + uvAt + 4, positions[i * 3 + 2]!, true);
- for (let k = 0; k < 4; k++) view.setUint8(base + colorAt + k, Math.round(Math.min(Math.max(colors[i * 4 + k]!, 0), 1) * 255));
- }
- return { channels, vertexStride, vertexCount, vertices, indices: new Uint32Array(indices), aabbMin: min, aabbMax: max };
-}
diff --git a/sdk/src/water/shore.ts b/sdk/src/water/shore.ts
index e4605f93d..8a924122b 100644
--- a/sdk/src/water/shore.ts
+++ b/sdk/src/water/shore.ts
@@ -2,22 +2,9 @@
// 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.
+ * @brief Where a lake ends, and how the waves calm toward it: what the zone (zone.ts) bakes a lake's outline and shore with.
*/
-/** 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 }
@@ -45,82 +32,3 @@ export function shoreDamp(reach: number, width: number): number {
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/underwater.ts b/sdk/src/water/underwater.ts
index 457c05b71..6cd583021 100644
--- a/sdk/src/water/underwater.ts
+++ b/sdk/src/water/underwater.ts
@@ -304,8 +304,7 @@ export class UnderwaterPlugin implements Plugin {
const sample = eye ? waters.sample(eye[0], eye[1], eye[2]) : null;
// Under, or close enough above that part of the lens (the near plane ahead of the camera) can be: the effect decides pixel by pixel.
if (!sample || !(sample.depth < lensReach(near))) { setUnderwaterState(null); return; }
- const built = waters.built_.get(sample.entity);
- const instance = built?.instance ?? 0;
+ const instance = waters.instance_;
const depth = Math.max(-sample.depth, 0);
const density = single(instance, 'u_density', 0.12);
const shallow = triple(instance, 'u_shallowColor', [0.10, 0.42, 0.46]);
diff --git a/sdk/src/water/waterMesh.ts b/sdk/src/water/waterMesh.ts
index 1b9e2d668..2f585b605 100644
--- a/sdk/src/water/waterMesh.ts
+++ b/sdk/src/water/waterMesh.ts
@@ -2,14 +2,13 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file waterMesh.ts
- * @brief The geometry of a body of water: a flat grid for a lake, rings of coarsening grids for an ocean.
+ * @brief The geometry of a zone's water: rings of coarsening grids that follow the camera.
*
- * @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), 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).
+ * @details It lies in the xz plane facing up, with the uv the position itself (so the Water shader's surface space is x and z, plus
+ * `u_origin`), 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).
*
- * 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
+ * The surface 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
* do between its vertices; the fade keeps that to waves the coarse ring can already draw.
*/
@@ -23,43 +22,6 @@ 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, 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++) {
- 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++) {
- 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);
-}
-
/**
* An ocean of `rings` rings of `cells` cells a side (a multiple of four), the innermost with `cellSize` cells. It reaches
* `cells * cellSize * 2^(rings - 1) / 2` out from its centre.
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 590954e3a..be099ec67 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -2,16 +2,17 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file waterPlugin.ts
- * @brief A body of water: a component that says what it is, a mesh the plugin builds for it, and the surface it answers questions about.
+ * @brief Bodies of water, the zone they are baked into, the one surface drawn from it, and the surface they answer questions about.
*
- * @details The `WaterBody` component names a form (an ocean, a lake) and the waves; this builds the geometry as a child entity, gives it a
- * material instance of its own (the Water material with the waves, the body's space and its cell size written in), and keeps
- * the instance in step with the component every frame, so editing a field moves the water at once.
+ * @details A `WaterBody` says what water is where: an ocean, a lake inside an outline, a river along a Spline, each with the height its waves
+ * stand to and how far in from its shore they calm. It is not drawn on its own: the bodies are inputs to a zone (zone.ts), which bakes
+ * them over its region into one field (the surface's height, the shore, the waves' height, the current) where rivers run into lakes and
+ * lakes into the sea with no seam. One mesh of rings following the camera reads the field and is every body's surface; the zone's
+ * `WaterZone` component (or, without one, a zone over every lake and river with its defaults) says where, how fine, the waves every
+ * body shares and the material.
*
- * The waves are the ones the Water shader draws: `waves.ts` is the same formula, and {@link Waters.sample} answers from it in the body's
- * own frame, so a floating object, a camera under the surface and a splash all read the surface that is on the screen. The body's
- * transform places and tilts it (waves follow its up), and an ocean's mesh follows the camera on a lattice its rings line up on,
- * with the material's origin moved by as much so the waves stay put in the world.
+ * The waves are the ones the Water shader draws: `waves.ts` is the same formula, and {@link Waters.sample} answers from the same field, so
+ * a floating object, a camera under the surface and a splash all read the surface that is on the screen.
*/
import type { App, Plugin } from '../app/app';
import { defineSystem, Schedule } from '../ecs/system';
@@ -31,13 +32,17 @@ import { BlendMode } from '../render/blend';
import { log } from '../util/logger';
import type { Entity } from '../types';
import { waveHeight, waveSlope, type WaveParams } from './waves';
-import { buildBoxMesh, buildOceanMesh, oceanSnap } from './waterMesh';
-import { ShoreField, type Point2 } from './shore';
-import { buildRiverMesh, currentShare } from './riverMesh';
+import { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';
+import { type Point2 } from './shore';
import { Spline, type SplineData } from '../spline/splinePlugin';
import { SplineCurve } from '../spline/curve';
import { RippleField } from './ripples';
+import {
+ WaterField, WaterZone, currentShare,
+ type RiverStation, type WaterZoneData, type ZoneBody, type ZoneGrid, type ZoneGround,
+} from './zone';
import { Quality } from '../render/qualityRuntime';
+import { currentWeather, currentWeatherDrive, WeatherDrive } from '../postprocess/weather';
import { defaultQualityProfile, type QualityProfile } from '../render/quality';
import { isMiniGame } from '../platform';
@@ -48,74 +53,43 @@ export const WaterForm = { Ocean: 0, Lake: 1, River: 2 } as const;
export interface WaterBodyData {
/** {@link WaterForm}. */
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, when it has no outline of its own. 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 goes on past the zone. */
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. */
+ /** How far in from the shore, 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;
- rings: number;
/** A river's current, in world units a second where the river is as wide as its widest; a narrower reach runs faster. */
flowSpeed: number;
- /** The waves: the height of the tallest, the length of the longest, a multiplier on their speed, and the heading in degrees. */
+ /** The height of the tallest wave, in world units. Their length, speed and heading are the zone's, which every body shares. */
waveHeight: number;
- waveLength: number;
- waveSpeed: number;
- waveDirection: number;
- /** Cells along a side of the ripple grid; 0 keeps no ripples. The grid is a window of `rippleSize` that follows the camera. */
- ripples: number;
- rippleSize: number;
- /** How fast a ripple spreads (world units a second), how much of its height it loses a second, and how fast the foam it leaves fades a second. */
- rippleSpeed: number;
- rippleDamping: number;
- foamFade: number;
}
/**
- * A body of water. Presence is the opt-in; its geometry is a child, rebuilt when the shape changes.
+ * A body of water. Presence is the opt-in; it is drawn as part of its zone's surface.
*
* @experimental
*/
export const WaterBody: ComponentDef<WaterBodyData> = defineComponent<WaterBodyData>('WaterBody', {
- form: WaterForm.Lake, material: 0, sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, cellSize: 1, cells: 64, rings: 5, flowSpeed: 2,
- waveHeight: 0.3, waveLength: 14, waveSpeed: 1, waveDirection: 30,
- ripples: 0, rippleSize: 64, rippleSpeed: 6, rippleDamping: 0.8, foamFade: 0.4,
+ form: WaterForm.Lake, sizeX: 100, sizeZ: 100, boundary: [] as Point2[], shoreWidth: 3, flowSpeed: 2, waveHeight: 0.3,
}, {
- assetFields: [{ field: 'material', type: 'material' }],
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 and follows the camera; a lake is a rectangle or an outline of its own; a river follows the Spline on the same entity.' },
- flowSpeed: { min: 0, max: 50, category: 'Waves', tooltip: 'A river\'s current, in world units a second where it is as wide as its widest. A narrower reach runs faster.', shownWhen: { field: 'form', values: [WaterForm.River] } },
- material: { category: 'Look', tooltip: 'A material on the Water shader. Empty uses the stock water.' },
+ 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.' },
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] } },
- 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.', shownWhen: { field: 'form', values: [WaterForm.Lake] } },
- 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).', shownWhen: { field: 'form', values: [WaterForm.Ocean] } },
- rings: { min: 1, max: 8, step: 1, category: 'Detail', tooltip: 'Rings of an ocean, each twice as coarse as the one inside it.', shownWhen: { field: 'form', values: [WaterForm.Ocean] } },
- waveHeight: { min: 0, max: 8, category: 'Waves', tooltip: 'The height of the tallest wave, in world units.' },
- waveLength: { min: 0.5, max: 300, category: 'Waves', tooltip: 'The length of the longest wave.' },
- waveSpeed: { min: 0, max: 4, category: 'Waves', tooltip: 'A multiplier on how fast the waves travel.' },
- waveDirection: { min: 0, max: 360, category: 'Waves', tooltip: 'The heading of the waves, in degrees.' },
- ripples: { min: 0, max: 256, step: 8, category: 'Ripples', tooltip: 'Cells along a side of the grid that keeps what disturbs the water: bodies moving in it, and what a script disturbs. 0 keeps none.' },
- rippleSize: { min: 4, category: 'Ripples', tooltip: 'The side of the window the ripples are kept in, in world units. It follows the camera.' },
- rippleSpeed: { min: 0.1, max: 40, category: 'Ripples', tooltip: 'How fast a ripple spreads, in world units a second.' },
- rippleDamping: { min: 0, max: 10, category: 'Ripples', tooltip: 'How much of its height a ripple loses each second.' },
- foamFade: { min: 0, max: 10, category: 'Ripples', tooltip: 'How fast the foam a disturbance leaves fades, a second.' },
+ shoreWidth: { min: 0, category: 'Shape', tooltip: 'How far in from the shore, and how deep, the waves take to come to full height. 0 leaves them whole to the edge.' },
+ flowSpeed: { min: 0, max: 5000, category: 'Waves', tooltip: 'A river\'s current, in world units a second where it is as wide as its widest. A narrower reach runs faster.', shownWhen: { field: 'form', values: [WaterForm.River] } },
+ waveHeight: { min: 0, max: 800, category: 'Waves', tooltip: 'The height of the tallest wave, in world units. Their length, speed and heading are the zone\'s.' },
},
});
/** What {@link Waters.sample} answers. */
export interface WaterSample {
- /** The body's entity. */
+ /** The entity of the body that holds the most of the water there. */
entity: Entity;
- /** How far the point is above the surface along the body's up (negative under it), in world units. */
+ /** 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. */
normal: [number, number, number];
@@ -123,7 +97,7 @@ export interface WaterSample {
flow: [number, number, number];
/** The world position of the surface above or below the point. */
surface: [number, number, number];
- /** Whether the point is over the body's extent (an ocean has none, so it is always). */
+ /** Whether the point is over water: always, for an answer that is not null. */
inside: boolean;
}
@@ -149,132 +123,65 @@ export function waterQualityOf(profile: Readonly<QualityProfile> | null, miniGam
return { waves: p.waterWaves, rippleCells: p.waterRippleCells, displacement: p.waterDisplacement, mirror: p.waterMirror, caustics: p.waterCaustics };
}
-/** What the plugin knows about one body it has built. */
-interface Built {
- signature: string;
- data: WaterBodyData;
- mesh: number;
- /** A lake's baked shore, and the texture the shader reads it from. */
- field: ShoreField | null;
- /** A river's curve, the width it is drawn at its widest, and the shoreless texture it does not have. */
- curve: SplineCurve | null;
- widest: number;
- shoreTexture: number;
- /** The ripples this body keeps, where `ripples` asks for them, and the texture the shader reads them from. */
- ripples: RippleField | null;
- rippleTexture: number;
- rippleBytes: Uint8Array | null;
- child: Entity;
- instance: number;
- epoch: number;
- pending: boolean;
-}
+/** The zone a scene without a `WaterZone` is given: the component's defaults, over every lake and river. */
+const ZONE_DEFAULTS: WaterZoneData = { ...WaterZone._default };
/** Run-time access to the water: where its surface is at a point, for what floats on it or swims in it. */
export class Waters {
- /** @internal */ readonly built_ = new Map<Entity, Built>();
/** @internal */ app_: App | null = null;
/** What the quality level allows now; the plugin refreshes it each frame, and what is drawn and what is answered both follow it. */
quality: WaterQuality = FULL_WATER;
+ /** The baked water, and the zone it was baked by. @internal */
+ field_: WaterField | null = null;
+ /** @internal */ zone_: WaterZoneData = ZONE_DEFAULTS;
+ /** The ripples the zone keeps, where it asks for them. @internal */
+ ripples_: RippleField | null = null;
+ /** The material instance the surface is drawn with, for what draws the same water (the underwater effect). @internal */
+ instance_ = 0;
/**
- * The surface of the body that holds `(x, y, z)`: how far above it the point is (negative under), the surface's normal and the point on
- * it straight above or below along the body's up. Null where there is no water. The body's position, rotation and uniform scale are taken
- * into account, and the waves are read at the instant of the frame.
+ * The surface over or under `(x, y, z)`: how far above it the point is (negative under), the surface's normal, the current, and the point
+ * on it straight above or below. Null where there is no water. The waves are read at the instant of the frame.
*/
sample(x: number, y: number, z: number): WaterSample | null {
- const world = this.app_?.world;
- if (!world) return null;
- const time = this.app_!.getResource(Time).elapsed;
- for (const [entity, built] of this.built_) {
- if (!world.valid(entity)) continue;
- const t = world.tryGet(entity, Transform) as TransformData | null;
- if (!t) continue;
- const scale = t.worldScale.y || 1;
- const q = toLocal(t, x, y, z, scale);
- const d = built.data;
- const field = built.field;
- if (d.form === WaterForm.River) {
- const curve = built.curve;
- if (!curve) continue;
- const near = curve.nearest(q[0], q[2]);
- const half = curve.width(near.s) / 2;
- if (near.distance > half) continue;
- // A river's surface is the curve's own height and its normal is up; what moves is the water.
- const level = curve.position(near.s)[1];
- const tangent = curve.tangent(near.s);
- const run = Math.hypot(tangent[0], tangent[2]) || 1;
- const speed = d.flowSpeed * currentShare(half * 2, built.widest) * 2;
- const flow = rotate(t.worldRotation, (tangent[0] / run) * speed * scale, 0, (tangent[2] / run) * speed * scale);
- const normal = rotate(t.worldRotation, 0, 1, 0);
- return { entity, depth: (q[1] - level) * scale, normal, flow, surface: fromLocal(t, q[0], level, q[2], scale), inside: true };
- }
- const inside = d.form === WaterForm.Ocean || (field ? field.inside(q[0], q[2]) : false);
- if (!inside) continue;
- const params = { ...paramsOf(d), count: this.quality.waves };
- // 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;
- // The lite water is flat: its waves are in the shading, so the height code reads is the rest plane's.
- const h = (this.quality.displacement ? waveHeight(params, q[0], q[2], time) * damp : 0) + (built.ripples ? built.ripples.heightAt(q[0], q[2]) : 0);
- 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);
- return { entity, depth: (q[1] - h) * scale, normal, flow: [0, 0, 0], surface: onSurface, inside };
- }
- return null;
+ const field = this.field_;
+ if (!field || !this.app_) return null;
+ const s = field.sample(x, z);
+ if (!s) return null;
+ const time = this.app_.getResource(Time).elapsed;
+ const params = this.waves(s.amp);
+ // The lite water is flat: its waves are in the shading, so the height code reads is the rest plane's.
+ const h = s.height + (this.quality.displacement ? waveHeight(params, x, z, time) : 0) + (this.ripples_?.heightAt(x, z) ?? 0);
+ 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,
+ };
}
/**
* Disturbs the water at the world point (x, y, z): a bump of `strength` world units (negative is a dip) over `radius`, which spreads as a ring and leaves foam.
- * Goes to the body that holds the point, and does nothing where there is none or where the body keeps no ripples.
+ * Does nothing where there is no water or where the zone keeps no ripples.
*/
disturb(x: number, y: number, z: number, radius: number, strength: number): boolean {
- const world = this.app_?.world;
- if (!world) return false;
- for (const [entity, built] of this.built_) {
- if (!world.valid(entity) || !built.ripples) continue;
- const t = world.tryGet(entity, Transform) as TransformData | null;
- if (!t) continue;
- const scale = t.worldScale.y || 1;
- const q = toLocal(t, x, y, z, scale);
- const inside = built.data.form === WaterForm.Ocean || (built.field ? built.field.inside(q[0], q[2]) : false)
- || (built.curve ? built.curve.nearest(q[0], q[2]).distance <= built.curve.width(built.curve.nearest(q[0], q[2]).s) / 2 : false);
- if (!inside) continue;
- built.ripples.disturb(q[0], q[2], radius / scale, strength / scale);
- return true;
- }
- return false;
+ if (!this.ripples_ || !this.field_?.sample(x, z)) return false;
+ this.ripples_.disturb(x, z, radius, strength);
+ return true;
}
- /** The height the ripples add to the surface at the world point, for a body that keeps them; 0 elsewhere. */
- rippleAt(x: number, y: number, z: number): number {
- const world = this.app_?.world;
- if (!world) return 0;
- for (const [entity, built] of this.built_) {
- if (!world.valid(entity) || !built.ripples) continue;
- const t = world.tryGet(entity, Transform) as TransformData | null;
- if (!t) continue;
- const scale = t.worldScale.y || 1;
- const q = toLocal(t, x, y, z, scale);
- const h = built.ripples.heightAt(q[0], q[2]);
- if (h !== 0) return h * scale;
- }
- return 0;
+ /** The height the ripples add to the surface at the world point, where the zone keeps them; 0 elsewhere. */
+ rippleAt(x: number, _y: number, z: number): number {
+ return this.ripples_?.heightAt(x, z) ?? 0;
}
- /** The world height of the surface above or below (x, z) for an untilted body, or null where there is none. */
+ /** The world height of the surface above or below (x, z), or null where there is none. */
heightAt(x: number, z: number): number | null {
- const world = this.app_?.world;
- if (!world) return null;
- for (const entity of this.built_.keys()) {
- if (!world.valid(entity)) continue;
- const t = world.tryGet(entity, Transform) as TransformData | null;
- const s = t ? this.sample(x, t.worldPosition.y, z) : null;
- if (s) return s.surface[1];
- }
- return null;
+ return this.sample(x, 0, z)?.surface[1] ?? null;
+ }
+
+ /** The waves as they stand where the zone says they are `amp` high: the zone's, at that height, scaled by the weather. */
+ private waves(amp: number): WaveParams {
+ return { ...waveParamsOf(this.zone_), height: amp * weatherWaves(), count: this.quality.waves };
}
}
@@ -288,8 +195,36 @@ function outlineOf(d: WaterBodyData): Point2[] {
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 };
+/** × the waves' height the weather asks for now: 1 with no weather, or one that does not drive the wind. */
+function weatherWaves(): number {
+ const w = currentWeather();
+ return w && (currentWeatherDrive() & WeatherDrive.Wind) ? w.waves : 1;
+}
+
+/** How hard it rains on the water now (the weather's rain level), 0 with none or one that does not drive the rain. */
+function weatherRain(): number {
+ const w = currentWeather();
+ return w && (currentWeatherDrive() & WeatherDrive.Rain) ? w.rain : 0;
+}
+
+/** The zone's waves at unit height, scaled by the weather: what is drawn and what the surface answers both read this, times each place's height. */
+export function waveParamsOf(zone: Pick<WaterZoneData, 'waveLength' | 'waveSpeed' | 'waveDirection'>): WaveParams {
+ return { height: weatherWaves(), length: zone.waveLength, speed: zone.waveSpeed, direction: zone.waveDirection };
+}
+
+/**
+ * Rain on water that keeps ripples: drops over its window, as many a second as the weather's rain asks (110 at the rain preset's 1.1),
+ * each a dip a cell and a half across and a third of a cell deep, so a shower is a field of small rings whatever the window's scale.
+ */
+export function rainOnRipples(field: RippleField, dt: number): void {
+ const rain = weatherRain();
+ if (rain <= 0 || dt <= 0) return;
+ field.rainOwed += rain * 100 * dt;
+ const cell = field.size / field.n;
+ for (; field.rainOwed >= 1; field.rainOwed--) {
+ const x = field.originX + Math.random() * field.size, z = field.originZ + Math.random() * field.size;
+ field.disturb(x, z, cell * 1.5, -cell / 3);
+ }
}
type Quat = { x: number; y: number; z: number; w: number };
@@ -311,20 +246,67 @@ function fromLocal(t: TransformData, x: number, y: number, z: number, scale: num
return [r[0] + t.worldPosition.x, r[1] + t.worldPosition.y, r[2] + t.worldPosition.z];
}
-/** 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, ground: string, spline: SplineData | null): string {
- return JSON.stringify([d.form, d.sizeX, d.sizeZ, d.boundary, d.shoreWidth, d.cellSize, d.cells, d.rings, d.material, ground, d.form === WaterForm.River ? spline : null]);
+/** A river's stations in the world: a few to its narrowest width along its curve, each with its height, half its width, its heading and its current. */
+export function riverStations(curve: SplineCurve, flowSpeed: number, toWorld: (x: number, y: number, z: number) => [number, number, number],
+ turn: (x: number, y: number, z: number) => [number, number, number], scale: number): RiverStation[] {
+ let widest = 0, narrowest = Infinity;
+ for (let i = 0; i <= 64; i++) {
+ const w = curve.width((i / 64) * curve.length);
+ widest = Math.max(widest, w);
+ narrowest = Math.min(narrowest, w);
+ }
+ const step = Math.max(narrowest / 3, curve.length / 1024, 1e-3);
+ const count = Math.max(2, Math.ceil(curve.length / step) + 1);
+ const stations: RiverStation[] = [];
+ for (let i = 0; i < count; i++) {
+ const s = (i / (count - 1)) * curve.length;
+ const [px, py, pz] = curve.position(s);
+ const [x, y, z] = toWorld(px, py, pz);
+ const tangent = curve.tangent(s);
+ const [tx, , tz] = turn(tangent[0], 0, tangent[2]);
+ const run = Math.hypot(tx, tz) || 1;
+ const width = curve.width(s);
+ stations.push({ x, y, z, half: (width / 2) * scale, dx: tx / run, dz: tz / run, speed: flowSpeed * currentShare(width, widest) * 2 * scale });
+ }
+ return stations;
+}
+
+/** Everything the zone is baked from, as the scene says it now. */
+interface Inputs {
+ bodies: ZoneBody[];
+ grid: ZoneGrid;
+ zone: WaterZoneData;
+ /** What, changed, rebakes the field. */
+ key: string;
+}
+
+/** The surface the plugin draws: its mesh, its material instance and the textures it reads the field and the ripples from. */
+interface Surface {
+ entity: Entity;
+ mesh: number;
+ meshKey: string;
+ instance: number;
+ material: number;
+ heights: number;
+ field: number;
+ /** Which bake the textures hold. */
+ baked: WaterField | null;
+ ripple: number;
+ rippleBytes: Uint8Array | null;
+ epoch: number;
+ pending: boolean;
}
export class WaterPlugin implements Plugin {
name = 'water';
- /** The stock material every body without one of its own is an instance of, made once from the Water shader. */
+ /** The stock material the surface is an instance of when the zone names none, made once from the Water shader. */
private stock_ = 0;
- private stockPending_ = false;
-
- /** The resource this plugin installed, for the parts of it that read the quality level. */
+ /** The resource this plugin installed. */
private waters_: Waters = new Waters();
+ private key_ = '';
+ private surface_: Surface | null = null;
+ private epoch_ = 0;
build(app: App): void {
const waters = new Waters();
@@ -333,39 +315,38 @@ export class WaterPlugin implements Plugin {
app.insertResource(WatersRes, waters);
app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {
- this.sweep(app, waters);
const policy = app.hasResource(Quality) ? app.getResource(Quality) : null;
waters.quality = waterQualityOf(policy && policy.enabled ? policy.profile : null, isMiniGame());
- // What a body IS (its outline and shore, its curve) needs no renderer: it is built here whether or not anything is drawn, so a
- // server or a test that never draws can still ask the surface where it is. What is DRAWN waits for the asset layer.
- const rendering = app.hasResource(Assets);
- const time = app.getResource(Time).elapsed;
- const eye = rendering ? this.eye(app) : null;
- for (const entity of app.world.getEntitiesWithComponents([WaterBody, Transform])) {
- const data = app.world.get(entity, WaterBody) as WaterBodyData;
- const spline = data.form === WaterForm.River ? app.world.tryGet(entity, Spline) as SplineData | null : null;
- const signature = signatureOf(data, this.groundKey(app, entity, data), spline);
- let built = waters.built_.get(entity);
- if (!built || built.signature !== signature) {
- if (built) this.destroy(app, built);
- built = { signature, data: { ...data }, mesh: 0, field: null, curve: null, widest: 0, shoreTexture: 0, ripples: null, rippleTexture: 0, rippleBytes: null, child: 0 as Entity, instance: 0, epoch: (built?.epoch ?? 0) + 1, pending: false };
- waters.built_.set(entity, built);
- this.surface(app, entity, built);
- }
- built.data = { ...data };
- this.ripple(app, entity, built, eye ?? this.eye(app), app.getResource(Time).delta);
- if (!rendering) continue;
- if (!built.child && !built.pending) void this.build_(app, entity, built);
- if (built.child && built.instance) this.update(app, entity, built, eye, time);
+ // What the water IS (the baked field) needs no renderer: it is baked here whether or not anything is drawn, so a server or a test
+ // that never draws can still ask the surface where it is. What is DRAWN waits for the asset layer.
+ const inputs = this.gather(app);
+ waters.zone_ = inputs.zone;
+ if (inputs.bodies.length === 0) {
+ waters.field_ = null;
+ this.key_ = '';
+ this.dropRipples();
+ this.dropSurface(app);
+ return;
}
+ if (inputs.key !== this.key_ || !waters.field_) {
+ this.key_ = inputs.key;
+ waters.field_ = WaterField.bake(inputs.grid, inputs.bodies, this.ground(app));
+ }
+ const eye = this.eye(app);
+ this.ripple(app, inputs.zone, eye, app.getResource(Time).delta);
+ if (!app.hasResource(Assets)) return;
+ const surface = this.surface(app, inputs.zone);
+ if (surface.instance && surface.entity) this.update(app, surface, inputs.zone, eye ?? this.middle(inputs.grid));
}, { name: 'WaterSystem' }));
}
cleanup(app?: App): void {
if (!app?.hasResource(WatersRes)) return;
+ this.dropRipples();
+ this.dropSurface(app);
const waters = app.getResource(WatersRes);
- for (const built of waters.built_.values()) this.destroy(app, built);
- waters.built_.clear();
+ waters.field_ = null;
+ this.key_ = '';
if (this.stock_) Material.release(this.stock_);
this.stock_ = 0;
}
@@ -381,7 +362,71 @@ export class WaterPlugin implements Plugin {
return null;
}
- /** The material every body without one is an instance of: the Water shader, compiled once. */
+ /** The middle of the zone's region: where the surface and the ripples stay without a camera to follow. */
+ private middle(grid: ZoneGrid): [number, number, number] {
+ return [grid.minX + grid.sizeX / 2, 0, grid.minZ + grid.sizeZ / 2];
+ }
+
+ /**
+ * The bodies as the zone takes them, in the world, the zone's settings, and the region they are baked over: the `WaterZone`'s, or without
+ * one a region round every lake and river with a margin for their shores.
+ */
+ private gather(app: App): Inputs {
+ const bodies: ZoneBody[] = [];
+ const keyParts: unknown[] = [];
+ for (const entity of app.world.getEntitiesWithComponents([WaterBody, Transform])) {
+ const d = app.world.get(entity, WaterBody) as WaterBodyData;
+ const t = app.world.get(entity, Transform) as TransformData;
+ const scale = t.worldScale.y || 1;
+ const key = entity as number;
+ if (d.form === WaterForm.Ocean) {
+ bodies.push({ kind: 'ocean', key, level: t.worldPosition.y, waveHeight: d.waveHeight, shoreWidth: d.shoreWidth });
+ keyParts.push([key, d.form, t.worldPosition.y, d.waveHeight, d.shoreWidth]);
+ } else if (d.form === WaterForm.Lake) {
+ const outline = outlineOf(d);
+ bodies.push({
+ kind: 'lake', key, level: t.worldPosition.y, waveHeight: d.waveHeight, shoreWidth: d.shoreWidth * scale, outline,
+ toLocal: (x, z) => { const q = toLocal(t, x, t.worldPosition.y, z, scale); return [q[0], q[2]]; },
+ toWorld: (x, z) => { const w = fromLocal(t, x, 0, z, scale); return [w[0], w[2]]; },
+ });
+ keyParts.push([key, d.form, outline, d.waveHeight, d.shoreWidth, t.worldPosition, t.worldRotation, scale]);
+ } else if (d.form === WaterForm.River) {
+ const spline = app.world.tryGet(entity, Spline) as SplineData | null;
+ if (!spline || spline.points.length < 2) continue;
+ const curve = new SplineCurve(spline.points, spline.closed);
+ const stations = riverStations(curve, d.flowSpeed, (x, y, z) => fromLocal(t, x, y, z, scale), (x, y, z) => rotate(t.worldRotation, x, y, z), scale);
+ bodies.push({ kind: 'river', key, waveHeight: d.waveHeight, shoreWidth: d.shoreWidth * scale, stations });
+ keyParts.push([key, d.form, spline.points, spline.closed, d.flowSpeed, d.waveHeight, d.shoreWidth, t.worldPosition, t.worldRotation, scale]);
+ }
+ }
+ let zone = ZONE_DEFAULTS;
+ let grid: ZoneGrid | null = null;
+ for (const entity of app.world.getEntitiesWithComponents([WaterZone, Transform])) {
+ zone = app.world.get(entity, WaterZone) as WaterZoneData;
+ const t = app.world.get(entity, Transform) as TransformData;
+ grid = gridOver(t.worldPosition.x - zone.sizeX / 2, t.worldPosition.z - zone.sizeZ / 2, zone.sizeX, zone.sizeZ, zone.resolution);
+ break;
+ }
+ if (!grid) {
+ grid = implicitGrid(bodies, zone);
+ // The surface without a zone of its own reaches over the whole region from wherever the camera is in it: its cells grow with the region.
+ const reach = oceanReach(zone.cells, zone.rings, zone.cellSize), need = Math.max(grid.sizeX, grid.sizeZ);
+ if (reach < need) zone = { ...zone, cellSize: zone.cellSize * (need / reach) };
+ }
+ const terrain = app.hasResource(TerrainsRes) ? app.getResource(TerrainsRes) : null;
+ const ground = terrain && terrain.built_.size > 0 ? terrain.revision_ : -1;
+ return { bodies, grid, zone, key: JSON.stringify([keyParts, grid, ground]) };
+ }
+
+ /** The world height of the ground, where a terrain is built. */
+ private ground(app: App): ZoneGround | undefined {
+ if (!app.hasResource(TerrainsRes)) return undefined;
+ const terrains = app.getResource(TerrainsRes);
+ if (terrains.built_.size === 0) return undefined;
+ return (x, z) => terrains.heightAt(x, z);
+ }
+
+ /** The material the surface is an instance of when the zone names none: the Water shader, compiled once. */
private async stock(app: App): Promise<number> {
if (this.stock_) return this.stock_;
const assets = app.getResource(Assets);
@@ -395,151 +440,139 @@ export class WaterPlugin implements Plugin {
return this.stock_;
}
- private async build_(app: App, entity: Entity, built: Built): Promise<void> {
- built.pending = true;
- const epoch = built.epoch;
+ /** The surface, made (or remade, where its mesh or its material changed) as the zone asks. */
+ private surface(app: App, zone: WaterZoneData): Surface {
+ const meshKey = JSON.stringify([zone.cells, zone.rings, zone.cellSize]);
+ let s = this.surface_;
+ if (s && (s.meshKey !== meshKey || s.material !== zone.material)) { this.dropSurface(app); s = null; }
+ if (!s) {
+ s = { entity: 0 as Entity, mesh: 0, meshKey, instance: 0, material: zone.material, heights: 0, field: 0, baked: null, ripple: 0, rippleBytes: null, epoch: ++this.epoch_, pending: false };
+ this.surface_ = s;
+ }
+ if (!s.entity && !s.pending) void this.build_(app, s, zone);
+ return s;
+ }
+
+ private async build_(app: App, s: Surface, zone: WaterZoneData): Promise<void> {
+ s.pending = true;
+ const epoch = s.epoch;
try {
- const source = built.data.material || await this.stock(app);
- if (built.epoch !== epoch || !app.world.valid(entity)) return;
- const d = built.data;
+ const source = zone.material || await this.stock(app);
+ if (s.epoch !== epoch || this.surface_ !== s) return;
const assets = app.getResource(Assets);
- let mesh: number;
- if (d.form === WaterForm.Ocean) {
- mesh = assets.createMesh(buildOceanMesh(d.cells, d.rings, d.cellSize));
- } else if (d.form === WaterForm.River) {
- // A river: the curve of the Spline on its entity, laid as a ribbon.
- if (!built.curve) return;
- const across = Math.min(64, Math.max(2, Math.ceil(built.widest / Math.max(d.cellSize, 0.05))));
- mesh = assets.createMesh(buildRiverMesh(built.curve, d.cellSize, across));
- } else {
- // A lake: cut to its outline, calmer toward its shore.
- const field = built.field;
- if (!field) return;
- 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,
- }));
- }
+ const mesh = assets.createMesh(buildOceanMesh(zone.cells, zone.rings, zone.cellSize));
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, {
+ s.mesh = mesh;
+ s.instance = instance;
+ this.waters_.instance_ = instance;
+ const entity = app.world.spawn('Water');
+ app.world.insert(entity, Transform, { position: { x: 0, y: 0, z: 0 } });
+ app.world.insert(entity, MeshRenderer, {
mesh, material: instance, lit: true, opaque: false, cullBackfaces: false, color: { r: 1, g: 1, b: 1, a: 1 },
} as Partial<MeshRendererData>);
- app.world.setParent(child, entity);
- built.child = child;
+ s.entity = entity;
} catch (e) {
log.error('water', 'building the water failed', e);
} finally {
- built.pending = false;
+ s.pending = false;
}
}
- /** What a body is, apart from how it is drawn: a lake's outline with its shore and depth, a river's curve with its widest reach. */
- private surface(app: App, entity: Entity, built: Built): void {
- const d = built.data;
- built.field = null;
- built.curve = null;
- built.widest = 0;
- if (d.form === WaterForm.River) {
- const spline = app.world.tryGet(entity, Spline) as SplineData | null;
- if (!spline || spline.points.length < 2) { log.warn('water', 'a river needs a Spline of two points or more on its entity'); return; }
- built.curve = new SplineCurve(spline.points, spline.closed);
- for (let i = 0; i <= 64; i++) built.widest = Math.max(built.widest, built.curve.width((i / 64) * built.curve.length));
- } else if (d.form === WaterForm.Lake) {
- 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));
- }
+ /** Puts the baked field where the shader reads it: the heights texel by texel, the rest filtered. */
+ private upload(app: App, s: Surface, field: WaterField): void {
+ this.dropFieldTextures(s);
+ const ranges = field.ranges();
+ const { heights, field: rest } = field.encode(ranges);
+ const { nx, nz, minX, minZ, sizeX, sizeZ } = field.grid;
+ const empty = nx < 2 || nz < 2;
+ const w = empty ? 2 : nx, h = empty ? 2 : nz;
+ s.heights = createTextureFromPixels(app.wasmModule, { width: w, height: h, pixels: empty ? new Uint8Array(16) : heights }, TextureContent.Retained, false,
+ { filterMode: 'nearest', wrapMode: 'clamp', srgb: false });
+ s.field = createTextureFromPixels(app.wasmModule, { width: w, height: h, pixels: empty ? new Uint8Array(16) : rest }, TextureContent.Retained, false,
+ { filterMode: 'linear', wrapMode: 'clamp', srgb: false });
+ s.baked = field;
+ const set = (name: string, value: Parameters<typeof Material.setUniform>[2]): void => { Material.setUniform(s.instance, name, value); };
+ set('u_zoneHeights', Material.tex(s.heights));
+ set('u_zoneField', Material.tex(s.field));
+ // A region of nothing is put where no point is: everything is past it, which is the ocean.
+ set('u_zoneOrigin', empty ? { x: 1e9, y: 1e9 } : { x: minX, y: minZ });
+ set('u_zoneSize', empty ? { x: 1e-4, y: 1e-4 } : { x: sizeX, y: sizeZ });
+ set('u_zoneHeight', { x: ranges.heightMin, y: ranges.heightSpan });
+ set('u_zoneRange', { x: ranges.shore, y: ranges.amp, z: ranges.flow, w: ranges.depth });
+ set('u_zoneOn', 1);
}
- /** 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 zone into the instance, and moves the surface to the camera on the lattice its rings line up on. */
+ private update(app: App, s: Surface, zone: WaterZoneData, eye: [number, number, number]): void {
+ const field = this.waters_.field_!;
+ if (s.baked !== field) this.upload(app, s, field);
+ const snap = oceanSnap(zone.rings, zone.cellSize);
+ const ox = Math.round(eye[0] / snap) * snap, oz = Math.round(eye[2] / snap) * snap;
+ const t = app.world.get(s.entity, Transform) as TransformData;
+ if (t.position.x !== ox || t.position.z !== oz) app.world.insert(s.entity, Transform, { ...t, position: { x: ox, y: 0, z: oz } });
+ const set = (name: string, value: number | { x: number; y: number }): void => { Material.setUniform(s.instance, name, value); };
+ const q = this.waters_.quality;
+ const ocean = field.ocean;
+ const waves = waveParamsOf(zone);
+ set('u_waveCount', q.waves);
+ set('u_mirror', q.mirror ? 1 : 0);
+ set('u_causticOn', q.caustics ? 1 : 0);
+ set('u_waveSpace', 1);
+ set('u_origin', { x: ox, y: oz });
+ set('u_cellSize', zone.cellSize);
+ set('u_geoWaves', q.displacement ? 1 : 0);
+ set('u_waveHeight', waves.height);
+ set('u_waveLength', waves.length);
+ set('u_waveSpeed', waves.speed);
+ set('u_waveDirection', waves.direction);
+ set('u_oceanOn', ocean ? 1 : 0);
+ set('u_oceanLevel', ocean ? ocean.level : 0);
+ set('u_oceanWaves', ocean ? ocean.waveHeight : 0);
}
/**
- * Keeps a body's ripples: makes the grid when `ripples` asks for one, moves its window to the camera, steps it, and (where drawn) puts it where the shader reads it.
+ * Keeps the zone's ripples: makes the grid when `ripples` asks for one, moves its window to the camera, steps it, and (where drawn) puts it where the shader reads it.
* It runs headless too, so the surface a test or a server asks about has them.
*/
- private ripple(app: App, entity: Entity, built: Built, eye: [number, number, number] | null, dt: number): void {
- const d = built.data;
- if (d.ripples <= 0 || this.waters_.quality.rippleCells <= 0) { this.dropRipples(built); return; }
- // The level holds the grid to its own side; a body that asks for more gets the level's.
- const n = Math.max(8, Math.floor(Math.min(d.ripples, this.waters_.quality.rippleCells))), size = Math.max(d.rippleSize, 1e-3);
- if (!built.ripples || built.ripples.n !== n || built.ripples.size !== size) {
- this.dropRipples(built);
- built.ripples = new RippleField(n, size);
- // Until a camera says otherwise a body keeps its window over its middle.
- built.ripples.recenter(built.field ? built.field.minX + built.field.sizeX / 2 : 0, built.field ? built.field.minZ + built.field.sizeZ / 2 : 0);
- }
- const field = built.ripples;
- const t = app.world.tryGet(entity, Transform) as TransformData | null;
- if (t && eye) {
- const q = toLocal(t, eye[0], eye[1], eye[2], t.worldScale.y || 1);
- field.recenter(q[0], q[2]);
+ private ripple(app: App, zone: WaterZoneData, eye: [number, number, number] | null, dt: number): void {
+ const waters = this.waters_;
+ if (zone.ripples <= 0 || waters.quality.rippleCells <= 0) { this.dropRipples(); return; }
+ // The level holds the grid to its own side; a zone that asks for more gets the level's.
+ const n = Math.max(8, Math.floor(Math.min(zone.ripples, waters.quality.rippleCells))), size = Math.max(zone.rippleSize, 1e-3);
+ if (!waters.ripples_ || waters.ripples_.n !== n || waters.ripples_.size !== size) {
+ this.dropRipples();
+ waters.ripples_ = new RippleField(n, size);
+ const grid = waters.field_!.grid;
+ waters.ripples_.recenter(grid.minX + grid.sizeX / 2, grid.minZ + grid.sizeZ / 2);
}
- field.step(Math.min(Math.max(dt, 0), 0.1), d.rippleSpeed, d.rippleDamping, d.foamFade);
- if (!built.instance || !app.hasResource(Assets)) return;
- const range = this.rippleRange(d);
+ const field = waters.ripples_;
+ if (eye) field.recenter(eye[0], eye[2]);
+ const step = Math.min(Math.max(dt, 0), 0.1);
+ rainOnRipples(field, step);
+ field.step(step, zone.rippleSpeed, zone.rippleDamping, zone.foamFade);
+ const s = this.surface_;
+ if (!s || !s.instance || !app.hasResource(Assets)) return;
+ // The height the grid holds and its encoding spans either side of rest: twice the tallest waves, or a fiftieth of the window where the water is calm.
+ const range = Math.max((waters.field_ ? waters.field_.ranges().amp : 0) * weatherWaves() * 2, zone.rippleSize * 0.02);
field.limit = range;
- const bytes = field.encode(range, built.rippleBytes ?? undefined);
- built.rippleBytes = bytes;
- if (!built.rippleTexture) {
- built.rippleTexture = createTextureFromPixels(app.wasmModule, { width: n, height: n, pixels: bytes }, TextureContent.Retained, false,
- { filterMode: 'linear', wrapMode: 'clamp' });
- const handle = built.rippleTexture;
+ const bytes = field.encode(range, s.rippleBytes ?? undefined);
+ s.rippleBytes = bytes;
+ if (!s.ripple) {
+ s.ripple = createTextureFromPixels(app.wasmModule, { width: n, height: n, pixels: bytes }, TextureContent.Retained, false,
+ { filterMode: 'linear', wrapMode: 'clamp', srgb: false });
+ const handle = s.ripple;
provideTextureContent(handle, () => {
- if (built.rippleTexture !== handle || !built.rippleBytes) return false;
- updateTextureSubregion(app.wasmModule, handle, 0, 0, n, n, built.rippleBytes);
+ if (s.ripple !== handle || !s.rippleBytes) return false;
+ updateTextureSubregion(app.wasmModule, handle, 0, 0, n, n, s.rippleBytes);
return true;
});
- Material.setUniform(built.instance, 'u_rippleMap', Material.tex(handle));
+ Material.setUniform(s.instance, 'u_rippleMap', Material.tex(handle));
} else {
- updateTextureSubregion(app.wasmModule, built.rippleTexture, 0, 0, n, n, bytes);
+ updateTextureSubregion(app.wasmModule, s.ripple, 0, 0, n, n, bytes);
}
- const set = (name: string, value: number | { x: number; y: number }): void => { Material.setUniform(built.instance, name, value); };
+ const set = (name: string, value: number | { x: number; y: number }): void => { Material.setUniform(s.instance, name, value); };
set('u_rippleOn', 1);
set('u_rippleOrigin', { x: field.originX, y: field.originZ });
set('u_rippleSize', field.size);
@@ -547,75 +580,78 @@ export class WaterPlugin implements Plugin {
set('u_rippleRange', range);
}
- /** The height the grid holds and its encoding spans either side of rest: twice the waves' height, or a fiftieth of the window where the water is calm. */
- private rippleRange(d: WaterBodyData): number {
- return Math.max(d.waveHeight * 2, d.rippleSize * 0.02);
- }
-
- private dropRipples(built: Built): void {
- if (built.rippleTexture) {
- withdrawTextureContent(built.rippleTexture);
- getResourceManager()?.releaseTexture(built.rippleTexture);
+ private dropRipples(): void {
+ const s = this.surface_;
+ if (s?.ripple) {
+ withdrawTextureContent(s.ripple);
+ getResourceManager()?.releaseTexture(s.ripple);
+ }
+ if (s) {
+ s.ripple = 0;
+ s.rippleBytes = null;
+ if (s.instance) Material.setUniform(s.instance, 'u_rippleOn', 0);
}
- built.rippleTexture = 0;
- built.rippleBytes = null;
- built.ripples = null;
- if (built.instance) Material.setUniform(built.instance, 'u_rippleOn', 0);
+ this.waters_.ripples_ = null;
}
- /** 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;
- let ox = 0, oz = 0;
- if (d.form === WaterForm.Ocean && eye) {
- const t = app.world.get(entity, Transform) as TransformData;
- const q = toLocal(t, eye[0], eye[1], eye[2], t.worldScale.y || 1);
- const snap = oceanSnap(d.rings, d.cellSize);
- ox = Math.round(q[0] / snap) * snap;
- oz = Math.round(q[2] / snap) * snap;
- }
- const child = app.world.get(built.child, Transform) as TransformData;
- if (child.position.x !== ox || child.position.z !== oz) {
- app.world.insert(built.child, Transform, { ...child, position: { x: ox, y: 0, z: oz } });
- }
- const set = (name: string, value: number | { x: number; y: number }): void => { Material.setUniform(built.instance, name, value); };
- const q = this.waters_.quality;
- set('u_waveCount', q.waves);
- set('u_mirror', q.mirror ? 1 : 0);
- set('u_causticOn', q.caustics ? 1 : 0);
- set('u_waveSpace', 1);
- set('u_origin', { x: ox, y: oz });
- set('u_cellSize', d.cellSize);
- set('u_flowSpeed', d.form === WaterForm.River ? d.flowSpeed : 0);
- set('u_geoWaves', d.form === WaterForm.River || !q.displacement ? 0 : 1);
- set('u_waveHeight', d.waveHeight);
- set('u_waveLength', d.waveLength);
- set('u_waveSpeed', d.waveSpeed);
- set('u_waveDirection', d.waveDirection);
- void time;
+ private dropFieldTextures(s: Surface): void {
+ const rm = getResourceManager();
+ if (s.heights) rm?.releaseTexture(s.heights);
+ if (s.field) rm?.releaseTexture(s.field);
+ s.heights = 0;
+ s.field = 0;
+ s.baked = null;
}
- private destroy(app: App, built: Built): void {
- built.epoch++;
- if (built.child && app.world.valid(built.child)) app.world.despawn(built.child);
- this.dropRipples(built);
- if (built.instance) Material.release(built.instance);
- if (built.shoreTexture) getResourceManager()?.releaseTexture(built.shoreTexture);
- built.shoreTexture = 0;
- if (built.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(built.mesh);
- built.child = 0 as Entity;
- built.instance = 0;
- built.mesh = 0;
+ private dropSurface(app: App): void {
+ const s = this.surface_;
+ if (!s) return;
+ s.epoch = ++this.epoch_;
+ this.surface_ = null;
+ if (s.entity && app.world.valid(s.entity)) app.world.despawn(s.entity);
+ if (s.ripple) { withdrawTextureContent(s.ripple); getResourceManager()?.releaseTexture(s.ripple); }
+ this.waters_.ripples_ = null;
+ this.dropFieldTextures(s);
+ if (s.instance) Material.release(s.instance);
+ if (s.mesh && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(s.mesh);
+ this.waters_.instance_ = 0;
}
+}
- /** Releases the geometry of a body whose entity is gone. */
- private sweep(app: App, waters: Waters): void {
- for (const [entity, built] of waters.built_) {
- if (app.world.valid(entity) && app.world.has(entity, WaterBody)) continue;
- this.destroy(app, built);
- waters.built_.delete(entity);
+/** A region from (minX, minZ), `sizeX` by `sizeZ`, with `resolution` texels along its longer side. */
+function gridOver(minX: number, minZ: number, sizeX: number, sizeZ: number, resolution: number): ZoneGrid {
+ const longer = Math.max(sizeX, sizeZ, 1e-3);
+ const res = Math.max(2, Math.round(resolution));
+ return { minX, minZ, sizeX, sizeZ, nx: Math.max(2, Math.round((res * sizeX) / longer)), nz: Math.max(2, Math.round((res * sizeZ) / longer)) };
+}
+
+/**
+ * The region a scene without a `WaterZone` is baked over: round every lake and river, with a margin of their shores and a few texels, at half
+ * the surface's finest cell to a texel (no finer than 32 texels along its longer side, no coarser than 1024). None, when there is only an ocean.
+ */
+function implicitGrid(bodies: readonly ZoneBody[], zone: WaterZoneData): ZoneGrid {
+ let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity, margin = 0;
+ for (const b of bodies) {
+ if (b.kind === 'ocean') continue;
+ margin = Math.max(margin, b.shoreWidth);
+ if (b.kind === 'river') {
+ for (const s of b.stations) {
+ minX = Math.min(minX, s.x - s.half); maxX = Math.max(maxX, s.x + s.half);
+ minZ = Math.min(minZ, s.z - s.half); maxZ = Math.max(maxZ, s.z + s.half);
+ }
+ } else {
+ for (const p of b.outline) {
+ const [x, z] = b.toWorld(p.x, p.y);
+ minX = Math.min(minX, x); maxX = Math.max(maxX, x);
+ minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z);
+ }
}
}
+ if (!Number.isFinite(minX)) return { minX: 0, minZ: 0, sizeX: 0, sizeZ: 0, nx: 0, nz: 0 };
+ const longer = Math.max(maxX - minX, maxZ - minZ);
+ const res = Math.min(1024, Math.max(32, Math.ceil(longer / Math.max(zone.cellSize * 0.5, 1e-3))));
+ const pad = margin + (longer / res) * 4;
+ return gridOver(minX - pad, minZ - pad, maxX - minX + pad * 2, maxZ - minZ + pad * 2, res);
}
export const waterPlugin: Plugin = new WaterPlugin();
diff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.ts
index 5a37b4943..49045d20d 100644
--- a/sdk/src/water/waterShader.ts
+++ b/sdk/src/water/waterShader.ts
@@ -41,38 +41,42 @@ const WATER = `#pragma shader "Water"
#pragma param u_foamCrest float default(0.5) range(0,1) ui(slider)
// The depth taken where the device could not measure one.
#pragma param u_fallbackDepth float default(4) range(0,200) ui(slider)
-// Where the waves are measured. 0 is the world's xz plane, which is what a flat plane of water wants. 1 is the body's own space: the mesh's uv is its
-// local x and z (plus u_origin, which a body that follows the camera moves so the waves stay put), and the waves then lift the geometry and follow the
-// body's tilt, which is what the WaterBody component builds.
+// Where the waves are measured. 0 is the world's xz plane, which is what a plain mesh of water wants. 1 is the surface a WaterZone draws: the mesh's uv
+// is its x and z (plus u_origin, which the zone moves as the mesh follows the camera, so the waves stay put in the world), and the vertices are lifted
+// to the zone's water and its waves.
#pragma param u_waveSpace float default(0) range(0,1) ui(slider)
#pragma param u_origin vec2 default(0,0)
-// 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.
+// The cell size of the mesh's finest ring: 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)
-// A river's current: how fast it runs (world units a second, 0 for still water) along the direction the mesh's vertex colour gives (red and green) at the speed
-// its blue says (half is the nominal), and how long, in seconds, each of the two copies of the surface the shader carries downstream lives before the other takes over.
-#pragma param u_flowSpeed float default(0) range(0,50) ui(slider)
+// A WaterZone's baked water (zone.ts encode): heights texel by texel (rg height over u_zoneHeight, b depth, a waves' height), field filtered
+// (r shore distance, 0.5 at it; gb current; a calm share), over u_zoneRange (shore, waves, current, depth). Below the shore there is no
+// water; past the region there is the ocean where u_oceanOn says so.
+#pragma param u_zoneOn float default(0) range(0,1) ui(slider)
+#pragma param u_zoneHeights texture default(white) texel(data)
+#pragma param u_zoneField texture default(white) texel(data)
+#pragma param u_zoneOrigin vec2 default(0,0)
+#pragma param u_zoneSize vec2 default(1,1)
+#pragma param u_zoneHeight vec2 default(0,1)
+#pragma param u_zoneRange vec4 default(16,1,1,16)
+#pragma param u_oceanOn float default(0) range(0,1) ui(slider)
+#pragma param u_oceanLevel float default(0) range(-100000,100000) ui(slider)
+#pragma param u_oceanWaves float default(1) range(0,100) ui(slider)
+// How long, in seconds, each of the two copies of the surface the shader carries down a current lives before the other takes over.
#pragma param u_flowCycle float default(2) range(0.2,20) ui(slider)
-// How much of the waves lifts the geometry: 1 for a lake or an ocean, 0 for a river, whose surface is drawn flat and moved only in the shading.
+// How much of the waves lifts the geometry: 0 draws the surface flat and moves it only in the shading (the lite water).
#pragma param u_geoWaves float default(1) range(0,1) ui(slider)
// The net of light the waves throw on what is under the water: how strong it is, how large one cell of it is (world units), and how fast it swims. The Underwater
// effect draws the same one from below, with these numbers, so the two halves of the picture agree.
#pragma param u_causticStrength float default(0.6) range(0,3) ui(slider)
#pragma param u_causticScale float default(2) range(0.05,2000) ui(slider)
#pragma param u_causticSpeed float default(0.35) range(0,4) ui(slider)
-// What the quality level allows (the WaterBody component writes these): how many of the four waves are summed, whether the surface seen from below mirrors the world under it,
+// What the quality level allows (the WaterZone writes these): how many of the four waves are summed, whether the surface seen from below mirrors the world under it,
// and whether the sun's web of light is drawn on what lies under the water.
#pragma param u_waveCount float default(4) range(1,4) ui(slider)
#pragma param u_mirror float default(1) range(0,1) ui(slider)
#pragma param u_causticOn float default(1) range(0,1) ui(slider)
-// The disturbance the water keeps (WaterBody ripples): a window of the body's xz plane, red the height of the ripples (0.5 at rest, u_rippleRange above or below at 1 and 0)
+// The disturbance the water keeps (WaterZone ripples): a window of the xz plane, red the height of the ripples (0.5 at rest, u_rippleRange above or below at 1 and 0)
// and green the foam they left, as the CPU stepped them. u_rippleSize is the window's side, u_rippleTexel one texel of it.
#pragma param u_rippleOn float default(0) range(0,1) ui(slider)
#pragma param u_rippleMap texture default(white) texel(data)
@@ -102,11 +106,30 @@ float waterWaveHeight(vec2 p, float time, float cell) {
}
return height;
}
+// The zone's water at p: its surface's height, its depth and how high its waves stand, each texel decoded before the four about p are blended
+// (bytes blended are no number). Past the region: the ocean's, where there is one.
+vec3 waterZoneAt(vec2 p) {
+ vec2 uv = (p - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));
+ bool inside = all(greaterThanEqual(uv, vec2(0.0))) && all(lessThanEqual(uv, vec2(1.0)));
+ ivec2 size = textureSize(u_zoneHeights, 0);
+ vec2 f = clamp(uv, 0.0, 1.0) * vec2(size - 1);
+ ivec2 i = min(ivec2(floor(f)), max(size - 2, ivec2(0)));
+ vec2 t = f - vec2(i);
+ vec4 a = texelFetch(u_zoneHeights, i, 0), b = texelFetch(u_zoneHeights, i + ivec2(1, 0), 0);
+ vec4 c = texelFetch(u_zoneHeights, i + ivec2(0, 1), 0), d = texelFetch(u_zoneHeights, i + ivec2(1, 1), 0);
+ vec4 ha = vec4(a.r * 65280.0 + a.g * 255.0, b.r * 65280.0 + b.g * 255.0, c.r * 65280.0 + c.g * 255.0, d.r * 65280.0 + d.g * 255.0) / 65535.0;
+ float h = mix(mix(ha.x, ha.y, t.x), mix(ha.z, ha.w, t.x), t.y);
+ vec2 da = mix(mix(a.ba, b.ba, t.x), mix(c.ba, d.ba, t.x), t.y);
+ vec3 zone = vec3(u_zoneHeight.x + h * u_zoneHeight.y, da.x * u_zoneRange.w, da.y * u_zoneRange.y);
+ return !inside && u_oceanOn > 0.5 ? vec3(u_oceanLevel, 1e6, u_oceanWaves) : zone;
+}
void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
if (u_waveSpace < 0.5) return;
+ vec2 p = uv + u_origin;
float cell = u_cellSize > 0.0 ? u_cellSize * exp2(es_vertexColor.r * 7.0) : 0.0;
- float damp = u_shoreOn > 0.5 ? es_vertexColor.g : 1.0;
- local.y += waterWaveHeight(uv + u_origin, u_time.x, cell) * damp * u_geoWaves;
+ // The water's rest height there and how high its waves stand (a multiple of u_waveHeight, which the zone sets to the weather's).
+ vec3 zone = u_zoneOn > 0.5 ? waterZoneAt(p) : vec3(0.0, 0.0, 1.0);
+ local.y += zone.x + waterWaveHeight(p, u_time.x, cell) * zone.z * u_geoWaves;
}
#pragma end
@@ -129,13 +152,31 @@ fn waterWaveHeight(p : vec2f, time : f32, cell : f32) -> f32 {
}
return height;
}
+fn waterZoneAt(p : vec2f) -> vec3f {
+ let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));
+ let inside = all(uv >= vec2f(0.0)) && all(uv <= vec2f(1.0));
+ let size = vec2i(textureDimensions(u_zoneHeights, 0));
+ let f = clamp(uv, vec2f(0.0), vec2f(1.0)) * vec2f(size - vec2i(1));
+ let i = min(vec2i(floor(f)), max(size - vec2i(2), vec2i(0)));
+ let t = f - vec2f(i);
+ let a = textureLoad(u_zoneHeights, i, 0);
+ let b = textureLoad(u_zoneHeights, i + vec2i(1, 0), 0);
+ let c = textureLoad(u_zoneHeights, i + vec2i(0, 1), 0);
+ let d = textureLoad(u_zoneHeights, i + vec2i(1, 1), 0);
+ let ha = vec4f(a.r * 65280.0 + a.g * 255.0, b.r * 65280.0 + b.g * 255.0, c.r * 65280.0 + c.g * 255.0, d.r * 65280.0 + d.g * 255.0) / 65535.0;
+ let h = mix(mix(ha.x, ha.y, t.x), mix(ha.z, ha.w, t.x), t.y);
+ let da = mix(mix(a.ba, b.ba, t.x), mix(c.ba, d.ba, t.x), t.y);
+ if (!inside && mc.u_oceanOn > 0.5) { return vec3f(mc.u_oceanLevel, 1e6, mc.u_oceanWaves); }
+ return vec3f(mc.u_zoneHeight.x + h * mc.u_zoneHeight.y, da.x * mc.u_zoneRange.w, da.y * mc.u_zoneRange.y);
+}
fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {
if (mc.u_waveSpace < 0.5) { return; }
+ let p = uv + mc.u_origin;
var cell = 0.0;
if (mc.u_cellSize > 0.0) { cell = mc.u_cellSize * exp2(es_vertexColor.r * 7.0); }
- 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 * mc.u_geoWaves;
+ var zone = vec3f(0.0, 0.0, 1.0);
+ if (mc.u_zoneOn > 0.5) { zone = waterZoneAt(p); }
+ (*local).y = (*local).y + zone.x + waterWaveHeight(p, tc.u_time.x, cell) * zone.z * mc.u_geoWaves;
}
#pragma end
@@ -210,6 +251,23 @@ vec2 waveSlope(vec2 p, float time, float dist, out float crest) {
}
${CAUSTICS_GLSL}
+// The zone's water at p: its surface's height, its depth and how high its waves stand, each texel decoded before the four about p are blended
+// (bytes blended are no number). Past the region: the ocean's, where there is one.
+vec3 waterZoneAt(vec2 p) {
+ vec2 uv = (p - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));
+ bool inside = all(greaterThanEqual(uv, vec2(0.0))) && all(lessThanEqual(uv, vec2(1.0)));
+ ivec2 size = textureSize(u_zoneHeights, 0);
+ vec2 f = clamp(uv, 0.0, 1.0) * vec2(size - 1);
+ ivec2 i = min(ivec2(floor(f)), max(size - 2, ivec2(0)));
+ vec2 t = f - vec2(i);
+ vec4 a = texelFetch(u_zoneHeights, i, 0), b = texelFetch(u_zoneHeights, i + ivec2(1, 0), 0);
+ vec4 c = texelFetch(u_zoneHeights, i + ivec2(0, 1), 0), d = texelFetch(u_zoneHeights, i + ivec2(1, 1), 0);
+ vec4 ha = vec4(a.r * 65280.0 + a.g * 255.0, b.r * 65280.0 + b.g * 255.0, c.r * 65280.0 + c.g * 255.0, d.r * 65280.0 + d.g * 255.0) / 65535.0;
+ float h = mix(mix(ha.x, ha.y, t.x), mix(ha.z, ha.w, t.x), t.y);
+ vec2 da = mix(mix(a.ba, b.ba, t.x), mix(c.ba, d.ba, t.x), t.y);
+ vec3 zone = vec3(u_zoneHeight.x + h * u_zoneHeight.y, da.x * u_zoneRange.w, da.y * u_zoneRange.y);
+ return !inside && u_oceanOn > 0.5 ? vec3(u_oceanLevel, 1e6, u_oceanWaves) : zone;
+}
/// The first directional light that shines: xyz is where it stands in the sky, w 1 if there is one, color its colour and strength, tiles its place in the shadow atlas.
void waterSun(out vec4 dir, out vec4 color, out ivec2 tiles) {
dir = vec4(0.0);
@@ -269,14 +327,16 @@ vec4 waterReflect(vec3 p, vec3 r, float eyeDist) {
return vec4(0.0);
}
-/// The slope of the surface at p and how near it is to a crest: the waves, and the ripples they carry, flattened with distance.
-vec2 waterSurface(vec2 p, float time, float dist, out float crest) {
- vec2 slope = waveSlope(p, time, dist, crest);
+/// The slope of the surface at p and how near it is to a crest: the waves, amp times as high as u_waveHeight says, and the ripples they carry,
+/// calm of their strength, flattened with distance.
+vec2 waterSurface(vec2 p, float time, float dist, float amp, float calm, out float crest) {
+ vec2 slope = waveSlope(p, time, dist, crest) * amp;
+ crest *= calm;
float rippleFade = clamp(1.0 - dist / (u_rippleLength * 180.0), 0.0, 1.0);
float e = u_rippleLength * 0.1;
vec2 ripple = vec2(ripples(p + vec2(e, 0.0), time) - ripples(p - vec2(e, 0.0), time),
ripples(p + vec2(0.0, e), time) - ripples(p - vec2(0.0, e), time)) / (2.0 * e);
- return slope + ripple * (u_rippleStrength * u_rippleLength * rippleFade);
+ return slope + ripple * (u_rippleStrength * u_rippleLength * rippleFade * calm);
}
void main() {
@@ -291,11 +351,18 @@ 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;
+ // The zone's water at this pixel (texture reads, taken before any branch): how far in from the shore, how deep, how high the waves, the current.
+ vec2 zoneUv = (wp - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));
+ vec4 zoneTex = texture(u_zoneField, clamp(zoneUv, vec2(0.0), vec2(1.0)));
+ vec3 zone = waterZoneAt(wp);
+ bool zoneIn = all(greaterThanEqual(zoneUv, vec2(0.0))) && all(lessThanEqual(zoneUv, vec2(1.0)));
+ bool zoneOn = u_zoneOn > 0.5 && u_waveSpace > 0.5;
+ float shoreDist = !zoneOn ? 1e6 : zoneIn ? (zoneTex.r - 0.5) * 2.0 * u_zoneRange.x : u_oceanOn > 0.5 ? 1e6 : -1.0;
+ float shoreDepth = zoneOn ? zone.y : 1e6;
+ // How high the waves stand (a multiple of u_waveHeight), and the share of them kept toward the shore, which calms the small ripples and the crests too.
+ float damp = zoneOn ? zone.z : 1.0;
+ float calm = !zoneOn ? 1.0 : zoneIn ? zoneTex.a : 1.0;
+ vec2 flow = zoneOn && zoneIn ? (zoneTex.gb - 0.5) * 2.0 * u_zoneRange.z : vec2(0.0);
// The ripples at this pixel: their height on four sides gives the slope they add, and the foam is what they left (reads taken before any branch).
vec2 ripUv = (wp - u_rippleOrigin) / max(u_rippleSize, 1e-4);
vec4 ripC = texture(u_rippleMap, ripUv);
@@ -308,31 +375,28 @@ void main() {
float ripFoam = ripIn ? ripC.g : 0.0;
float crest;
vec2 slope;
- if (u_flowSpeed > 0.0) {
- // A river: the surface rides the current. Two copies of it are carried downstream a cycle at a time, each fading in as the other fades
+ if (dot(flow, flow) > 1e-6) {
+ // A current: the surface rides it. Two copies of it are carried downstream a cycle at a time, each fading in as the other fades
// out, so the moment one is put back at its start is hidden by the other.
- vec2 flow = (v_color.rg * 2.0 - 1.0) * (v_color.b * 2.0) * u_flowSpeed;
float cycle = max(u_flowCycle, 0.1);
float ph0 = fract(time / cycle);
float ph1 = fract(time / cycle + 0.5);
float w0 = 1.0 - abs(2.0 * ph0 - 1.0);
float crest0, crest1;
- vec2 s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, crest0);
- vec2 s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, crest1);
+ vec2 s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, damp, calm, crest0);
+ vec2 s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, damp, calm, crest1);
slope = mix(s1, s0, w0);
crest = mix(crest1, crest0, w0);
} else {
- slope = waterSurface(wp, time, waterDist, crest);
+ slope = waterSurface(wp, time, waterDist, damp, calm, crest);
}
- slope *= damp;
- crest *= damp;
slope += ripSlope;
vec3 N = normalize(vec3(-slope.x, 1.0, -slope.y));
vec3 Ngeo = vec3(0.0, 1.0, 0.0);
#ifdef MESH_NORMALS
if (u_waveSpace > 0.5) {
- // The body's own frame: the mesh's normal is its up (the hook lifts the vertices and leaves it alone), and the slope leans along
- // its uv axes, which are its local x and z.
+ // The zone's surface: the mesh's normal is up (the hook lifts the vertices and leaves it alone), and the slope leans along its uv
+ // axes, which are x and z.
Ngeo = normalize(v_worldNormal);
N = perturbNormal(Ngeo, P, v_texCoord, normalize(vec3(-slope.x, -slope.y, 1.0)));
}
@@ -397,8 +461,8 @@ 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) {
+ // The baked shore foams too, where the depth buffer cannot say (no chain, no float targets) and along the outline the zone traced.
+ if (zoneOn && 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;
@@ -425,11 +489,12 @@ void main() {
mirror = met.a > 0.5 ? met.rgb : mix(u_shallowColor.rgb, u_deepColor.rgb, 0.5) * 0.25;
}
seen += mirror * fresnel * (1.0 - foam);
- // Outside the lake's outline there is no water.
- if (u_shoreOn > 0.5 && shoreDist < 0.0) discard;
+ // Past the shore there is no water.
+ if (shoreDist < 0.0) discard;
fragColor = vec4(lit + seen, haveColor ? 1.0 : 0.85);
#ifdef ES_GBUFFER
- fragSurface = vec4(packNormal(normalize(N)), roughness, 0.75);
+ // 0.72: a surface, and water (see readSurface): what lands on it is the water's, not a wet floor's.
+ fragSurface = vec4(packNormal(normalize(N)), roughness, 0.72);
#endif
}
#pragma end
@@ -497,6 +562,23 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {
}
${CAUSTICS_WGSL}
+fn waterZoneAt(p : vec2f) -> vec3f {
+ let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));
+ let inside = all(uv >= vec2f(0.0)) && all(uv <= vec2f(1.0));
+ let size = vec2i(textureDimensions(u_zoneHeights, 0));
+ let f = clamp(uv, vec2f(0.0), vec2f(1.0)) * vec2f(size - vec2i(1));
+ let i = min(vec2i(floor(f)), max(size - vec2i(2), vec2i(0)));
+ let t = f - vec2f(i);
+ let a = textureLoad(u_zoneHeights, i, 0);
+ let b = textureLoad(u_zoneHeights, i + vec2i(1, 0), 0);
+ let c = textureLoad(u_zoneHeights, i + vec2i(0, 1), 0);
+ let d = textureLoad(u_zoneHeights, i + vec2i(1, 1), 0);
+ let ha = vec4f(a.r * 65280.0 + a.g * 255.0, b.r * 65280.0 + b.g * 255.0, c.r * 65280.0 + c.g * 255.0, d.r * 65280.0 + d.g * 255.0) / 65535.0;
+ let h = mix(mix(ha.x, ha.y, t.x), mix(ha.z, ha.w, t.x), t.y);
+ let da = mix(mix(a.ba, b.ba, t.x), mix(c.ba, d.ba, t.x), t.y);
+ if (!inside && mc.u_oceanOn > 0.5) { return vec3f(mc.u_oceanLevel, 1e6, mc.u_oceanWaves); }
+ return vec3f(mc.u_zoneHeight.x + h * mc.u_zoneHeight.y, da.x * mc.u_zoneRange.w, da.y * mc.u_zoneRange.y);
+}
struct WaterSun { dir : vec4f, color : vec4f, tiles : vec2i };
/// The first directional light that shines: dir.xyz is where it stands in the sky, dir.w 1 if there is one.
fn waterSun() -> WaterSun {
@@ -558,13 +640,13 @@ fn waterReflect(p : vec3f, r : vec3f, eyeDist : f32) -> vec4f {
}
/// The slope of the surface at p (x, y) and how near it is to a crest (z): the waves, and the ripples they carry, flattened with distance.
-fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
+fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec3f {
let waves = waveSlope(p, time, dist);
let rippleFade = clamp(1.0 - dist / (mc.u_rippleLength * 180.0), 0.0, 1.0);
let eps = mc.u_rippleLength * 0.1;
let ripple = vec2f(ripples(p + vec2f(eps, 0.0), time) - ripples(p - vec2f(eps, 0.0), time),
ripples(p + vec2f(0.0, eps), time) - ripples(p - vec2f(0.0, eps), time)) / (2.0 * eps);
- return vec3f(waves.slope + ripple * (mc.u_rippleStrength * mc.u_rippleLength * rippleFade), waves.crest);
+ return vec3f(waves.slope * amp + ripple * (mc.u_rippleStrength * mc.u_rippleLength * rippleFade * calm), waves.crest * calm);
}
#ifdef ES_GBUFFER
@@ -588,11 +670,22 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
var wp = P.xz;
if (mc.u_waveSpace > 0.5) { wp = v.v_texCoord + mc.u_origin; }
- 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;
+ let zoneUv = (wp - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));
+ let zoneTex = textureSample(u_zoneField, u_zoneField_s, clamp(zoneUv, vec2f(0.0), vec2f(1.0)));
+ let zone = waterZoneAt(wp);
+ let zoneIn = all(zoneUv >= vec2f(0.0)) && all(zoneUv <= vec2f(1.0));
+ let zoneOn = mc.u_zoneOn > 0.5 && mc.u_waveSpace > 0.5;
+ var shoreDist = 1e6;
+ var shoreDepth = 1e6;
var damp = 1.0;
- if (mc.u_shoreOn > 0.5) { damp = shoreTex.b; }
+ var calm = 1.0;
+ var flow = vec2f(0.0);
+ if (zoneOn) {
+ shoreDepth = zone.y;
+ damp = zone.z;
+ if (zoneIn) { shoreDist = (zoneTex.r - 0.5) * 2.0 * mc.u_zoneRange.x; flow = (zoneTex.gb - vec2f(0.5)) * 2.0 * mc.u_zoneRange.z; calm = zoneTex.a; }
+ else if (mc.u_oceanOn < 0.5) { shoreDist = -1.0; }
+ }
// The ripples at this pixel: their height on four sides gives the slope they add, and the foam is what they left (taken in uniform control flow).
let ripUv = (wp - mc.u_rippleOrigin) / max(mc.u_rippleSize, 1e-4);
let ripC = textureSample(u_rippleMap, u_rippleMap_s, ripUv);
@@ -606,22 +699,21 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
var ripFoam = 0.0;
if (ripIn) { ripSlope = vec2f(ripR - ripL, ripU - ripD) * mc.u_rippleRange / ripCell; ripFoam = ripC.g; }
var surface = vec3f(0.0);
- if (mc.u_flowSpeed > 0.0) {
- // A river: two copies of the surface carried downstream a cycle at a time, each fading in as the other fades out.
- let flow = (v.v_color.rg * 2.0 - vec2f(1.0)) * (v.v_color.b * 2.0) * mc.u_flowSpeed;
+ if (dot(flow, flow) > 1e-6) {
+ // A current: two copies of the surface carried downstream a cycle at a time, each fading in as the other fades out.
let cycle = max(mc.u_flowCycle, 0.1);
let ph0 = fract(time / cycle);
let ph1 = fract(time / cycle + 0.5);
let w0 = 1.0 - abs(2.0 * ph0 - 1.0);
- let s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist);
- let s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist);
+ let s0 = waterSurface(wp - flow * (ph0 * cycle), time, waterDist, damp, calm);
+ let s1 = waterSurface(wp - flow * (ph1 * cycle), time, waterDist, damp, calm);
surface = mix(s1, s0, w0);
} else {
- surface = waterSurface(wp, time, waterDist);
+ surface = waterSurface(wp, time, waterDist, damp, calm);
}
var waves : Waves;
- waves.crest = surface.z * damp;
- var slope = surface.xy * damp + ripSlope;
+ waves.crest = surface.z;
+ var slope = surface.xy + ripSlope;
var N = normalize(vec3f(-slope.x, 1.0, -slope.y));
var Ngeo = vec3f(0.0, 1.0, 0.0);
#ifdef MESH_NORMALS
@@ -686,7 +778,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
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) {
+ if (zoneOn && 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;
@@ -714,11 +806,11 @@ fn waterSurface(p : vec2f, time : f32, dist : f32) -> vec3f {
seen = seen + mirror * fresnel * (1.0 - foam);
var alpha = 0.85;
if (haveColor) { alpha = 1.0; }
- if (mc.u_shoreOn > 0.5 && shoreDist < 0.0) { discard; }
+ if (shoreDist < 0.0) { discard; }
#ifdef ES_GBUFFER
var frag : FragOut;
frag.color = vec4f(lit + seen, alpha);
- frag.surface = vec4f(packNormal(normalize(N)), roughness, 0.75);
+ frag.surface = vec4f(packNormal(normalize(N)), roughness, 0.72);
return frag;
#else
return vec4f(lit + seen, alpha);
diff --git a/sdk/src/water/waves.ts b/sdk/src/water/waves.ts
index 529b4660b..bb185d672 100644
--- a/sdk/src/water/waves.ts
+++ b/sdk/src/water/waves.ts
@@ -20,7 +20,7 @@ export const WAVE_SET: readonly (readonly [number, number, number, number])[] =
[71, 0.21, 0.15, 1.35],
];
-/** What shapes the waves: the fields of a WaterBody, and the parameters of the Water material they are written to. */
+/** What shapes the waves: a WaterZone's and its bodies' heights, and the parameters of the Water material they are written to. */
export interface WaveParams {
/** Height of the tallest wave, in world units. */
height: number;
diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.ts
new file mode 100644
index 000000000..d5e052bec
--- /dev/null
+++ b/sdk/src/water/zone.ts
@@ -0,0 +1,388 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file zone.ts
+ * @brief A water zone: every body of water in a region baked into one field, which one surface is drawn from.
+ *
+ * @details Bodies of water drawn each as a mesh of its own are separate surfaces, and where a river runs into a lake or the sea they meet
+ * along a seam: two heights, two sets of waves, a shore foaming across the river's mouth, a ribbon's edge showing over the lake.
+ * So a body of water is not drawn: it is an INPUT. A zone gathers the bodies over its region and bakes them into a grid, each
+ * texel holding what the water is there:
+ * - the height of its surface (a lake's level, the height of a river's curve at its nearest place, the sea's level);
+ * - the signed distance to the nearest shore (positive on the water): where the surface is cut and where it foams;
+ * - how high its waves stand there (a body's own height, calmed toward its shore and as the water shallows);
+ * - how it flows (a river's current), and how deep it is over the ground.
+ * Where two bodies meet their values are blended by how far inside each the texel is, so a river is at its lake's level where it runs
+ * into it, its current fades into the still water, and its banks run on into the lake's shores with no seam; the sea gives way to
+ * the bodies over it. One mesh following the camera reads the field and is the whole surface, and {@link WaterField.sample} answers
+ * the CPU from the same numbers.
+ *
+ * The field is in the world's own frame on the xz plane: bodies may be turned about their up, not tilted.
+ */
+import { defineComponent, type ComponentDef } from '../ecs/component';
+import { polygonSdf, shoreDamp, type Point2 } from './shore';
+
+/** The fields of the `WaterZone` component. @experimental */
+export interface WaterZoneData {
+ /** The region baked, along x and z, centred on the entity. Bodies (or the parts of them) outside it are not drawn; an ocean goes on past it. */
+ sizeX: number;
+ sizeZ: number;
+ /** Texels along the longer side of the region. */
+ resolution: number;
+ /** A material on the Water shader for the whole surface. Empty uses the stock water. */
+ material: number;
+ /** The waves every body shares (each sets only how high they stand): the length of the longest, a multiplier on their speed, their heading in degrees. */
+ waveLength: number;
+ waveSpeed: number;
+ waveDirection: number;
+ /** The surface's mesh: the cell size of its finest ring, cells along a ring's side, and how many rings (each twice as coarse) follow the camera. */
+ cellSize: number;
+ cells: number;
+ rings: number;
+ /** Cells along a side of the ripple grid; 0 keeps none. The grid is a window of `rippleSize` that follows the camera. */
+ ripples: number;
+ rippleSize: number;
+ /** How fast a ripple spreads (world units a second), how much of its height it loses a second, and how fast the foam it leaves fades a second. */
+ rippleSpeed: number;
+ rippleDamping: number;
+ foamFade: number;
+}
+
+/**
+ * Where the bodies of water are drawn from, and what they share. A scene without one is given a zone over its lakes and rivers with these
+ * defaults; put one in to say where, how fine, and what the water looks like.
+ *
+ * @experimental
+ */
+export const WaterZone: ComponentDef<WaterZoneData> = defineComponent<WaterZoneData>('WaterZone', {
+ sizeX: 200, sizeZ: 200, resolution: 256, material: 0,
+ waveLength: 14, waveSpeed: 1, waveDirection: 30,
+ cellSize: 1, cells: 64, rings: 5,
+ ripples: 0, rippleSize: 64, rippleSpeed: 6, rippleDamping: 0.8, foamFade: 0.4,
+}, {
+ assetFields: [{ field: 'material', type: 'material' }],
+ fields: {
+ sizeX: { min: 1, category: 'Region', tooltip: 'The region baked along x, centred on the entity. Water outside it is not drawn; an ocean goes on past it.' },
+ sizeZ: { min: 1, category: 'Region', tooltip: 'The region baked along z, centred on the entity.' },
+ resolution: { min: 32, max: 1024, step: 32, category: 'Region', tooltip: 'Texels along the longer side of the region: how finely shores and rivers are traced.' },
+ material: { category: 'Look', tooltip: 'A material on the Water shader for the whole surface. Empty uses the stock water.' },
+ waveLength: { min: 0.5, max: 3000, category: 'Waves', tooltip: 'The length of the longest wave. Every body shares the waves; each sets how high they stand.' },
+ waveSpeed: { min: 0, max: 4, category: 'Waves', tooltip: 'A multiplier on how fast the waves travel.' },
+ waveDirection: { min: 0, max: 360, category: 'Waves', tooltip: 'The heading of the waves, in degrees.' },
+ cellSize: { min: 0.05, category: 'Detail', tooltip: 'The cell size of the finest ring of the surface. 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.' },
+ rings: { min: 1, max: 10, step: 1, category: 'Detail', tooltip: 'Rings of the surface, each twice as coarse as the one inside it.' },
+ ripples: { min: 0, max: 256, step: 8, category: 'Ripples', tooltip: 'Cells along a side of the grid that keeps what disturbs the water: bodies moving in it, rain, and what a script disturbs. 0 keeps none.' },
+ rippleSize: { min: 4, category: 'Ripples', tooltip: 'The side of the window the ripples are kept in, in world units. It follows the camera.' },
+ rippleSpeed: { min: 0.1, max: 4000, category: 'Ripples', tooltip: 'How fast a ripple spreads, in world units a second.' },
+ rippleDamping: { min: 0, max: 10, category: 'Ripples', tooltip: 'How much of its height a ripple loses each second.' },
+ foamFade: { min: 0, max: 10, category: 'Ripples', tooltip: 'How fast the foam a disturbance leaves fades, a second.' },
+ },
+});
+
+/** An ocean, as the zone takes it: everywhere at `level`, where the ground (if known) is below it. */
+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. */
+export interface ZoneLake {
+ kind: 'lake'; key: number; level: number; waveHeight: number; shoreWidth: number;
+ outline: readonly Point2[];
+ /** A world (x, z) in the outline's own space, and back. */
+ toLocal(x: number, z: number): [number, number];
+ toWorld(x: number, z: number): [number, number];
+}
+
+/** A point along a river, in the world: where its middle is, its surface's height, half its width, its heading and how fast it runs there. */
+export interface RiverStation { x: number; z: number; y: number; half: number; dx: number; dz: number; speed: number }
+
+/** A river, as the stations along it (a few to a width), in order downstream. */
+export interface ZoneRiver { kind: 'river'; key: number; waveHeight: number; shoreWidth: number; stations: readonly RiverStation[] }
+
+export type ZoneBody = ZoneOcean | ZoneLake | ZoneRiver;
+
+/** The ground's world height at (x, z), or null where none is known. */
+export type ZoneGround = (x: number, z: number) => number | null;
+
+/** The region a field is baked over, in world units, and its grid. */
+export interface ZoneGrid { minX: number; minZ: number; sizeX: number; sizeZ: number; nx: number; nz: number }
+
+/** What the field encodes its numbers over, which the shader decodes with: see {@link WaterField.encode}. */
+export interface ZoneRanges { heightMin: number; heightSpan: number; shore: number; amp: number; flow: number; depth: number }
+
+/** What {@link WaterField.sample} answers about the water at a point. */
+export interface FieldSample {
+ /** The body that owns the most of it. */
+ key: number;
+ /** Its surface's height at rest, the height its waves stand to (and the share of its body's that is, calmed toward the shore), and its current. */
+ height: number;
+ amp: number;
+ calm: number;
+ flowX: number;
+ flowZ: number;
+ /** The signed distance to the nearest shore (positive on the water) and how deep the water is over the ground. */
+ shore: number;
+ depth: number;
+}
+
+/** What the current is at a reach this wide against the river's widest, against its nominal speed (half): a narrow reach is quick and a wide one slow. */
+export function currentShare(width: number, widest: number): number {
+ return Math.min(Math.max(widest / Math.max(width, 1e-3), 0.25), 2) / 2;
+}
+
+/** The depth over ground nothing is known of. */
+const DEEP = 1e6;
+
+/** The baked water of a zone. */
+export class WaterField {
+ readonly grid: ZoneGrid;
+ readonly height: Float32Array;
+ readonly shore: Float32Array;
+ readonly amp: Float32Array;
+ readonly calm: Float32Array;
+ readonly flowX: Float32Array;
+ readonly flowZ: Float32Array;
+ readonly depth: Float32Array;
+ /** The body that owns the most of each texel, as its key; -1 where there is no water. */
+ readonly owner: Int32Array;
+ /** The ocean, which goes on past the region: what a point outside it is. */
+ readonly ocean: ZoneOcean | null;
+
+ private constructor(grid: ZoneGrid, ocean: ZoneOcean | null) {
+ const n = grid.nx * grid.nz;
+ this.grid = grid;
+ this.ocean = ocean;
+ this.height = new Float32Array(n);
+ this.shore = new Float32Array(n);
+ this.amp = new Float32Array(n);
+ this.calm = new Float32Array(n);
+ this.flowX = new Float32Array(n);
+ this.flowZ = new Float32Array(n);
+ this.depth = new Float32Array(n);
+ this.owner = new Int32Array(n);
+ }
+
+ /**
+ * Bakes `bodies` over `grid`. Each texel takes every body's say (its height, its distance to its own shore, its waves and current) and
+ * weighs them by how far inside each it is, over a texel and a half, so where two bodies meet the values run from one to the other.
+ * The lakes and rivers come first; the ocean has what they leave. A texel no body holds keeps the height of the nearest water, so the
+ * surface's vertices there (which the shore cuts away) do not pull the water's edge down to nothing.
+ */
+ static bake(grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround): WaterField {
+ const ocean = (bodies.find((b) => b.kind === 'ocean') as ZoneOcean | undefined) ?? null;
+ const field = new WaterField(grid, ocean);
+ const texel = Math.max(grid.sizeX / Math.max(grid.nx - 1, 1), grid.sizeZ / Math.max(grid.nz - 1, 1));
+ const blend = texel * 1.5;
+ const bounded = bodies.filter((b) => b.kind !== 'ocean') as (ZoneLake | ZoneRiver)[];
+ const boxes = bounded.map((b) => boundsOf(b));
+ for (let j = 0; j < grid.nz; j++) {
+ 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;
+ let w = 0, h = 0, a = 0, c = 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]!;
+ if (x < box[0] - blend || x > box[2] + blend || z < box[1] - blend || z > box[3] + blend) continue;
+ const say = sayOf(bounded[b]!, x, z, g);
+ if (!say) continue;
+ best = Math.max(best, say.shore);
+ const weight = smooth(-blend, blend, say.shore);
+ if (weight <= 0) continue;
+ held = Math.max(held, weight);
+ w += weight; h += say.height * weight; a += say.amp * weight; c += say.calm * weight; fx += say.fx * weight; fz += say.fz * weight;
+ if (weight > ownerW) { ownerW = weight; owner = bounded[b]!.key; }
+ }
+ if (ocean) {
+ const deep = g === null ? DEEP : ocean.level - g;
+ best = Math.max(best, deep);
+ const weight = smooth(-blend, blend, deep) * (1 - held);
+ if (weight > 0) {
+ const calm = shoreDamp(deep, ocean.shoreWidth);
+ w += weight; h += ocean.level * weight; a += ocean.waveHeight * calm * weight; c += calm * weight;
+ if (weight > ownerW) { ownerW = weight; owner = ocean.key; }
+ }
+ }
+ field.shore[k] = best === -Infinity ? -DEEP : best;
+ field.owner[k] = w > 0 ? owner : -1;
+ if (w > 0) {
+ field.height[k] = h / w;
+ field.amp[k] = a / w;
+ field.calm[k] = c / w;
+ field.flowX[k] = fx / w;
+ field.flowZ[k] = fz / w;
+ } else {
+ field.height[k] = Number.NaN;
+ }
+ field.depth[k] = g === null ? DEEP : Math.max(0, (w > 0 ? h / w : 0) - g);
+ }
+ }
+ fillDry(field);
+ return field;
+ }
+
+ /** The field at a world point inside the region, read as the texels around it blend; null outside the region. */
+ at(x: number, z: number): FieldSample | null {
+ const { minX, minZ, sizeX, sizeZ, nx, nz } = this.grid;
+ if (nx < 2 || nz < 2) return null;
+ const u = (x - minX) / sizeX, v = (z - minZ) / sizeZ;
+ if (u < 0 || u > 1 || v < 0 || v > 1) return null;
+ const fx = u * (nx - 1), fz = v * (nz - 1);
+ const i = Math.min(Math.floor(fx), nx - 2), j = Math.min(Math.floor(fz), nz - 2);
+ const tx = fx - i, tz = fz - j;
+ const lerp2 = (a: Float32Array): number => {
+ const k = j * nx + i;
+ const lo = a[k]! * (1 - tx) + a[k + 1]! * tx, hi = a[k + nx]! * (1 - tx) + a[k + nx + 1]! * tx;
+ return lo * (1 - tz) + hi * tz;
+ };
+ const near = (j + (tz > 0.5 ? 1 : 0)) * nx + i + (tx > 0.5 ? 1 : 0);
+ return {
+ key: this.owner[near]!, height: lerp2(this.height), amp: lerp2(this.amp), calm: lerp2(this.calm), flowX: lerp2(this.flowX), flowZ: lerp2(this.flowZ),
+ shore: lerp2(this.shore), depth: lerp2(this.depth),
+ };
+ }
+
+ /**
+ * The water at a world point: the field inside the region, the ocean past it (as deep as it likes, waves whole), null where there is none.
+ * `shore` above zero is water.
+ */
+ sample(x: number, z: number): FieldSample | null {
+ const inside = this.at(x, z);
+ if (inside) return inside.shore > 0 ? inside : null;
+ const o = this.ocean;
+ if (!o) return null;
+ return { key: o.key, height: o.level, amp: o.waveHeight, calm: 1, flowX: 0, flowZ: 0, shore: DEEP, depth: DEEP };
+ }
+
+ /** The ranges the encoding spans, from what the field holds. */
+ ranges(): ZoneRanges {
+ let lo = Infinity, hi = -Infinity, amp = 0, flow = 0;
+ for (let k = 0; k < this.height.length; k++) {
+ const h = this.height[k]!;
+ if (Number.isFinite(h)) { lo = Math.min(lo, h); hi = Math.max(hi, h); }
+ amp = Math.max(amp, this.amp[k]!);
+ flow = Math.max(flow, Math.abs(this.flowX[k]!), Math.abs(this.flowZ[k]!));
+ }
+ if (this.ocean) { lo = Math.min(lo, this.ocean.level); hi = Math.max(hi, this.ocean.level); amp = Math.max(amp, this.ocean.waveHeight); }
+ if (!Number.isFinite(lo)) { lo = 0; hi = 0; }
+ const texel = Math.max(this.grid.sizeX / Math.max(this.grid.nx - 1, 1), this.grid.sizeZ / Math.max(this.grid.nz - 1, 1));
+ return { heightMin: lo, heightSpan: Math.max(hi - lo, 1e-3), shore: texel * 16, amp: Math.max(amp, 1e-3), flow: Math.max(flow, 1e-3), depth: texel * 16 };
+ }
+
+ /**
+ * The field as two RGBA8 images, rows from minZ. heights (read texel by texel: filtered bytes are no number): rg the height, high byte
+ * first; b the depth; a the waves' height. field (filtered): r the shore distance (0.5 at it); gb the current (0.5 still); a the calm.
+ * Each over its range in `r`.
+ */
+ encode(r: ZoneRanges): { heights: Uint8Array; field: Uint8Array } {
+ const n = this.height.length;
+ const heights = new Uint8Array(n * 4), field = new Uint8Array(n * 4);
+ const byte = (v: number): number => Math.round(Math.min(Math.max(v, 0), 1) * 255);
+ for (let k = 0; k < n; k++) {
+ const h = Math.round(Math.min(Math.max((this.height[k]! - r.heightMin) / r.heightSpan, 0), 1) * 65535);
+ heights[k * 4] = h >> 8;
+ heights[k * 4 + 1] = h & 255;
+ heights[k * 4 + 2] = byte(this.depth[k]! / r.depth);
+ heights[k * 4 + 3] = byte(this.amp[k]! / r.amp);
+ field[k * 4] = byte(this.shore[k]! / (2 * r.shore) + 0.5);
+ field[k * 4 + 1] = byte(this.flowX[k]! / (2 * r.flow) + 0.5);
+ field[k * 4 + 2] = byte(this.flowZ[k]! / (2 * r.flow) + 0.5);
+ field[k * 4 + 3] = byte(this.calm[k]!);
+ }
+ return { heights, field };
+ }
+}
+
+/** What one body says about a point: its height there, how far inside it the point is, its waves and its current. Null where it says nothing. */
+function sayOf(body: ZoneLake | ZoneRiver, x: number, z: number, g: number | null):
+ { 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);
+ return { height: body.level, shore, amp: body.waveHeight * calm, calm, fx: 0, fz: 0 };
+ }
+ const st = body.stations;
+ if (st.length < 2) return null;
+ // The nearest place on the river's middle, between two stations, with what is there eased between them.
+ let best = Infinity, at = 0, t = 0;
+ for (let s = 0; s + 1 < st.length; s++) {
+ const a = st[s]!, b = st[s + 1]!;
+ const ex = b.x - a.x, ez = b.z - a.z;
+ const len2 = ex * ex + ez * ez;
+ const u = len2 > 0 ? Math.min(Math.max(((x - a.x) * ex + (z - a.z) * ez) / len2, 0), 1) : 0;
+ const d = Math.hypot(x - (a.x + u * ex), z - (a.z + u * ez));
+ if (d < best) { best = d; at = s; t = u; }
+ }
+ const a = st[at]!, b = st[at + 1]!;
+ const mix = (p: number, q: number): number => p + (q - p) * t;
+ const half = mix(a.half, b.half), y = mix(a.y, b.y), speed = mix(a.speed, b.speed);
+ 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;
+ // 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);
+ return { height: y, shore, amp: body.waveHeight * calm, calm, fx: dx * speed * run, fz: dz * speed * run };
+}
+
+/** 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;
+ if (body.kind === 'river') {
+ for (const s of body.stations) {
+ minX = Math.min(minX, s.x - s.half); maxX = Math.max(maxX, s.x + s.half);
+ minZ = Math.min(minZ, s.z - s.half); maxZ = Math.max(maxZ, s.z + s.half);
+ }
+ return [minX, minZ, maxX, maxZ];
+ }
+ for (const p of body.outline) {
+ const [x, z] = body.toWorld(p.x, p.y);
+ minX = Math.min(minX, x); maxX = Math.max(maxX, x);
+ minZ = Math.min(minZ, z); maxZ = Math.max(maxZ, z);
+ }
+ return [minX, minZ, maxX, maxZ];
+}
+
+/** A texel no body holds takes the height of the nearest that one does: two passes of a chamfer sweep over which texel is nearest. */
+function fillDry(field: WaterField): void {
+ const { nx, nz } = field.grid;
+ const n = nx * nz;
+ const src = new Int32Array(n).fill(-1);
+ const dist = new Float32Array(n).fill(Infinity);
+ for (let k = 0; k < n; k++) if (Number.isFinite(field.height[k]!)) { src[k] = k; dist[k] = 0; }
+ const relax = (k: number, from: number, step: number): void => {
+ if (src[from]! < 0 || dist[from]! + step >= dist[k]!) return;
+ dist[k] = dist[from]! + step;
+ src[k] = src[from]!;
+ };
+ for (let j = 0; j < nz; j++) for (let i = 0; i < nx; i++) {
+ const k = j * nx + i;
+ if (i > 0) relax(k, k - 1, 1);
+ if (j > 0) relax(k, k - nx, 1);
+ if (i > 0 && j > 0) relax(k, k - nx - 1, Math.SQRT2);
+ if (i < nx - 1 && j > 0) relax(k, k - nx + 1, Math.SQRT2);
+ }
+ for (let j = nz - 1; j >= 0; j--) for (let i = nx - 1; i >= 0; i--) {
+ const k = j * nx + i;
+ if (i < nx - 1) relax(k, k + 1, 1);
+ if (j < nz - 1) relax(k, k + nx, 1);
+ if (i < nx - 1 && j < nz - 1) relax(k, k + nx + 1, Math.SQRT2);
+ if (i > 0 && j < nz - 1) relax(k, k + nx - 1, Math.SQRT2);
+ }
+ const fallback = field.ocean ? field.ocean.level : 0;
+ for (let k = 0; k < n; k++) {
+ if (Number.isFinite(field.height[k]!)) continue;
+ field.height[k] = src[k]! >= 0 ? field.height[src[k]!]! : fallback;
+ }
+}
+
+function smooth(a: number, b: number, x: number): number {
+ const t = Math.min(Math.max((x - a) / (b - a), 0), 1);
+ return t * t * (3 - 2 * t);
+}
diff --git a/sdk/tests/spline.test.ts b/sdk/tests/spline.test.ts
index c8b01eaa9..206fea8a8 100644
--- a/sdk/tests/spline.test.ts
+++ b/sdk/tests/spline.test.ts
@@ -2,8 +2,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, expect, it } from 'vitest';
import { SplineCurve, type SplinePoint } from '../src/spline/curve';
-import { buildRiverMesh, currentShare } from '../src/water/riverMesh';
-import { MeshChannel } from '../src/asset/meshFormat';
+import { currentShare } from '../src/water/zone';
+import { riverStations } from '../src/water/waterPlugin';
const pt = (x: number, y: number, z: number, width = 1): SplinePoint => ({ x, y, z, width });
@@ -73,54 +73,26 @@ describe('SplineCurve', () => {
});
});
-function positions(mesh: { channels: { semantic: number; offset: number }[]; vertexStride: number; vertexCount: number; vertices: Uint8Array }): Float32Array {
- const channel = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!;
- const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);
- const out = new Float32Array(mesh.vertexCount * 3);
- for (let i = 0; i < mesh.vertexCount; i++) for (let k = 0; k < 3; k++) out[i * 3 + k] = view.getFloat32(i * mesh.vertexStride + channel.offset + k * 4, true);
- return out;
-}
-
-describe('a river\'s mesh', () => {
- // Along +x, widening from 2 to 6, falling a unit over its length.
+describe('a river\'s stations', () => {
+ // Along +x, widening from 2 to 6, falling a unit over its length; in the world as it is.
const curve = new SplineCurve([pt(0, 1, 0, 2), pt(20, 0, 0, 6)]);
- const mesh = buildRiverMesh(curve, 2, 4);
- const p = positions(mesh);
+ const same = (x: number, y: number, z: number): [number, number, number] => [x, y, z];
+ const stations = riverStations(curve, 4, same, same, 1);
- it('faces up, whichever way it runs', () => {
- for (const c of [curve, new SplineCurve([pt(0, 0, 0, 3), pt(0, 0, 20, 3)]), new SplineCurve([pt(0, 0, 0, 3), pt(-12, 0, -9, 3)])]) {
- const m = buildRiverMesh(c, 2, 3);
- const q = positions(m);
- for (let t = 0; t < m.indices.length; t += 3) {
- const a = m.indices[t]!, b = m.indices[t + 1]!, d = m.indices[t + 2]!;
- const f = (q[b * 3 + 2]! - q[a * 3 + 2]!) * (q[d * 3]! - q[a * 3]!) - (q[b * 3]! - q[a * 3]!) * (q[d * 3 + 2]! - q[a * 3 + 2]!);
- expect(f).toBeGreaterThan(0);
- }
- }
- });
-
- it('is as wide as the curve at each station and lies at its height', () => {
- const stride = 5;
- const stations = mesh.vertexCount / stride;
- for (const i of [0, Math.floor(stations / 2), stations - 1]) {
- const s = (i / (stations - 1)) * curve.length;
- const first = i * stride, last = i * stride + 4;
- const width = Math.hypot(p[first * 3]! - p[last * 3]!, p[first * 3 + 2]! - p[last * 3 + 2]!);
- expect(width).toBeCloseTo(curve.width(s), 4);
- expect(p[first * 3 + 1]).toBeCloseTo(curve.position(s)[1], 4);
- }
+ it('run the river\'s length, a few to its narrowest width', () => {
+ expect(stations[0]!.x).toBeCloseTo(0, 6);
+ expect(stations[stations.length - 1]!.x).toBeCloseTo(20, 6);
+ expect(stations.length).toBeGreaterThanOrEqual(20 / (2 / 3));
});
- it('carries the direction of the current in its colour, and a narrow reach runs faster than a wide one', () => {
- const colorAt = mesh.channels.find((c) => c.semantic === MeshChannel.Color)!.offset;
- const rgb = (v: number): number[] => [0, 1, 2].map((k) => mesh.vertices[v * mesh.vertexStride + colorAt + k]! / 255);
- const first = rgb(0), last = rgb(mesh.vertexCount - 1);
- // Heading along +x: red high, green at rest.
- expect(first[0]).toBeGreaterThan(0.95);
- expect(first[1]).toBeCloseTo(0.5, 1);
- expect(first[2]).toBeGreaterThan(last[2]);
- expect(currentShare(2, 6)).toBe(1);
- expect(currentShare(6, 6)).toBe(0.5);
- expect(currentShare(60, 6)).toBe(0.125);
+ it('are as wide as the curve and at its height, heading downstream, quicker where it is narrow', () => {
+ const first = stations[0]!, last = stations[stations.length - 1]!;
+ expect(first.half).toBeCloseTo(curve.width(0) / 2, 6);
+ expect(last.half).toBeCloseTo(curve.width(curve.length) / 2, 6);
+ expect(first.y).toBeCloseTo(1, 4);
+ expect(last.y).toBeCloseTo(0, 4);
+ expect(first.dx).toBeCloseTo(1, 3);
+ expect(first.speed).toBeGreaterThan(last.speed);
+ expect(last.speed).toBeCloseTo(4 * currentShare(6, 6) * 2, 4);
});
});
diff --git a/sdk/tests/water-shore.test.ts b/sdk/tests/water-shore.test.ts
deleted file mode 100644
index 9b6e2e010..000000000
--- a/sdk/tests/water-shore.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-// 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/sdk/tests/water-weather.test.ts b/sdk/tests/water-weather.test.ts
new file mode 100644
index 000000000..9bed93419
--- /dev/null
+++ b/sdk/tests/water-weather.test.ts
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, describe, expect, it } from 'vitest';
+import { waveParamsOf, rainOnRipples } from '../src/water/waterPlugin';
+import { WaterZone } from '../src/water/zone';
+import { RippleField } from '../src/water/ripples';
+import {
+ blendWeather, setCurrentWeather, WeatherDrive, WEATHER_CLEAR, WEATHER_MIST, WEATHER_RAIN, WEATHER_STORM, WEATHER_NONE,
+} from '../src/postprocess/weather';
+
+const zone = WaterZone._default;
+const under = (preset: number, drive: number = WeatherDrive.All): void => setCurrentWeather(blendWeather(preset, WEATHER_NONE, 0), drive);
+
+afterEach(() => setCurrentWeather(null));
+
+describe('the wind in a weather', () => {
+ it('rises from mist to a storm, and is still at clear', () => {
+ const wind = (p: number) => blendWeather(p, WEATHER_NONE, 0).wind;
+ const waves = (p: number) => blendWeather(p, WEATHER_NONE, 0).waves;
+ expect(wind(WEATHER_CLEAR)).toBe(1);
+ expect(waves(WEATHER_CLEAR)).toBe(1);
+ expect(wind(WEATHER_MIST)).toBeLessThan(1);
+ expect(wind(WEATHER_RAIN)).toBeGreaterThan(1);
+ expect(wind(WEATHER_STORM)).toBeGreaterThan(wind(WEATHER_RAIN));
+ expect(waves(WEATHER_STORM)).toBeGreaterThan(waves(WEATHER_RAIN));
+ });
+
+ it('turns with the weather, halfway at half a turn', () => {
+ const half = blendWeather(WEATHER_CLEAR, WEATHER_STORM, 0.5);
+ expect(half.waves).toBeCloseTo((1 + blendWeather(WEATHER_STORM, WEATHER_NONE, 0).waves) / 2, 6);
+ });
+});
+
+describe('the waves under a weather', () => {
+ it('stand as the bodies say with no weather', () => {
+ expect(waveParamsOf(zone).height).toBe(1);
+ expect(waveParamsOf(zone).length).toBe(zone.waveLength);
+ });
+
+ it('are scaled by the weather\'s waves, in what is drawn and what the surface answers alike', () => {
+ under(WEATHER_STORM);
+ expect(waveParamsOf(zone).height).toBeCloseTo(blendWeather(WEATHER_STORM, WEATHER_NONE, 0).waves, 6);
+ });
+
+ it('are left alone by a weather that does not drive the wind', () => {
+ under(WEATHER_STORM, WeatherDrive.All & ~WeatherDrive.Wind);
+ expect(waveParamsOf(zone).height).toBe(1);
+ });
+});
+
+describe('rain on water that keeps ripples', () => {
+ const disturbed = (field: RippleField): number => {
+ let n = 0;
+ for (let i = 0; i < 64; i++) for (let j = 0; j < 64; j++) if (field.heightAt((i + 0.5) / 64 * field.size, (j + 0.5) / 64 * field.size) !== 0) n++;
+ return n;
+ };
+
+ it('falls as drops over the window while it rains', () => {
+ const field = new RippleField(64, 64);
+ under(WEATHER_RAIN);
+ rainOnRipples(field, 0.5);
+ expect(disturbed(field)).toBeGreaterThan(0);
+ });
+
+ it('is none under a clear sky, or when the weather does not drive the rain', () => {
+ const clear = new RippleField(64, 64);
+ under(WEATHER_CLEAR);
+ rainOnRipples(clear, 1);
+ expect(disturbed(clear)).toBe(0);
+ const off = new RippleField(64, 64);
+ under(WEATHER_STORM, WeatherDrive.All & ~WeatherDrive.Rain);
+ rainOnRipples(off, 1);
+ expect(disturbed(off)).toBe(0);
+ });
+
+ it('carries part of a drop from one frame to the next, so a slow frame rate rains as hard', () => {
+ const field = new RippleField(64, 64);
+ under(WEATHER_RAIN);
+ for (let k = 0; k < 10; k++) rainOnRipples(field, 0.001);
+ expect(field.rainOwed).toBeGreaterThan(0);
+ expect(field.rainOwed).toBeLessThan(1.5);
+ });
+});
diff --git a/sdk/tests/water-zone.test.ts b/sdk/tests/water-zone.test.ts
new file mode 100644
index 000000000..1f49a8b07
--- /dev/null
+++ b/sdk/tests/water-zone.test.ts
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, expect, it } from 'vitest';
+import { WaterField, currentShare, type RiverStation, type ZoneBody, type ZoneGrid, type ZoneLake, type ZoneOcean, type ZoneRiver } from '../src/water/zone';
+import { polygonSdf, shoreDamp, type Point2 } from '../src/water/shore';
+
+// A square lake 40 across round the origin, its surface at y = 0.
+const square: Point2[] = [{ x: -20, y: -20 }, { x: 20, y: -20 }, { x: 20, y: 20 }, { x: -20, y: 20 }];
+const lake = (extra: Partial<ZoneLake> = {}): ZoneLake => ({
+ kind: 'lake', key: 1, level: 0, waveHeight: 1, shoreWidth: 4, outline: square, toLocal: (x, z) => [x, z], toWorld: (x, z) => [x, z], ...extra,
+});
+// A river along +x from x = -60 into the lake at x = -10, 6 wide, at the lake's level, running at 2.
+const river = (y = 0): ZoneRiver => {
+ const stations: RiverStation[] = [];
+ for (let x = -60; x <= -10; x += 1) stations.push({ x, z: 0, y, half: 3, dx: 1, dz: 0, speed: 2 });
+ return { kind: 'river', key: 2, waveHeight: 0.2, shoreWidth: 1, stations };
+};
+const ocean = (level = -5): ZoneOcean => ({ kind: 'ocean', key: 3, level, waveHeight: 2, shoreWidth: 6 });
+const grid: ZoneGrid = { minX: -80, minZ: -40, sizeX: 120, sizeZ: 80, nx: 241, nz: 161 };
+const bake = (bodies: ZoneBody[], ground?: (x: number, z: number) => number | null): WaterField => WaterField.bake(grid, bodies, ground);
+
+describe('the outline of a lake', () => {
+ it('is the signed distance to its edge, positive inside', () => {
+ expect(polygonSdf(square, 0, 0)).toBeCloseTo(20, 6);
+ expect(polygonSdf(square, 19, 0)).toBeCloseTo(1, 6);
+ expect(polygonSdf(square, 25, 0)).toBeCloseTo(-5, 6);
+ });
+
+ it('calms the waves toward it', () => {
+ expect(shoreDamp(0, 4)).toBe(0);
+ expect(shoreDamp(2, 4)).toBeCloseTo(0.5, 6);
+ expect(shoreDamp(10, 4)).toBe(1);
+ expect(shoreDamp(-1, 0)).toBe(1);
+ });
+});
+
+describe('a zone with a lake', () => {
+ const field = bake([lake()]);
+
+ it('is water inside the outline at the lake\'s level, and none outside', () => {
+ const mid = field.sample(0, 0)!;
+ expect(mid.key).toBe(1);
+ expect(mid.height).toBeCloseTo(0, 3);
+ expect(mid.shore).toBeCloseTo(20, 0);
+ expect(field.sample(30, 0)).toBeNull();
+ });
+
+ it('raises its waves to their full height from the shore in', () => {
+ expect(field.sample(0, 0)!.amp).toBeCloseTo(1, 3);
+ expect(field.sample(19.5, 0)!.amp).toBeLessThan(0.1);
+ expect(field.sample(0, 0)!.calm).toBeCloseTo(1, 3);
+ expect(field.sample(19.5, 0)!.calm).toBeLessThan(0.1);
+ });
+
+ it('keeps the lake\'s height on the dry texels round it, so the surface cut at the shore is not pulled down there', () => {
+ expect(field.at(30, 0)!.height).toBeCloseTo(0, 3);
+ expect(field.at(30, 0)!.shore).toBeLessThan(0);
+ });
+
+ it('takes its depth from the ground, and calms the waves where it is shallow', () => {
+ // The bed rises to 0.5 under the surface east of x = 0.
+ const shoal = bake([lake()], (x) => (x > 0 ? -0.5 : -10));
+ expect(shoal.sample(-5, 0)!.depth).toBeCloseTo(10, 3);
+ expect(shoal.sample(5, 0)!.depth).toBeCloseTo(0.5, 3);
+ expect(shoal.sample(5, 0)!.amp).toBeLessThan(shoal.sample(-5, 0)!.amp);
+ });
+
+ it('turns with the lake, so a lake turned a quarter about up holds its outline in the world turned', () => {
+ const long: Point2[] = [{ x: -20, y: -5 }, { x: 20, y: -5 }, { x: 20, y: 5 }, { x: -20, y: 5 }];
+ const turned = bake([lake({ outline: long, toLocal: (x, z) => [z, -x], toWorld: (x, z) => [-z, x] })]);
+ expect(turned.sample(0, 15)).not.toBeNull();
+ expect(turned.sample(15, 0)).toBeNull();
+ });
+});
+
+describe('a river running into a lake', () => {
+ const field = bake([lake(), river()]);
+
+ it('is one water along its course and into the lake, with no shore across its mouth', () => {
+ for (let x = -55; x <= 0; x += 0.5) {
+ const s = field.sample(x, 0);
+ expect(s, `water at x = ${x}`).not.toBeNull();
+ expect(s!.height).toBeCloseTo(0, 3);
+ }
+ // Where the river's middle crosses the lake's outline the water is a river's half width or more from any shore: nothing foams there.
+ expect(field.sample(-20, 0)!.shore).toBeGreaterThan(2.5);
+ // Its banks run on into the lake's shores: beside the river, outside the lake, there is no water.
+ expect(field.sample(-30, 5)).toBeNull();
+ });
+
+ it('carries its current, which fades out in the still water', () => {
+ const mid = field.sample(-40, 0)!;
+ expect(mid.flowX).toBeGreaterThan(1.5);
+ expect(Math.abs(mid.flowZ)).toBeLessThan(1e-3);
+ expect(Math.hypot(field.sample(0, 0)!.flowX, field.sample(0, 0)!.flowZ)).toBeLessThan(0.05);
+ });
+
+ it('is at its own height up its course, and blends to the lake\'s where they meet', () => {
+ const high = bake([lake(), river(2)]);
+ expect(high.sample(-50, 0)!.height).toBeCloseTo(2, 2);
+ expect(high.sample(0, 0)!.height).toBeCloseTo(0, 2);
+ });
+});
+
+describe('an ocean', () => {
+ it('is everywhere the ground is below its level, and goes on past the region', () => {
+ const field = bake([ocean()], (x) => (x > 0 ? 5 : -20));
+ expect(field.sample(-30, 0)!.height).toBeCloseTo(-5, 3);
+ expect(field.sample(30, 0)).toBeNull();
+ const past = field.sample(5000, 5000)!;
+ expect(past.key).toBe(3);
+ expect(past.height).toBe(-5);
+ expect(past.amp).toBe(2);
+ });
+
+ it('gives way to a lake over it: a point on the lake is the lake\'s, not the sea\'s under it', () => {
+ const field = bake([ocean(-5), lake()], () => -30);
+ const s = field.sample(0, 0)!;
+ expect(s.key).toBe(1);
+ expect(s.height).toBeCloseTo(0, 3);
+ expect(field.sample(-60, 30)!.key).toBe(3);
+ });
+});
+
+describe('the field as the shader reads it', () => {
+ it('holds the height to a 65535th of its span, and the shore, the waves and the current in bytes', () => {
+ const field = bake([lake(), river(3)]);
+ const r = field.ranges();
+ const { heights, field: rest } = field.encode(r);
+ const k = Math.round((0 - grid.minZ) / grid.sizeZ * (grid.nz - 1)) * grid.nx + Math.round((-50 - grid.minX) / grid.sizeX * (grid.nx - 1));
+ const h = r.heightMin + ((heights[k * 4]! * 256 + heights[k * 4 + 1]!) / 65535) * r.heightSpan;
+ expect(h).toBeCloseTo(field.height[k]!, 3);
+ expect((rest[k * 4 + 1]! / 255 - 0.5) * 2 * r.flow).toBeCloseTo(field.flowX[k]!, 1);
+ expect((rest[k * 4]! / 255 - 0.5) * 2 * r.shore).toBeCloseTo(Math.max(-r.shore, Math.min(r.shore, field.shore[k]!)), 0);
+ });
+
+ it('is nothing over an ocean alone: there is no region, and every point is the ocean', () => {
+ const field = WaterField.bake({ minX: 0, minZ: 0, sizeX: 0, sizeZ: 0, nx: 0, nz: 0 }, [ocean(1)]);
+ expect(field.at(0, 0)).toBeNull();
+ expect(field.sample(0, 0)!.height).toBe(1);
+ });
+});
+
+describe('a river\'s current', () => {
+ it('is quicker in a narrow reach than a wide one', () => {
+ expect(currentShare(2, 6)).toBe(1);
+ expect(currentShare(6, 6)).toBe(0.5);
+ expect(currentShare(60, 6)).toBe(0.125);
+ });
+});
diff --git a/sdk/tests/water.test.ts b/sdk/tests/water.test.ts
index 694f52aaf..2d17a3406 100644
--- a/sdk/tests/water.test.ts
+++ b/sdk/tests/water.test.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, expect, it } from 'vitest';
import { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from '../src/water/waves';
-import { buildOceanMesh, buildRectMesh, oceanReach, oceanSnap } from '../src/water/waterMesh';
+import { buildOceanMesh, oceanReach, oceanSnap } from '../src/water/waterMesh';
import { MeshChannel } from '../src/asset/meshFormat';
import type { MeshData } from '../src/asset/meshFormat';
@@ -68,31 +68,7 @@ describe('the waves', () => {
});
});
-describe('a lake\'s mesh', () => {
- const mesh = buildRectMesh(20, 10, 2);
- const p = positions(mesh);
-
- it('covers its rectangle in cells of the size asked, facing up', () => {
- expect(mesh.vertexCount).toBe(11 * 6);
- expect(mesh.indices.length / 3).toBe(10 * 5 * 2);
- expect(mesh.aabbMin).toEqual([-10, 0, -5]);
- expect(mesh.aabbMax).toEqual([10, 0, 5]);
- for (let t = 0; t < mesh.indices.length; t += 3) {
- expect(facing(p, mesh.indices[t]!, mesh.indices[t + 1]!, mesh.indices[t + 2]!)).toBeGreaterThan(0);
- }
- });
-
- it('takes its uv from its position, so the shader\'s body space is local x and z', () => {
- const channel = mesh.channels.find((c) => c.semantic === MeshChannel.TexCoord0)!;
- const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);
- for (const i of [0, 7, mesh.vertexCount - 1]) {
- expect(view.getFloat32(i * mesh.vertexStride + channel.offset, true)).toBeCloseTo(p[i * 3]!, 6);
- expect(view.getFloat32(i * mesh.vertexStride + channel.offset + 4, true)).toBeCloseTo(p[i * 3 + 2]!, 6);
- }
- });
-});
-
-describe('an ocean\'s mesh', () => {
+describe('the surface\'s mesh', () => {
const cells = 16, rings = 4, cell = 1;
const mesh = buildOceanMesh(cells, rings, cell);
const p = positions(mesh);
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index af54dbc96..24cb86c45 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -1122,10 +1122,11 @@ std::string wgslReachedTextureDecls(const std::string& source, bool postProcess)
// The sampler is declared only for a texture the stage samples through it. A texture read with textureLoad alone has
// no sampler to bind, and that is what lets a 32-bit float one (the motion pass's) be its binding: a float32 texture
// cannot be filtered, and a layout that pairs it with a filtering sampler is refused by the device.
-std::string wgslMaterialTextureDecls(const ParsedShader& parsed, const std::string& body) {
+std::string wgslMaterialTextureDecls(const ParsedShader& parsed, const std::string& body, const std::string* only = nullptr) {
std::string src;
for (const auto& p : parsed.properties) {
if (!p.fromParam || p.type != ShaderPropertyType::Texture || p.textureUnit < 0) continue;
+ if (only && only->find(p.name) == std::string::npos) continue;
const u32 unit = static_cast<u32>(p.textureUnit);
src += "@group(1) @binding(" + std::to_string(unit + 8) + ") var " + p.name +
" : texture_2d<f32>;\n";
@@ -2168,6 +2169,13 @@ ShaderParser::AssembledStage assembleWGSLStage(const ParsedShader& parsed,
"@group(0) @binding(1) var<uniform> mc : MaterialConstants;\n";
inject(block);
}
+ std::string bodyText = bodyIt->second;
+ if (stage == ShaderStage::Vertex && !parsed.wgslVertexHook.empty()) {
+ fillHook(bodyText, "@@ES_VERTEX_HOOK@@", parsed.wgslVertexHook);
+ // A material's vertex hook may read its textures too (a height field the surface is lifted by): the ones it names are declared
+ // for this stage as well, and the device then makes their bindings visible to it.
+ inject(wgslMaterialTextureDecls(parsed, bodyText, &parsed.wgslVertexHook));
+ }
if (stage == ShaderStage::Fragment) {
inject(wgslMaterialTextureDecls(parsed, bodyIt->second));
if (lit) inject(kLitHeaderWGSL);
@@ -2184,10 +2192,6 @@ ShaderParser::AssembledStage assembleWGSLStage(const ParsedShader& parsed,
inject(wgslReachedTextureDecls(assembled.str() + bodyIt->second,
parsed.domain == "PostProcess"));
- std::string bodyText = bodyIt->second;
- if (stage == ShaderStage::Vertex && !parsed.wgslVertexHook.empty()) {
- fillHook(bodyText, "@@ES_VERTEX_HOOK@@", parsed.wgslVertexHook);
- }
assembled << bodyText;
result.source = preprocessConditionals(assembled.str(), features);
diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjs
index f6609bed5..2248f6280 100644
--- a/tools/apiSubsystems.mjs
+++ b/tools/apiSubsystems.mjs
@@ -341,9 +341,9 @@ export const SUBSYSTEMS = [
titleZh: '水体',
source: ['water'],
tier: 'experimental',
- why: 'the surface draws and its waves are shared with the CPU, but only an ocean and a rectangular lake exist so far, and nothing floats or swims in it yet',
- whyZh: '水面能画出来,波浪也和 CPU 共用同一个公式,但目前只有海洋和矩形湖泊,还没有东西能漂浮或游泳',
- entry: ['WaterBody', 'Waters'],
+ why: 'oceans, lakes and rivers are baked into one zone and drawn as one surface the CPU reads back, and things float on it, but the field and its shading are still settling and nothing swims yet',
+ whyZh: '海洋、湖泊和河流烘焙进同一个水体区域、画成一张水面,CPU 读到的就是画出来的那一面,也能漂浮物体;但区域场和着色还在定型,还没有东西能游泳',
+ entry: ['WaterBody', 'WaterZone', 'Waters'],
},
{
id: 'decal',
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index d6b5732ac..f67173b84 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -123,9 +123,6 @@ 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 —
- Floating: ['owed', 'no example floats anything yet; the first boat or buoy goes into one'],
- Spline: ['owed', 'no example carries a spline yet; the first river, with a spline tool in the editor, 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'],
SpringBone: ['owed', 'no example carries a rigged character with hair or a tail yet; the first one imported with its chains goes into one'],
SpringBoneCollider: ['owed', 'no example has a spring-bone chain to keep out of anything; it arrives with the first SpringBone'],
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'],
diff --git a/tools/check-gizmo-coverage.mjs b/tools/check-gizmo-coverage.mjs
index 18a76de72..67e9299ea 100644
--- a/tools/check-gizmo-coverage.mjs
+++ b/tools/check-gizmo-coverage.mjs
@@ -124,11 +124,13 @@ const DISPOSITION = {
'Foliage.heightMax': ['no-place', 'a band of world heights plants grow in, not a region round the entity'],
'Foliage.lodDistance': ['no-place', 'a distance from the camera past which the far version is drawn'],
'Foliage.drawDistance': ['no-place', 'a distance from the camera past which nothing is drawn'],
- '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.shoreWidth': ['no-place', 'a distance in from a body\'s shore over which the waves come to full height, not a region of the entity'],
+ 'WaterZone.sizeX': 'extent',
+ 'WaterZone.sizeZ': 'extent',
+ 'WaterZone.cellSize': ['no-place', 'the cell size of the finest ring of the surface\'s mesh, not a region of the entity'],
+ 'WaterZone.rippleSize': ['no-place', 'the side of a window of ripples that follows the camera, not a region of the entity'],
'Floating.radius': ['no-place', 'how deep under the surface a point of the body is wholly wet, 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'],
- 'WaterBody.rippleSize': ['no-place', 'the side of a window of ripples that follows the camera, not a region of the entity'],
'SpringBone.radius': ['no-place', 'the thickness of the strand, kept clear of the colliders; a margin on each bone, not a region of the root'],
'Sprite.size': ['renders', 'the sprite drawn at it is the outline'],
'Sprite.tileSize': ['renders', 'the repeat of a drawn sprite'],
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 816d79b19..4b2698a6e 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2706,4 +2706,18 @@ export const NOTED = {
{"note":"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."},
"feat(render): reflections no longer guess a surface, plain meshes record themselves, and what the ray never finds is the sky":
{"note":"Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen."},
+ "fix(render): an opaque mesh on a material records its surface, and water and glass own theirs":
+ {"note":"A mesh on a material records its surface."},
+ "fix(terrain): a splatmap's fourth layer no longer erases the other three":
+ {"note":"A terrain's splatmap keeps all four layers."},
+ "feat(weather): the wind raises the waves and bends the plants, and rain falls on the water":
+ {"note":"Wind and rain on the water."},
+ "feat(water): every body of water is baked into a zone and drawn as one surface":
+ {"note":"Water zones."},
+ "fix(examples): the Wilds ground textures repeat instead of smearing at their edges":
+ {"internal":"An example's texture import settings; the engine is unchanged."},
+ "feat(editor): a new Weather drives the wind too":
+ {"internal":"The editor half of the wind note: a Weather added in Details drives the wind with the rest."},
+ "feat(editor): the viewport outlines a WaterZone, and the water checks author their water in one":
+ {"internal":"The editor half of Water zones, which carries the note."},
};