A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(water): a waterfall - a Waterfall on an entity at a lip throws sheets of water level at a speed and lets gravity take them, each ending where it meets the ground or water that is not the water it left; it is the entity's own MeshRenderer, and with no material it takes the stock Waterfall shader, glass at the lip tearing into strands that ride down with the water
yhh52fe65265fad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c23e1622..b6cebe4eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **A waterfall.** A river's surface lies over the ground and stopped at the edge of a cliff with nothing after it. A `Waterfall` on an entity at the lip, facing the way the water leaves, throws sheets of water level at `speed` and lets gravity take them: each ends where it meets the ground, or water that is not the water it left, or `maxDrop` under the lip, and is made again when what is under it changes. It is the entity's own `MeshRenderer`; with no material it takes the stock Waterfall shader, glass at the lip that tears into strands and then veils, its pattern riding down with the water at the water's own speed.- **A sky of your own shades the ground under its clouds.** Sky Atmosphere's clouds cast their shadow on the scene; a sky written with `defineSkyEffect` could not, so a stylised sky lit a world with no cloud shadow on it. With `groundShadow: true` the sky's source holds a second function, `skyShadow(world, sun)`, what is left of the light at a world position, and every surface the sky pass finds is multiplied by it.- **A texture says whether it is a picture or numbers.** Import settings have a **Use**: Colour, or Data for an image read a number a texel (a heightmap, a mask of measured values, a lookup table). A build treats Data as what it is: never compressed, never decoded as sRGB or filled, kept at its depth, and at its own size unless Max Size (which now offers Source size) says otherwise, in which case it is resampled at 16 bits and not through 8. Nobody has to know to set it: a PNG of 16 bits a sample is imported as Data from the editor and the CLI alike, a texture put in a `Terrain`'s heightmap or splatmap is marked Data there and then (a splatmap cooked as a picture had its weights overwritten wherever the fourth was 0, and the ground fell back to grass everywhere), and Project Health lists textures a component reads as numbers that are still set up as pictures, with the fix on the row.- **An ocean reaches the horizon.** The sea's surface is rings of mesh round the camera, and it ended where they did: from a hill, or with a small `cells` and `rings`, a straight edge with nothing past it. A flat apron now carries it on to 80 km, at the cost of one row of quads.diff --git a/desktop b/desktopindex bd42a882f..5389d416f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit bd42a882f57c435c2282b28918d80c66f2b92eea+Subproject commit 5389d416f7a4e448169cff8d34b32072213a49fediff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdxindex 22678639e..f9ff4952f 100644--- a/docs/astro/src/content/docs/graphics/water.mdx+++ b/docs/astro/src/content/docs/graphics/water.mdx@@ -153,6 +153,31 @@ so a river runs downhill. Put a `Spline` and a `WaterBody` with `form` River on- **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 oranother 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.+## Waterfalls++A river's surface is a field over the ground and cannot stand on end, so a river that comes to a cliff stops at its edge. A **`Waterfall`**+is what goes on from there. Put it on an entity at the lip, turned to face the way the water leaves (its forward): the water is thrown+level at `speed` and pulled down by gravity, and each sheet ends where it meets the ground, or water that is not the water it left, or+`maxDrop` under the lip. It is drawn as the entity's own `MeshRenderer`, and made again when its fields, its place or what is under it change.++| Field | What it does |+|---|---|+| `width` | How wide the water is where it leaves the lip. |+| `speed` | How fast it leaves, level and along the entity's forward. Faster throws it further from the cliff. |+| `flare` | How much wider a sheet is at its foot than at the lip, as a share of its width. |+| `sheets`, `sheetGap` | How many sheets (1 to 5), one behind another along the throw, and how far apart they leave the lip. The middle one is whole, the others narrower. |+| `maxDrop` | How far under the lip a fall that meets nothing ends. |+| `rows`, `across` | Rows down a sheet and cells across it. |++Only the entity's turn about the vertical aims it: keep it upright and unscaled. With no material on the `MeshRenderer` it takes the stock+**Waterfall** shader: glass at the lip that tears into strands and then veils, its pattern riding down with the water. Its params are the+water's colour at the lip (`u_water`) and the white it breaks into (`u_foam`), how many strands lie across a sheet (`u_strands`) and how+fast they run (`u_run`), how much of the sheet is gone at its foot (`u_veil`) and how far down it is torn that much (`u_tearBy`),+`u_opacity` and `u_roughness`. A material of your own reads what the mesh carries: `uv.x` across the sheet, `uv.y` the seconds the water+there has been falling, the colour's red the share of the fall done, its green a number of the sheet's own.++The fall is the sheet alone: the mist at its foot and the white water where it lands are a `ParticleEmitter`'s and the pool's own to draw.+## FloatingPut a `Floating` component on an entity with a `RigidBody3D` and a collider and the water holds it up and carries it along. It works through forces on thediff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdxindex 9e014759b..e59959b29 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx@@ -98,6 +98,28 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一- **河床。** `bedDepth` 大于零时,河流把河床挖进地形:河道中线处低于水面 `bedDepth`,河边与水面齐平,河岸以相同的坡度继续升高直到接回原地面,最远两个河宽。它以[地形修改器](/docs/zh-cn/graphics/terrain/#修改器)的形式铺设,每段河道一个,所以画出来的地面、查询和碰撞都跟随它;编辑样条只重做河道沿线的地面;比河床更低的地面保持不变。游戏自己刻好河道的地面(带河流一起生成的高度图)请把 `bedDepth` 留为 0。- **河岸与河口。** 河岸是场里岸线距离过零的地方,按区域的分辨率描出。河流流进湖、海或另一条河的地方,两者在一个半纹素内混合,所以没有接缝,河口没有横跨的岸线,也没有高度台阶。+## 瀑布++河面是铺在地面上的一个场,立不起来,所以河流到了崖边就停在崖口。**`Waterfall`** 接着往下画:把它放在崖口的实体上,朝向水离开的方向+(实体的前方)。水以 `speed` 水平抛出、受重力下落,每一片水帘在碰到地面、碰到不是它离开的那片水、或落到崖口下 `maxDrop` 处时结束。+它画成实体自己的 `MeshRenderer`,字段、位置或下方的地形/水域变了就重建。++| 字段 | 作用 |+|---|---|+| `width` | 水离开崖口处的宽度。 |+| `speed` | 离开崖口的速度,水平、沿实体前方。越快抛得离崖越远。 |+| `flare` | 水帘底部比崖口处宽多少,按自身宽度的比例。 |+| `sheets`、`sheetGap` | 水帘的片数(1 到 5),沿抛出方向前后排开,以及它们离开崖口时的间距。中间一片完整,其余更窄。 |+| `maxDrop` | 什么都没碰到时,落到崖口下多远为止。 |+| `rows`、`across` | 水帘沿下落方向的行数和横向的格数。 |++只有实体绕竖直轴的转向起作用:保持它直立、不缩放。`MeshRenderer` 上没有材质时用内置的 **Waterfall** 着色器:崖口处像玻璃,往下撕成水丝+再成水雾,花纹随水一起下落。参数有崖口处水的颜色(`u_water`)和碎开后的白(`u_foam`)、一片水帘上横向有多少条水丝(`u_strands`)+及其流速(`u_run`)、底部少掉多少(`u_veil`)和落到多深撕成那样(`u_tearBy`)、`u_opacity` 和 `u_roughness`。自己写材质时可以读网格+带的数据:`uv.x` 是横向位置,`uv.y` 是那里的水已经下落的秒数,颜色的红是下落完成的比例,绿是每片水帘自己的编号。++瀑布只是水帘本身:底部的水雾和落水处的白沫由 `ParticleEmitter` 和水潭自己来画。+## 漂浮给一个有 `RigidBody3D` 和碰撞体的实体加上 `Floating` 组件,水就会托住它并带着它走。它通过作用在刚体上的力来工作,力来自询问水面([查询表面](#查询表面))在身体的几个点之下在哪里,所以不需要渲染器:不画任何东西的服务器、测试或构建,漂浮的结果也一样。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex c9e2656d5..857cd1b18 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 178,- "experimental": 3057,+ "experimental": 3065,"deprecated": 3},- "total": 3350,+ "total": 3358,"subsystems": [{"id": "mobile-controls",diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 7abc83414..1a702c693 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -111,6 +111,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {MeshInstances: { category: 'graphics', summary: 'Draws the mesh of a MeshRenderer at many places as one renderable, culling each place and choosing its mesh by distance.', doc: 'graphics/foliage', anchor: 'placed-plants', 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: '样条' },+ Waterfall: { category: 'graphics', summary: 'Water falling from a lip: sheets thrown level at a speed and taken by gravity until they meet the ground or other water, drawn as the entity's own mesh.', doc: 'graphics/water', anchor: 'waterfalls', 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: '水体区域' },Billboard: { category: 'graphics', summary: 'Turns the MeshRenderer beside it to face each view that draws it: flat in the view plane, or upright about world up.', doc: 'graphics/drawing', anchor: 'cards-that-face-the-camera-billboard', anchorZh: '朝向相机的卡片billboard' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 5f58466a2..ea32caecf 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -10670,6 +10670,78 @@"foamFade"]},+ {+ "name": "Waterfall",+ "source": "ts",+ "fields": [+ {+ "key": "width",+ "type": "number",+ "default": "800",+ "doc": "How wide the water is where it leaves the lip.",+ "range": "≥ 0.01"+ },+ {+ "key": "speed",+ "type": "number",+ "default": "500",+ "doc": "How fast it leaves the lip, level and along the entity's forward. Faster throws it further out.",+ "range": "≥ 0"+ },+ {+ "key": "flare",+ "type": "number",+ "default": "1.1",+ "doc": "How much wider a sheet is at its foot than at the lip, as a share of its width.",+ "range": "0–4, step 0.01"+ },+ {+ "key": "sheets",+ "type": "number",+ "default": "3",+ "doc": "How many sheets, one behind another along the throw.",+ "range": "1–5, step 1"+ },+ {+ "key": "sheetGap",+ "type": "number",+ "default": "90",+ "doc": "How far apart the sheets leave the lip.",+ "range": "≥ 0"+ },+ {+ "key": "maxDrop",+ "type": "number",+ "default": "30000",+ "doc": "How far under the lip a fall that meets nothing ends.",+ "range": "≥ 0.01"+ },+ {+ "key": "rows",+ "type": "number",+ "default": "56",+ "doc": "Rows down a sheet. More follows the curve more closely.",+ "range": "2–256, step 1"+ },+ {+ "key": "across",+ "type": "number",+ "default": "6",+ "doc": "Cells across a sheet.",+ "range": "1–32, step 1"+ }+ ],+ "animatable": [+ "width",+ "speed",+ "flare",+ "sheets",+ "sheetGap",+ "maxDrop",+ "rows",+ "across"+ ]+ },{"name": "Weather","source": "ts",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 4fd75ec39..51fb38953 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 · 166 beta · 2168 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2176 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -13678,6 +13678,11 @@ static prototype: VoxelTerrainsResourceDef<VoxelTerrains>```+## WATERFALL_SHADER_TEMPLATE — const @experimental+```+BuiltinShaderTemplate+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -13821,6 +13826,38 @@ waveLength: numberwaveSpeed: number```+## Waterfall — const @experimental+```+ComponentDef<WaterfallData>+```++## WaterfallData — interface @experimental+```+across: number+flare: number+maxDrop: number+rows: number+sheetGap: number+sheets: number+speed: number+width: number+```++## WaterfallLanding — interface @experimental+```+heightAt: ((x: number, z: number) => number | null) | undefined+waterAt: ((x: number, z: number, y: number) => { body: number; above: number; } | null) | undefined+```++## WaterfallLip — interface @experimental+```+dirX: number+dirZ: number+x: number+y: number+z: number+```+## Waters — class @experimental```@internal app_: App | null@@ -14844,6 +14881,11 @@ MotionDriver<AnimatorBlend2DMotion>(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData```+## buildWaterfall — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null): MeshData | null+```+## builtinBusVolume — function @experimental```(name: string): number | null@@ -18549,6 +18591,16 @@ VoxelPluginPlugin```+## waterfallFlight — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null, ahead?: number): { seconds: number; drop: number; }+```++## waterfallHeading — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number]+```+## waveFade — function @experimental```(length: number, cell: number): numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex a7d41300b..aa31b4ca8 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 · 171 beta · 2188 experimental · 3 deprecated+Symbols: 115 public · 171 beta · 2196 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -13900,6 +13900,11 @@ static prototype: VoxelTerrainsResourceDef<VoxelTerrains>```+## WATERFALL_SHADER_TEMPLATE — const @experimental+```+BuiltinShaderTemplate+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -14043,6 +14048,38 @@ waveLength: numberwaveSpeed: number```+## Waterfall — const @experimental+```+ComponentDef<WaterfallData>+```++## WaterfallData — interface @experimental+```+across: number+flare: number+maxDrop: number+rows: number+sheetGap: number+sheets: number+speed: number+width: number+```++## WaterfallLanding — interface @experimental+```+heightAt: ((x: number, z: number) => number | null) | undefined+waterAt: ((x: number, z: number, y: number) => { body: number; above: number; } | null) | undefined+```++## WaterfallLip — interface @experimental+```+dirX: number+dirZ: number+x: number+y: number+z: number+```+## Waters — class @experimental```@internal app_: App | null@@ -15081,6 +15118,11 @@ MotionDriver<AnimatorBlend2DMotion>(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData```+## buildWaterfall — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null): MeshData | null+```+## builtinBusVolume — function @experimental```(name: string): number | null@@ -18821,6 +18863,16 @@ VoxelPluginPlugin```+## waterfallFlight — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null, ahead?: number): { seconds: number; drop: number; }+```++## waterfallHeading — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number]+```+## waveFade — function @experimental```(length: number, cell: number): numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex f080e4259..bdbc0648b 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 · 168 beta · 2167 experimental · 3 deprecated+Symbols: 115 public · 168 beta · 2175 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -13673,6 +13673,11 @@ static prototype: VoxelTerrainsResourceDef<VoxelTerrains>```+## WATERFALL_SHADER_TEMPLATE — const @experimental+```+BuiltinShaderTemplate+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -13816,6 +13821,38 @@ waveLength: numberwaveSpeed: number```+## Waterfall — const @experimental+```+ComponentDef<WaterfallData>+```++## WaterfallData — interface @experimental+```+across: number+flare: number+maxDrop: number+rows: number+sheetGap: number+sheets: number+speed: number+width: number+```++## WaterfallLanding — interface @experimental+```+heightAt: ((x: number, z: number) => number | null) | undefined+waterAt: ((x: number, z: number, y: number) => { body: number; above: number; } | null) | undefined+```++## WaterfallLip — interface @experimental+```+dirX: number+dirZ: number+x: number+y: number+z: number+```+## Waters — class @experimental```@internal app_: App | null@@ -14839,6 +14876,11 @@ MotionDriver<AnimatorBlend2DMotion>(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData```+## buildWaterfall — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null): MeshData | null+```+## builtinBusVolume — function @experimental```(name: string): number | null@@ -18554,6 +18596,16 @@ VoxelPluginPlugin```+## waterfallFlight — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null, ahead?: number): { seconds: number; drop: number; }+```++## waterfallHeading — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number]+```+## waveFade — function @experimental```(length: number, cell: number): numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5ed310d4a..f1f7d2cc9 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 · 166 beta · 2189 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2197 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -13976,6 +13976,11 @@ static prototype: VoxelTerrainsResourceDef<VoxelTerrains>```+## WATERFALL_SHADER_TEMPLATE — const @experimental+```+BuiltinShaderTemplate+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -14119,6 +14124,38 @@ waveLength: numberwaveSpeed: number```+## Waterfall — const @experimental+```+ComponentDef<WaterfallData>+```++## WaterfallData — interface @experimental+```+across: number+flare: number+maxDrop: number+rows: number+sheetGap: number+sheets: number+speed: number+width: number+```++## WaterfallLanding — interface @experimental+```+heightAt: ((x: number, z: number) => number | null) | undefined+waterAt: ((x: number, z: number, y: number) => { body: number; above: number; } | null) | undefined+```++## WaterfallLip — interface @experimental+```+dirX: number+dirZ: number+x: number+y: number+z: number+```+## Waters — class @experimental```@internal app_: App | null@@ -15142,6 +15179,11 @@ MotionDriver<AnimatorBlend2DMotion>(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData```+## buildWaterfall — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null): MeshData | null+```+## builtinBusVolume — function @experimental```(name: string): number | null@@ -18862,6 +18904,16 @@ VoxelPluginPlugin```+## waterfallFlight — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null, ahead?: number): { seconds: number; drop: number; }+```++## waterfallHeading — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number]+```+## waveFade — function @experimental```(length: number, cell: number): numberdiff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.mdindex 32f50962c..2209ffa2c 100644--- a/sdk/etc/water.api.md+++ b/sdk/etc/water.api.md@@ -1,7 +1,7 @@# API surface — esengine/water<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 39 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 47 experimental · 0 deprecated## Basin — interface @experimental```@@ -117,6 +117,11 @@ static new (): UnderwaterPluginstatic prototype: UnderwaterPlugin```+## WATERFALL_SHADER_TEMPLATE — const @experimental+```+BuiltinShaderTemplate+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -220,6 +225,38 @@ waveLength: numberwaveSpeed: number```+## Waterfall — const @experimental+```+ComponentDef<WaterfallData>+```++## WaterfallData — interface @experimental+```+across: number+flare: number+maxDrop: number+rows: number+sheetGap: number+sheets: number+speed: number+width: number+```++## WaterfallLanding — interface @experimental+```+heightAt: ((x: number, z: number) => number | null) | undefined+waterAt: ((x: number, z: number, y: number) => { body: number; above: number; } | null) | undefined+```++## WaterfallLip — interface @experimental+```+dirX: number+dirZ: number+x: number+y: number+z: number+```+## Waters — class @experimental```@internal app_: App | null@@ -262,6 +299,11 @@ speed: number(cells: number, rings: number, cellSize: number, skirt?: number): MeshData```+## buildWaterfall — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null): MeshData | null+```+## currentShare — function @experimental```(width: number, widest: number): number@@ -317,6 +359,16 @@ speed: numberPlugin```+## waterfallFlight — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null, ahead?: number): { seconds: number; drop: number; }+```++## waterfallHeading — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number]+```+## waveFade — function @experimental```(length: number, cell: number): numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex b66041a81..bfd27c632 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 · 166 beta · 2180 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2188 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -13680,6 +13680,11 @@ static prototype: VoxelTerrainsResourceDef<VoxelTerrains>```+## WATERFALL_SHADER_TEMPLATE — const @experimental+```+BuiltinShaderTemplate+```+## WAVE_SET — const @experimental```readonly (readonly [number, number, number, number])[]@@ -13823,6 +13828,38 @@ waveLength: numberwaveSpeed: number```+## Waterfall — const @experimental+```+ComponentDef<WaterfallData>+```++## WaterfallData — interface @experimental+```+across: number+flare: number+maxDrop: number+rows: number+sheetGap: number+sheets: number+speed: number+width: number+```++## WaterfallLanding — interface @experimental+```+heightAt: ((x: number, z: number) => number | null) | undefined+waterAt: ((x: number, z: number, y: number) => { body: number; above: number; } | null) | undefined+```++## WaterfallLip — interface @experimental+```+dirX: number+dirZ: number+x: number+y: number+z: number+```+## Waters — class @experimental```@internal app_: App | null@@ -14873,6 +14910,11 @@ MotionDriver<AnimatorBlend2DMotion>(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData```+## buildWaterfall — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null): MeshData | null+```+## builtinBusVolume — function @experimental```(name: string): number | null@@ -18588,6 +18630,16 @@ VoxelPluginPlugin```+## waterfallFlight — function @experimental+```+(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null, ahead?: number): { seconds: number; drop: number; }+```++## waterfallHeading — function @experimental+```+(q: { x: number; y: number; z: number; w: number; }): [number, number]+```+## waveFade — function @experimental```(length: number, cell: number): numberdiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex c9b2cae34..cb558e6f2 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -891,6 +891,8 @@ export {export { WAVE_SET, waveFade, waveHeight, waveSlope, type WaveParams } from './water/waves';export { WaterZone, WaterField, currentShare, type WaterZoneData, type FieldSample } from './water/zone';export { buildOceanMesh, oceanReach, oceanSnap } from './water/waterMesh';+export { Waterfall, buildWaterfall, waterfallFlight, waterfallHeading, type WaterfallData, type WaterfallLanding, type WaterfallLip } from './water/waterfall';+export { WATERFALL_SHADER_TEMPLATE } from './water/waterfallShader';export { polygonSdf, shoreDamp, type Point2 } from './water/shore';export { findBasins, drainPath, type Basin, type BasinMap, type BasinOptions } from './water/basins';export {diff --git a/sdk/src/water/index.ts b/sdk/src/water/index.tsindex c09965744..82234f49b 100644--- a/sdk/src/water/index.ts+++ b/sdk/src/water/index.ts@@ -9,6 +9,8 @@ export { RippleField } from './ripples';export { Floating, FloatingPlugin, floatingForce, wakeStrength, type FloatingBody, type FloatingData, type FloatingForce } from './floating';export { WaterZone, WaterField, currentShare, type WaterZoneData, type FieldSample } from './zone';export { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';+export { Waterfall, buildWaterfall, waterfallFlight, waterfallHeading, type WaterfallData, type WaterfallLanding, type WaterfallLip } from './waterfall';+export { WATERFALL_SHADER_TEMPLATE } from './waterfallShader';export { polygonSdf, shoreDamp, type Point2 } from './shore';export { findBasins, drainPath, type Basin, type BasinMap, type BasinOptions } from './basins';diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex 721c56476..4267a5488 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -36,6 +36,7 @@ import { bakesOf } from '../runtime/bakes';import type { Entity } from '../types';import { surfHeight, waveHeight, waveSlope, WAVE_SET_SIZE, type WaveParams } from './waves';import { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';+import { installWaterfalls } from './waterfall';import { worldUnitsPerMeter } from '../ecs/worldUnits';import { type Point2 } from './shore';import { Spline, type SplineData } from '../spline/splinePlugin';@@ -411,6 +412,7 @@ export class WaterPlugin implements Plugin {this.waters_ = waters;waters.app_ = app;app.insertResource(WatersRes, waters);+ installWaterfalls(app);app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {const policy = app.hasResource(Quality) ? app.getResource(Quality) : null;diff --git a/sdk/src/water/waterSupport.ts b/sdk/src/water/waterSupport.tsindex 3110584cb..c1729889a 100644--- a/sdk/src/water/waterSupport.ts+++ b/sdk/src/water/waterSupport.ts@@ -8,12 +8,14 @@import { addEntryPlugin } from '../runtime/entryPlugins';import { registerBuiltinShaderTemplate } from '../render/builtinShaders';import { WATER_SHADER_TEMPLATE } from './waterShader';+import { WATERFALL_SHADER_TEMPLATE } from './waterfallShader';import { WaterPlugin } from './waterPlugin';import { FloatingPlugin } from './floating';import { UnderwaterPlugin, registerUnderwaterEffect } from './underwater';export function registerWaterSupport(): void {registerBuiltinShaderTemplate(WATER_SHADER_TEMPLATE);+ registerBuiltinShaderTemplate(WATERFALL_SHADER_TEMPLATE);addEntryPlugin('water', () => new WaterPlugin());addEntryPlugin('floating', () => new FloatingPlugin());addEntryPlugin('underwater', () => new UnderwaterPlugin());diff --git a/sdk/src/water/waterfall.ts b/sdk/src/water/waterfall.tsnew file mode 100644index 000000000..142436287--- /dev/null+++ b/sdk/src/water/waterfall.ts@@ -0,0 +1,257 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file waterfall.ts+ * @brief Water falling from a lip: sheets thrown out at a speed and pulled down by gravity until they meet the ground or water.+ *+ * @details A river's surface is a field over the ground and cannot stand on end, so where a river comes to a cliff it stops. A `Waterfall`+ * is what goes on from there: put the entity at the lip, facing the way the water leaves it (its forward), and the sheets are the+ * path a thing thrown level at `speed` takes (only the entity's turn about the vertical aims it: keep it upright and unscaled), built as the entity's own MeshRenderer so a material on it can be anything. With no+ * material it takes the stock Waterfall shader (waterfallShader.ts). Each sheet ends where it meets the ground, or water that is+ * not the water it left, or `maxDrop` under the lip, whichever is first; it is made again when its fields, the entity's place or the ground change. The+ * terrain and the water are asked by name: with neither, a fall is `maxDrop` high.+ *+ * What a vertex carries for a material: uv.x across the sheet (0 to 1), uv.y the seconds the water there has been falling, colour+ * red the share of the fall done (0 at the lip, 1 at the foot), green a number of the sheet's own (so sheets do not move as one),+ * and alpha 0 at the sheet's two edges.+ */+import type { App } from '../app/app';+import type { Entity } from '../types';+import { defineComponent, MeshRenderer, Transform, type ComponentDef, type MeshRendererData, type TransformData } from '../ecs/component';+import { defineSystem, Schedule } from '../ecs/system';+import { worldUnitsPerMeter } from '../ecs/worldUnits';+import { Assets } from '../asset/AssetPlugin';+import type { MaterialShaderSource } from '../asset/loaders/MaterialShaderAssetLoader';+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from '../asset/meshFormat';+import { Material, MATERIAL_FORMAT_VERSION } from '../render/material';+import { BlendMode } from '../render/blend';++/** The fields of the `Waterfall` component. @experimental */+export interface WaterfallData {+ /** How wide the water is where it leaves the lip, in world units. */+ width: number;+ /** How fast it leaves the lip, level and along the entity's forward, in world units a second. Faster throws it further out. */+ speed: number;+ /** How much wider a sheet is at its foot than at the lip, as a share of its width: 1 is twice as wide. */+ flare: number;+ /** How many sheets, 1 to 5, one behind another along the throw: the middle one whole, the others narrower. */+ sheets: number;+ /** How far apart the sheets leave the lip, in world units. */+ sheetGap: number;+ /** How far under the lip a fall that meets nothing ends, in world units. */+ maxDrop: number;+ /** Rows down a sheet and cells across it. */+ rows: number;+ across: number;+}++/**+ * Falling water from the entity's place along its forward, drawn as the entity's MeshRenderer.+ *+ * @experimental+ */+export const Waterfall: ComponentDef<WaterfallData> = /* @__PURE__ */ defineComponent<WaterfallData>('Waterfall', {+ // Lengths at the engine's reference of 100 units a metre (ecs/worldUnits.ts): eight metres of water leaving at five metres a second.+ width: 800, speed: 500, flare: 1.1, sheets: 3, sheetGap: 90, maxDrop: 30000, rows: 56, across: 6,+}, {+ worldUnitFields: ['width', 'speed', 'sheetGap', 'maxDrop'],+ fields: {+ width: { min: 0.01, unit: 'wu', tooltip: 'How wide the water is where it leaves the lip.' },+ speed: { min: 0, unit: 'wu/s', tooltip: 'How fast it leaves the lip, level and along the entity\'s forward. Faster throws it further out.' },+ flare: { min: 0, max: 4, step: 0.01, tooltip: 'How much wider a sheet is at its foot than at the lip, as a share of its width.' },+ sheets: { min: 1, max: 5, step: 1, tooltip: 'How many sheets, one behind another along the throw.' },+ sheetGap: { min: 0, unit: 'wu', tooltip: 'How far apart the sheets leave the lip.' },+ maxDrop: { min: 0.01, unit: 'wu', tooltip: 'How far under the lip a fall that meets nothing ends.' },+ rows: { min: 2, max: 256, step: 1, tooltip: 'Rows down a sheet. More follows the curve more closely.' },+ across: { min: 1, max: 32, step: 1, tooltip: 'Cells across a sheet.' },+ },+});++/**+ * What a fall lands on: the ground's height at a place, and the water there (which body's it is, and how far `y` is above its surface,+ * negative under it), null where there is none. Either may be absent.+ */+export interface WaterfallLanding {+ heightAt?(x: number, z: number): number | null;+ waterAt?(x: number, z: number, y: number): { body: number; above: number } | null;+}++/** The lip in the world: where it is and the level direction the water leaves along (unit, on xz). */+export interface WaterfallLip { x: number; y: number; z: number; dirX: number; dirZ: number }++/** Gravity, in metres a second squared. */+const GRAVITY = 9.8;+/** How far a sheet has to have dropped, in metres, before what it meets ends it: at the lip it is still in the water it left. */+const CLEAR = 0.5;+/** The share of the middle sheet's width the others have. */+const OUTER = 0.72;+/** How far the middle of a sheet bows out past its edges at the foot, as a share of the sheet's own half width there. */+const BOW = 0.14;++/** The seconds a sheet thrown from `lip`, `ahead` along the throw, falls before it lands, and the drop that is. */+export function waterfallFlight(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null, ahead = 0): { seconds: number; drop: number } {+ const g = GRAVITY * worldUnitsPerMeter();+ const most = Math.sqrt((2 * Math.max(fall.maxDrop, 1e-3)) / g);+ const clear = CLEAR * worldUnitsPerMeter();+ const steps = 512;+ // The water it leaves reaches a little past the lip (a river ends in a round of its own width): what it lands in is another body's.+ const left = landing?.waterAt?.(lip.x, lip.z, lip.y)?.body ?? null;+ for (let i = 1; i <= steps; i++) {+ const t = (most * i) / steps, drop = 0.5 * g * t * t;+ if (drop < clear) continue;+ const x = lip.x + lip.dirX * (fall.speed * t + ahead), z = lip.z + lip.dirZ * (fall.speed * t + ahead), y = lip.y - drop;+ const ground = landing?.heightAt?.(x, z) ?? null;+ const water = landing?.waterAt?.(x, z, y) ?? null;+ if ((ground !== null && y <= ground) || (water !== null && water.above <= 0 && water.body !== left)) return { seconds: t, drop };+ }+ return { seconds: most, drop: fall.maxDrop };+}++/**+ * The sheets' geometry in the entity's own space, where the throw is along -z: the entity's turn about the vertical is what aims it in the+ * world, and `lip` says where that is for what the sheets land on. Null where there is nothing to draw. Rows are closer together near the+ * lip, where the path turns the most.+ */+export function buildWaterfall(fall: WaterfallData, lip: WaterfallLip, landing: WaterfallLanding | null): MeshData | null {+ if (!(fall.width > 0) || !(fall.maxDrop > 0)) return null;+ const g = GRAVITY * worldUnitsPerMeter();+ const sheets = Math.max(1, Math.min(5, Math.floor(fall.sheets)));+ const rows = Math.max(2, Math.min(256, Math.floor(fall.rows)));+ const cells = Math.max(1, Math.min(32, Math.floor(fall.across)));+ 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 perSheet = (rows + 1) * (cells + 1);+ const vertexCount = sheets * perSheet;+ const vertices = new Uint8Array(vertexCount * vertexStride);+ const view = new DataView(vertices.buffer);+ const at = (semantic: number): number => channels.find((c) => c.semantic === semantic)!.offset;+ const posAt = at(MeshChannel.Position), uvAt = at(MeshChannel.TexCoord0), colorAt = at(MeshChannel.Color), normalAt = at(MeshChannel.Normal);+ const min: [number, number, number] = [Infinity, Infinity, Infinity];+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];+ const indices = new Uint32Array(sheets * rows * cells * 6);+ let vertex = 0, index = 0;+ for (let s = 0; s < sheets; s++) {+ const middle = (sheets - 1) / 2;+ const ahead = (s - middle) * fall.sheetGap;+ const half = fall.width * 0.5 * (s === Math.round(middle) ? 1 : OUTER);+ const { seconds } = waterfallFlight(fall, lip, landing, ahead);+ const first = vertex;+ for (let r = 0; r <= rows; r++) {+ const t = Math.pow(r / rows, 0.8) * seconds, k = seconds > 0 ? t / seconds : 0;+ const out = fall.speed * t + ahead, down = 0.5 * g * t * t;+ const wide = half * (1 + fall.flare * k);+ // The path's own normal: level at the lip (the sheet lies flat as it leaves), turning to face along the throw as it steepens.+ const vy = g * t, vl = Math.hypot(fall.speed, vy) || 1;+ const n = [0, fall.speed / vl, -vy / vl] as const;+ for (let c = 0; c <= cells; c++, vertex++) {+ const u = c / cells, side = u * 2 - 1;+ const bow = (1 - side * side) * BOW * wide * k;+ const p = [side * wide, -down, -(out + bow)] as const;+ const base = vertex * vertexStride;+ for (let i = 0; i < 3; i++) {+ view.setFloat32(base + posAt + i * 4, p[i]!, true);+ view.setFloat32(base + normalAt + i * 4, n[i]!, true);+ if (p[i]! < min[i]!) min[i] = p[i]!;+ if (p[i]! > max[i]!) max[i] = p[i]!;+ }+ view.setFloat32(base + uvAt, u, true);+ view.setFloat32(base + uvAt + 4, t, true);+ view.setUint8(base + colorAt, Math.round(k * 255));+ view.setUint8(base + colorAt + 1, Math.round(((s * 0.381966) % 1) * 255));+ view.setUint8(base + colorAt + 2, 255);+ view.setUint8(base + colorAt + 3, c === 0 || c === cells ? 0 : 255);+ }+ }+ for (let r = 0; r < rows; r++) {+ for (let c = 0; c < cells; c++) {+ const a = first + r * (cells + 1) + c, b = a + 1, d = a + cells + 1, e = d + 1;+ indices[index++] = a; indices[index++] = b; indices[index++] = d;+ indices[index++] = b; indices[index++] = e; indices[index++] = d;+ }+ }+ }+ return { channels, vertexStride, vertexCount, vertices, indices, aabbMin: min, aabbMax: max };+}++/** The level direction an entity turned by `q` faces along (its forward, -z, laid on the ground), or -z where it faces straight up or down. */+export function waterfallHeading(q: { x: number; y: number; z: number; w: number }): [number, number] {+ const fx = -2 * (q.x * q.z + q.w * q.y), fz = -(1 - 2 * (q.x * q.x + q.y * q.y));+ const len = Math.hypot(fx, fz);+ return len > 1e-6 ? [fx / len, fz / len] : [0, -1];+}++interface Asked { heightAt?: unknown; sample?: unknown; revision_?: number; loading?: boolean; baking?: boolean; built_?: Map<unknown, unknown>; empty?: boolean }++/** What there is to land on, whichever modules are here, and how to tell when it has changed or is still being made. */+function landingOf(app: App): { query: WaterfallLanding; revision: string; waiting: boolean } {+ const terrains = app.getResourceByName?.('Terrains') as Asked | undefined;+ const waters = app.getResourceByName?.('Waters') as Asked | undefined;+ const ground = terrains && typeof terrains.heightAt === 'function' && terrains.built_?.size ? terrains : null;+ const water = waters && typeof waters.sample === 'function' && !waters.empty ? waters : null;+ return {+ query: {+ heightAt: ground ? (x, z) => (ground.heightAt as (x: number, z: number) => number | null)(x, z) : undefined,+ waterAt: water ? (x, z, y) => {+ const at = (water.sample as (x: number, y: number, z: number) => { entity: number; depth: number } | null)(x, y, z);+ return at ? { body: at.entity, above: at.depth } : null;+ } : undefined,+ },+ revision: `${ground?.revision_ ?? -1}:${water?.revision_ ?? -1}`,+ waiting: !!terrains?.loading || !!waters?.baking,+ };+}++/** Keeps every `Waterfall` falling to what is under it. Called once by the water plugin. */+export function installWaterfalls(app: App): void {+ const built = new Map<Entity, { key: string; handle: number }>();+ let stock = 0, asked = false;+ const letGo = (entity: Entity): void => {+ const held = built.get(entity);+ built.delete(entity);+ if (held?.handle && app.hasResource(Assets)) app.getResource(Assets).releaseBuiltMesh(held.handle);+ };+ app.world.onDespawn(letGo);+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ const world = app.world;+ if (!app.hasResource(Assets)) return;+ const assets = app.getResource(Assets);+ for (const entity of [...built.keys()]) if (!world.valid(entity) || !world.has(entity, Waterfall)) letGo(entity);+ const falls = world.getEntitiesWithComponents([Waterfall, Transform]);+ if (falls.length === 0) return;+ if (!stock && !asked) {+ asked = true;+ void assets.load<MaterialShaderSource>('material-shader', 'builtin:waterfall').then((source) => {+ stock = Material.createFromAsset({+ version: MATERIAL_FORMAT_VERSION, type: 'material', shader: 'builtin:waterfall', blendMode: BlendMode.Normal,+ depthTest: true, depthWrite: false, cull: 0, properties: {},+ }, source.compile([]));+ });+ }+ const landing = landingOf(app);+ // Thrown over a ground or a water still being made, it would fall through and be thrown again a moment later.+ if (landing.waiting) return;+ for (const entity of falls) {+ const fall = world.get(entity, Waterfall) as WaterfallData;+ const t = world.get(entity, Transform) as TransformData;+ const renderer = world.has(entity, MeshRenderer) ? world.get(entity, MeshRenderer) as MeshRendererData : null;+ const own = !!renderer?.material && renderer.material !== stock;+ if (!own && !stock) continue;+ const [dirX, dirZ] = waterfallHeading(t.worldRotation);+ const lip = { x: t.worldPosition.x, y: t.worldPosition.y, z: t.worldPosition.z, dirX, dirZ };+ const key = JSON.stringify([fall, lip, landing.revision, worldUnitsPerMeter(), own ? renderer!.material : stock]);+ const held = built.get(entity);+ if (held?.key === key) continue;+ const mesh = buildWaterfall(fall, lip, landing.query);+ const handle = mesh ? assets.createMesh(mesh) : 0;+ if (held?.handle) assets.releaseBuiltMesh(held.handle);+ built.set(entity, { key, handle });+ world.insert(entity, MeshRenderer, {+ ...renderer, enabled: true, mesh: handle, material: own ? renderer!.material : stock, opaque: false, castShadows: false, cullBackfaces: false,+ } as Partial<MeshRendererData>);+ }+ }, { name: 'WaterfallSystem' }));+}diff --git a/sdk/src/water/waterfallShader.ts b/sdk/src/water/waterfallShader.tsnew file mode 100644index 000000000..ccde215df--- /dev/null+++ b/sdk/src/water/waterfallShader.ts@@ -0,0 +1,148 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file waterfallShader.ts+ * @brief The Waterfall shader: a sheet of falling water that leaves the lip as glass, tears into strands and ends as veils.+ *+ * @details It reads what a `Waterfall`'s mesh carries (waterfall.ts): across the sheet in uv.x, the seconds fallen in uv.y, the share of the+ * fall done in the colour's red, the sheet's own number in its green. A pattern keeps its (seconds fallen - now), so it rides down+ * with the water at the water's own speed and stretches as the water does.+ */+import { makeBuiltinShaderTemplate } from '../render/builtinShaders';++const WATERFALL = `#pragma shader "Waterfall"+#pragma version 300 es+#pragma domain Lit+// The water at the lip, before it breaks, and the white it breaks into.+#pragma param u_water color default(0.30,0.55,0.52,1)+#pragma param u_foam color default(0.90,0.94,0.98,1)+// How many strands lie across the sheet, and how fast their pattern runs (1 is with the water).+#pragma param u_strands float default(60) range(4,400) ui(slider)+#pragma param u_run float default(0.55) range(0,4) ui(slider)+// How much of the sheet is gone at its foot (0 a whole sheet to the bottom, 1 nothing left of it), and how far down it is torn that much.+#pragma param u_veil float default(0.42) range(0,1) ui(slider)+#pragma param u_tearBy float default(0.85) range(0.05,1) ui(slider)+#pragma param u_opacity float default(1) range(0,1) ui(slider)+#pragma param u_roughness float default(0.6) range(0.02,1) ui(slider)++#pragma fragment+precision highp float;++in vec4 v_color;+in vec2 v_texCoord;+in highp vec2 v_worldPos;+#ifdef MESH_NORMALS+in highp vec3 v_worldNormal;+in highp vec3 v_worldXYZ;+#endif++#ifdef ES_GBUFFER+layout(location = 0) out vec4 fragColor;+layout(location = 1) out vec4 fragSurface;+layout(location = 2) out vec4 fragAlbedo;+#else+out vec4 fragColor;+#endif++float fallHash(vec2 p) { vec3 q = fract(vec3(p.xyx) * 0.1031); q += dot(q, q.yzx + 33.33); return fract((q.x + q.y) * q.z); }+float fallNoise(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ vec2 w = f * f * (3.0 - 2.0 * f);+ return mix(mix(fallHash(i), fallHash(i + vec2(1.0, 0.0)), w.x), mix(fallHash(i + vec2(0.0, 1.0)), fallHash(i + vec2(1.0, 1.0)), w.x), w.y);+}++void main() {+#ifdef MESH_NORMALS+ highp vec3 P = v_worldXYZ;+ highp vec3 N = normalize(v_worldNormal);+#else+ highp vec3 P = vec3(v_worldPos.x, 0.0, v_worldPos.y);+ highp vec3 N = vec3(0.0, 1.0, 0.0);+#endif+ highp vec3 V = viewDirection(P);+ if (dot(N, V) < 0.0) N = -N;+ float side = v_texCoord.x * 2.0 - 1.0, k = clamp(v_color.r, 0.0, 1.0), own = v_color.g;+ float across = (side + own) * u_strands;+ float along = (v_texCoord.y - u_time.x) * u_run * 28.0;+ float strands = fallNoise(vec2(across, along)) * 0.55 + fallNoise(vec2(across * 2.5 + 9.0, along * 2.1)) * 0.45;+ float clumps = fallNoise(vec2(across / 3.0 + 3.0, along * 0.45));+ // A glassy lip that tears into strands, then into veils.+ float body = mix(1.0, 0.74, smoothstep(0.05, 0.7, k));+ float cut = mix(-0.05, u_veil, smoothstep(0.0, u_tearBy, k)) - (clumps - 0.5) * 0.35;+ float alpha = smoothstep(cut, cut + 0.22, strands) * body + (1.0 - smoothstep(0.0, 0.06, k)) * 0.9;+ alpha *= pow(max(1.0 - side * side, 0.0), mix(0.35, 0.9, k));+ alpha *= 1.0 - smoothstep(0.90, 1.0, k) * 0.6;+ alpha = clamp(alpha * u_opacity, 0.0, 1.0);+ if (alpha < 0.02) discard;+ vec3 albedo = mix(u_water.rgb, u_foam.rgb, smoothstep(0.0, 0.10, k) * (0.6 + 0.4 * strands));+ SurfaceExt ext = surfaceExtNone(N);+ vec3 lit = applyLightingSurface(albedo, N, P, V, 0.0, u_roughness, 0.5, 1.0, ext);+ fragColor = vec4(lit, alpha);+#ifdef ES_GBUFFER+ fragSurface = vec4(0.5, 0.5, u_roughness, 0.0);+ fragAlbedo = vec4(albedo, 1.0);+#endif+}+#pragma end++#pragma fragment wgsl+fn fallHash(p : vec2f) -> f32 { var q = fract(vec3f(p.xyx) * 0.1031); q += dot(q, q.yzx + 33.33); return fract((q.x + q.y) * q.z); }+fn fallNoise(p : vec2f) -> f32 {+ let i = floor(p); let f = fract(p);+ let w = f * f * (3.0 - 2.0 * f);+ return mix(mix(fallHash(i), fallHash(i + vec2f(1.0, 0.0)), w.x), mix(fallHash(i + vec2f(0.0, 1.0)), fallHash(i + vec2f(1.0, 1.0)), w.x), w.y);+}+#ifdef ES_GBUFFER+struct FragOut {+ @location(0) color : vec4f,+ @location(1) surface : vec4f,+ @location(2) albedo : vec4f,+};+@fragment fn fs_main(v : VSOut) -> FragOut {+#else+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+#endif+ g_probeSlot = v.v_probeSlot;+#ifdef MESH_LIGHTMAP+ g_lightmap = v.v_lightmap;+#endif+#ifdef MESH_NORMALS+ let P = v.v_worldXYZ;+ var N = normalize(v.v_worldNormal);+#else+ let P = vec3f(v.v_worldPos.x, 0.0, v.v_worldPos.y);+ var N = vec3f(0.0, 1.0, 0.0);+#endif+ let V = viewDirection(P);+ if (dot(N, V) < 0.0) { N = -N; }+ let side = v.v_texCoord.x * 2.0 - 1.0;+ let k = clamp(v.v_color.r, 0.0, 1.0);+ let across = (side + v.v_color.g) * mc.u_strands;+ let along = (v.v_texCoord.y - tc.u_time.x) * mc.u_run * 28.0;+ let strands = fallNoise(vec2f(across, along)) * 0.55 + fallNoise(vec2f(across * 2.5 + 9.0, along * 2.1)) * 0.45;+ let clumps = fallNoise(vec2f(across / 3.0 + 3.0, along * 0.45));+ let body = mix(1.0, 0.74, smoothstep(0.05, 0.7, k));+ let cut = mix(-0.05, mc.u_veil, smoothstep(0.0, mc.u_tearBy, k)) - (clumps - 0.5) * 0.35;+ var alpha = smoothstep(cut, cut + 0.22, strands) * body + (1.0 - smoothstep(0.0, 0.06, k)) * 0.9;+ alpha = alpha * pow(max(1.0 - side * side, 0.0), mix(0.35, 0.9, k));+ alpha = alpha * (1.0 - smoothstep(0.90, 1.0, k) * 0.6);+ alpha = clamp(alpha * mc.u_opacity, 0.0, 1.0);+ if (alpha < 0.02) { discard; }+ let albedo = mix(mc.u_water.rgb, mc.u_foam.rgb, smoothstep(0.0, 0.10, k) * (0.6 + 0.4 * strands));+ let ext = surfaceExtNone(N);+ let lit = applyLightingSurface(albedo, N, P, V, 0.0, mc.u_roughness, 0.5, 1.0, ext);+#ifdef ES_GBUFFER+ var frag : FragOut;+ frag.color = vec4f(lit, alpha);+ frag.surface = vec4f(0.5, 0.5, mc.u_roughness, 0.0);+ frag.albedo = vec4f(albedo, 1.0);+ return frag;+#else+ return vec4f(lit, alpha);+#endif+}+#pragma end+`;++export const WATERFALL_SHADER_TEMPLATE = makeBuiltinShaderTemplate('waterfall', 'Waterfall',+ 'Falling water for a Waterfall: glass at the lip, strands and then veils on the way down, riding down with the water.', WATERFALL);diff --git a/sdk/tests/waterfall.test.ts b/sdk/tests/waterfall.test.tsnew file mode 100644index 000000000..cdb5c226d--- /dev/null+++ b/sdk/tests/waterfall.test.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file waterfall.test.ts+ * @brief A Waterfall's sheets: the path they take, what ends them, and what their vertices carry for the shader.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { setWorldUnitsPerMeter } from '../src/ecs/worldUnits';+import { MeshChannel, type MeshData } from '../src/asset/meshFormat';+import { Waterfall, buildWaterfall, waterfallFlight, waterfallHeading, type WaterfallData, type WaterfallLip } from '../src/water/waterfall';+import { WATERFALL_SHADER_TEMPLATE } from '../src/water/waterfallShader';++beforeAll(() => setWorldUnitsPerMeter(1));+afterAll(() => setWorldUnitsPerMeter(100));++const fall = (over: Partial<WaterfallData> = {}): WaterfallData => ({ width: 8, speed: 5, flare: 1, sheets: 1, sheetGap: 1, maxDrop: 300, rows: 16, across: 4, ...over });+const lip: WaterfallLip = { x: 10, y: 100, z: -20, dirX: 1, dirZ: 0 };++function read(mesh: MeshData, semantic: number, i: number, n: number): number[] {+ const c = mesh.channels.find((ch) => ch.semantic === semantic)!;+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset);+ return Array.from({ length: n }, (_, k) => view.getFloat32(i * mesh.vertexStride + c.offset + k * 4, true));+}+const colour = (mesh: MeshData, i: number, k: number): number =>+ mesh.vertices[i * mesh.vertexStride + mesh.channels.find((ch) => ch.semantic === MeshChannel.Color)!.offset + k]!;++describe('a waterfall\'s flight', () => {+ it('ends where the path meets the ground, by the time gravity takes to drop that far', () => {+ const { seconds, drop } = waterfallFlight(fall(), lip, { heightAt: () => 20 });+ expect(drop).toBeGreaterThanOrEqual(80);+ expect(drop).toBeLessThan(83);+ expect(seconds).toBeCloseTo(Math.sqrt((2 * drop) / 9.8), 5);+ });++ it('ends in water of another body, and not in the water it left, which reaches past the lip', () => {+ // The river it leaves, to 6 units past the lip and sagging there as a field read between texels does; then the sea.+ const waterAt = (x: number, _z: number, y: number): { body: number; above: number } => (x < 16 ? { body: 7, above: y - (100.1 - (x - 10)) } : { body: 3, above: y });+ const landed = waterfallFlight(fall(), lip, { waterAt }).drop;+ expect(landed).toBeGreaterThanOrEqual(100);+ expect(landed).toBeLessThan(103);+ // A fall from dry ground lands in the first water it meets.+ expect(waterfallFlight(fall(), { ...lip, x: 20 }, { waterAt: (x, _z, y) => (x > 25 ? { body: 3, above: y - 60 } : null) }).drop).toBeLessThan(43);+ });++ it('falls its whole length over nothing, and is thrown further by more speed', () => {+ expect(waterfallFlight(fall({ maxDrop: 50 }), lip, null).drop).toBe(50);+ const slow = waterfallFlight(fall({ speed: 2 }), lip, { heightAt: (x) => (x < 30 ? 90 : 0) }).drop;+ const fast = waterfallFlight(fall({ speed: 20 }), lip, { heightAt: (x) => (x < 30 ? 90 : 0) }).drop;+ expect(slow).toBeLessThan(12);+ expect(fast).toBeGreaterThan(90);+ });+});++describe('a waterfall\'s sheets', () => {+ it('are built along -z in the entity\'s own space, level at the lip and widening to the foot', () => {+ const mesh = buildWaterfall(fall({ flare: 1 }), lip, { heightAt: () => 20 })!;+ const rows = 16, cells = 4, last = rows * (cells + 1);+ expect(mesh.vertexCount).toBe((rows + 1) * (cells + 1));+ expect(read(mesh, MeshChannel.Position, 0, 3)).toEqual([-4, -0, -0]);+ expect(read(mesh, MeshChannel.Normal, 0, 3)[1]).toBeCloseTo(1, 5);+ const foot = read(mesh, MeshChannel.Position, last, 3), across = read(mesh, MeshChannel.Position, last + cells, 3);+ expect(foot[1]).toBeLessThan(-80);+ expect(foot[2]).toBeLessThan(-15);+ expect(across[0]! - foot[0]!).toBeCloseTo(16, 3);+ expect(mesh.aabbMin[1]).toBeCloseTo(foot[1]!, 4);+ });++ it('carry across and seconds fallen in the uv, the share done and the sheet\'s number in the colour, and 0 alpha at the edges', () => {+ const mesh = buildWaterfall(fall({ sheets: 3 }), lip, { heightAt: () => 20 })!;+ const per = 17 * 5;+ expect(mesh.vertexCount).toBe(3 * per);+ expect(read(mesh, MeshChannel.TexCoord0, 0, 2)).toEqual([0, 0]);+ const end = read(mesh, MeshChannel.TexCoord0, per - 1, 2);+ expect(end[0]).toBe(1);+ expect(end[1]).toBeGreaterThan(3.9);+ expect(colour(mesh, 0, 0)).toBe(0);+ expect(colour(mesh, per - 1, 0)).toBe(255);+ expect(new Set([colour(mesh, 0, 1), colour(mesh, per, 1), colour(mesh, 2 * per, 1)]).size).toBe(3);+ expect(colour(mesh, 0, 3)).toBe(0);+ expect(colour(mesh, 2, 3)).toBe(255);+ expect(colour(mesh, 4, 3)).toBe(0);+ });++ it('is nothing without a width or a drop', () => {+ expect(buildWaterfall(fall({ width: 0 }), lip, null)).toBeNull();+ expect(buildWaterfall(fall({ maxDrop: 0 }), lip, null)).toBeNull();+ });+});++describe('the Waterfall component and its shader', () => {+ it('aims by the entity\'s turn about the vertical', () => {+ expect(waterfallHeading({ x: 0, y: 0, z: 0, w: 1 })).toEqual([-0, -1]);+ const quarter = waterfallHeading({ x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 });+ expect(quarter[0]).toBeCloseTo(-1, 6);+ expect(quarter[1]).toBeCloseTo(0, 6);+ expect(waterfallHeading({ x: Math.SQRT1_2, y: 0, z: 0, w: Math.SQRT1_2 })).toEqual([0, -1]);+ });++ it('has its lengths in world units, and a shader that rides its pattern down with the water in both languages', () => {+ const d = Waterfall._default;+ expect([d.width, d.speed, d.sheetGap, d.maxDrop, d.flare]).toEqual([8, 5, 0.9, 300, 1.1]);+ const source = WATERFALL_SHADER_TEMPLATE.source;+ expect(source).toContain('(v_texCoord.y - u_time.x) * u_run');+ expect(source).toContain('(v.v_texCoord.y - tc.u_time.x) * mc.u_run');+ for (const p of ['u_water', 'u_foam', 'u_strands', 'u_run', 'u_veil', 'u_tearBy', 'u_opacity', 'u_roughness']) expect(source).toContain(`#pragma param ${p} `);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 5bd9f597b..c8eb95e27 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -4572,4 +4572,6 @@ export const NOTED = {{"note": "A colour map and an occlusion map lie the way the heightmap does."},"fix(water): the sea past the rings lies at the sea's level - the apron that carries an ocean to the horizon took its inner edge's height from the water under it, so with a river on high ground under that edge a strip of sea eighty kilometres long rose to the river's height; the apron's vertices are marked and the shader lays them at the ocean's level":{"note": "The sea past the rings lies at the sea's level."},+ "feat(water): a waterfall - a Waterfall on an entity at a lip throws sheets of water level at a speed and lets gravity take them, each ending where it meets the ground or water that is not the water it left; it is the entity's own MeshRenderer, and with no material it takes the stock Waterfall shader, glass at the lip tearing into strands that ride down with the water":+ {"note": "A waterfall."},};