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
fix(water): rain rings out on the surface instead of denting the ripples, wind ripples are waves not noise, and storms raise sheltered water less
yhh9955a934e3da
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 54be5d892..aff9af1f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,7 @@ published separately; it ships inside the editor.### Fixed+- **Rain and storms on water.** Rain no longer drops dips into the zone's ripples (which twitched and left blotches of foam under a storm): drops ring out on the surface in the Water shader, as fine rings that spread and die, the more the harder it rains, with no foam. The wind's ripples are six short waves around its heading instead of drifting noise, so a lake no longer shows cells of light and dark. A weather raises waves as far as the water is open to the wind (the sea whole, a lake by its width, a river hardly at all), and surf is swell from open water, so a lake's shore laps in a storm instead of breaking like the sea's; what floats rides the same water.- **Shadows follow what the camera draws.** A mesh the camera's level of detail culls (grass past its draw distance) no longer casts a shadow, and one drawn coarse casts coarse; seen from high up, a field of grass no longer laid an unseen square of shadow on the ground. The terrain's vertices slide between levels by the eye the ground was chosen for in every pass, so a shadow's ground is the ground that is seen, under an orthographic camera too.- **Ridged ground without end has no steps.** Infinite noise ground that was both ridged and worn broke into terraces with sheer walls where a ridge's fold turned; the crest is now rounded over a few hundredths, so the ground is continuous.- **The running game's resolution can be chosen.** A picker beside Play shows the target screen and stays usable while the game runs (it used to sit in a menu that was disabled in Play), with Free Aspect, the project's design resolution, the device presets and portrait or landscape; the choice is kept per project. ([#100](https://github.com/esengine/estella/issues/100))diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdxindex 8aaf0e416..1c0de6c7a 100644--- a/docs/astro/src/content/docs/graphics/water.mdx+++ b/docs/astro/src/content/docs/graphics/water.mdx@@ -65,7 +65,9 @@ terrain changes, at a cost of the texels times the bodies.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 speedthat 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**:+field: its body's `waveHeight`, times the share the shore leaves, times the weather's (a `Weather` that drives the wind scales the waves as far as the water+is open to it: wind waves grow with the water they blow over, so the sea takes the weather whole, a lake the more the wider it is against eight `waveLength`s,+and a river hardly at all). 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 andthe silhouette against the sky rises and falls with the waves.@@ -79,7 +81,8 @@ for an ocean over a beach as for a lake), and over the last four `surfLength`s othe shore and a long back, travelling in at the speed of a deep-water wave of their length times `waveSpeed`. They grow as the water shoals, whiten wherethey break in the inner part of that band and stay white behind the crest a while, and past the shore they run up the ground: the surface is drawn theretoo, a little above the water's rest height, and the depth test cuts it where the ground rises above it, so the waterline climbs a beach and falls back.-A breaker stands `surf` times the body's `waveHeight` (with the weather's waves in); a current carries none, so a river and its mouth stay calm.+A breaker stands `surf` times the body's `waveHeight` (with the weather's waves in), times how open the water is: surf is swell come in from open water, so a+lake's shore laps where the sea's breaks; a current carries none, so a river and its mouth stay calm.`Waters.sample` adds the same surf, so what floats near a beach rides it.## Geometry@@ -169,7 +172,6 @@ at `foamFade` a second, so a splash leaves white water that lingers and thins an- **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 foamwhitens 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.@@ -284,8 +286,11 @@ is its x and z, `u_origin` is where the mesh was moved to as it follows the came- **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 fromabove 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. On a zone's surface the zone writes the four every frame (its own length, speed and heading, and+- **Waves.** `u_waveLength`, `u_waveHeight`, `u_waveSpeed`, `u_waveDirection`; the ripples the wind raises (`u_rippleStrength`, `u_rippleLength`) ride+ on them: six short waves around the wind's heading, from `u_rippleLength` down to a fifth of it, each fading out with distance before it would shimmer.+- **Rain.** When a `Weather` drives the rain, drops ring out on the surface (`u_rain`, written by the zone): rings that spread and die, a few to every+ `u_rippleLength`, more of them the harder it rains, and the surface a little less sharp. They are drawn, not simulated: they put nothing in the zone's ripples+ and make no foam, and they fade out with distance. On a zone's surface the zone writes the four every frame (its own length, speed and heading, andthe 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 thereis. 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 atdiff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdxindex 35a5f2fa6..ec2e46e52 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx@@ -52,13 +52,13 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一## 波浪-四道波峰比波谷更尖的正弦波(`exp(sin(theta) - 1)`),相差几个方向,各自的波长、高度和速度是区域的 `waveLength`、`waveSpeed`、`waveDirection` 的份额。所有水体共用它们;它们在某处有多高,由场里那一处决定:所在水体的 `waveHeight`,乘以岸线留下的份额,再乘以天气的份额(驱动风的 `Weather` 会缩放所有波浪)。它们会**移动几何体**:着色器按波高抬起每个顶点,片元按同一个公式逐像素取斜率,所以被光照的表面就是画出来的表面,和天空交界的轮廓也随波浪起伏。+四道波峰比波谷更尖的正弦波(`exp(sin(theta) - 1)`),相差几个方向,各自的波长、高度和速度是区域的 `waveLength`、`waveSpeed`、`waveDirection` 的份额。所有水体共用它们;它们在某处有多高,由场里那一处决定:所在水体的 `waveHeight`,乘以岸线留下的份额,再乘以天气的份额(驱动风的 `Weather` 会按水面迎风的开阔程度放大波浪:风浪随吹过的水面长度增长,所以海完全受天气影响,湖按其宽度与八个 `waveLength` 之比受影响,河几乎不受影响)。它们会**移动几何体**:着色器按波高抬起每个顶点,片元按同一个公式逐像素取斜率,所以被光照的表面就是画出来的表面,和天空交界的轮廓也随波浪起伏。波浪在世界的 xz 平面上度量,把水面竖直向上抬起。参数以世界单位计:以米为单位的场景用默认值,以厘米为单位的要把长度相应缩放。## 拍岸浪-水与地面相接处,浪朝岸边推进。区域量出每一处沿地面到最近岸线的距离(海洋漫过沙滩和湖泊都是同一种量法),在最后四个 `surfLength` 的水面上,拍岸浪按这个距离立起来:朝岸的一面陡、背面长,以同波长深水波的速度乘 `waveSpeed` 向岸推进。水变浅时浪变高,在这段水域的靠岸部分破碎发白,浪峰过后白沫还会留一阵;过了岸线浪会冲上地面:那里也画出水面,略高于静水面,地面高过它的地方由深度测试裁掉,所以水线会爬上沙滩再退回来。浪头高度是所在水体的 `waveHeight` 乘 `surf`(含天气对波浪的缩放);有水流的地方没有拍岸浪,所以河流和河口保持平静。`Waters.sample` 也加上同样的拍岸浪,沙滩附近的漂浮物会随之起伏。+水与地面相接处,浪朝岸边推进。区域量出每一处沿地面到最近岸线的距离(海洋漫过沙滩和湖泊都是同一种量法),在最后四个 `surfLength` 的水面上,拍岸浪按这个距离立起来:朝岸的一面陡、背面长,以同波长深水波的速度乘 `waveSpeed` 向岸推进。水变浅时浪变高,在这段水域的靠岸部分破碎发白,浪峰过后白沫还会留一阵;过了岸线浪会冲上地面:那里也画出水面,略高于静水面,地面高过它的地方由深度测试裁掉,所以水线会爬上沙滩再退回来。浪头高度是所在水体的 `waveHeight` 乘 `surf`(含天气对波浪的缩放),再乘水面的开阔程度:拍岸浪是从开阔水面传来的涌浪,所以海岸会破浪,湖岸只是轻拍;有水流的地方没有拍岸浪,所以河流和河口保持平静。`Waters.sample` 也加上同样的拍岸浪,沙滩附近的漂浮物会随之起伏。## 几何体@@ -116,7 +116,7 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一`ripples` 大于 0 时,区域会记住扰动水的东西。它保存水面的一个方形窗口(边长 `rippleSize` 世界单位,沿边 `ripples` 个格子),作为一张高度网格,用波动方程推进:每个格子被拉向它的邻居,并带着它原有的速度,所以放进去的一个凸起会以 `rippleSpeed` 的速度扩散成一圈圈环,每秒损失 `rippleDamping` 的高度,最后消失。网格旁边还保存着**泡沫**:扰动在哪里发生就往哪里加泡沫,泡沫按每秒 `foamFade` 消退,所以一次水花留下的白水会逗留、变薄,而不是随着环一起突然消失。-- **谁来扰动。** 脚本调用 `Waters.disturb(x, y, z, radius, strength)`(`strength` 是以世界单位计的高度,负数是下凹;没有水的地方什么也不做),`Floating` 物体也会自己做:落进水里、从水里升出或沿水面运动的东西,会按速度推动水(`wake` 是倍数)。`Weather` 驱动雨时,雨会以雨滴落在窗口上:一个半格宽的小下凹,每秒的个数由雨量决定。+- **谁来扰动。** 脚本调用 `Waters.disturb(x, y, z, radius, strength)`(`strength` 是以世界单位计的高度,负数是下凹;没有水的地方什么也不做),`Floating` 物体也会自己做:落进水里、从水里升出或沿水面运动的东西,会按速度推动水(`wake` 是倍数)。- **它改变什么。** 着色器把网格当纹理读:涟漪的斜率弯折法线,光照、反射和折射看到的就是这个法线;泡沫让表面变白。几何体不会被它抬起。代码读到的表面包含它们:`Waters.sample` 把涟漪的高度加到表面上,`Waters.rippleAt(x, y, z)` 单独给出它,所以一个漂浮的球会被从它下面经过的环托起。- **在哪里。** 窗口以整格为单位跟随活动相机,所以任意大小的水,在看得见的地方都有涟漪,代价只是一张网格,由所有水体共用。窗口离开的地方被遗忘,新到的地方是静水。到达边缘的波会出去而不是被反射。网格在 CPU 上推进,子步数以保证波一步不跨过超过半个格子为准,并作为 RGBA8 纹理上传(红是高度,绿是泡沫):各后端一致。@@ -197,7 +197,8 @@ Details 只显示水体这种形态用得到的字段:湖有尺寸和边界,河`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_rippleLength` 到它的五分之一,每道在会闪烁之前随距离淡出。+- **雨。** `Weather` 驱动雨时,雨滴在水面上激起环纹(`u_rain`,由区域写入):向外扩散然后消失的圆环,每个 `u_rippleLength` 里有几个,雨越大越多,水面也稍微变得不那么锐利。它们是画出来的而不是模拟的:不会往区域的涟漪里放任何东西,也不产生泡沫,并随距离淡出。在区域的水面上,这四个由区域每帧写入(它自己的波长、速度和方向,高度则是天气的份额,再乘以场里每一处的高度),所以材质里这四个值在那里不起作用。- **折射与水深。** 水下看到的是不透明场景的画面,被波浪按水量多少偏移。水深是**量出来的**:绘制水之前,帧会拷贝一份场景每个像素离眼睛多远,水在某个像素处的深度就是那个距离与水面自己的距离之差。光沿着这段水柱被吸收——红色最先(`u_absorption`、`u_density`)——水再还给你它自己的颜色,随水变深从 `u_shallowColor` 过渡到 `u_deepColor`。- **反射。** 天空、灯光和环境按菲涅尔项反射(水是 1.333),所以俯视时清澈、掠射时像镜子。想要场景本身的倒影,在体积里加上屏幕空间反射。- **泡沫。** 水柱浅于 `u_foamWidth` 的地方(岸边、礁石、桥墩脚下)和波峰上(`u_foamCrest`)出现泡沫,由流动的噪声打散。在区域的水面上,烘好的岸线也起泡沫,范围是离岸边或浅水 `u_foamWidth` 以内,所以量不出深度的地方岸边也有泡沫。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 330be44ba..a2773f775 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4044,6 +4044,7 @@ unit: string | undefinedamp: numbercalm: numberdepth: number+exposure: numberflowX: numberflowZ: numberheight: number@@ -11728,7 +11729,8 @@ amp: Float32Array<ArrayBufferLike>at: (x: number, z: number) => FieldSample | nullcalm: Float32Array<ArrayBufferLike>depth: Float32Array<ArrayBufferLike>-encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array; }+exposure: Float32Array<ArrayBufferLike>flowX: Float32Array<ArrayBufferLike>flowZ: Float32Array<ArrayBufferLike>grid: ZoneGriddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 7c0c3f70f..7afdece97 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -4052,6 +4052,7 @@ unit: string | undefinedamp: numbercalm: numberdepth: number+exposure: numberflowX: numberflowZ: numberheight: number@@ -11941,7 +11942,8 @@ amp: Float32Array<ArrayBufferLike>at: (x: number, z: number) => FieldSample | nullcalm: Float32Array<ArrayBufferLike>depth: Float32Array<ArrayBufferLike>-encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array; }+exposure: Float32Array<ArrayBufferLike>flowX: Float32Array<ArrayBufferLike>flowZ: Float32Array<ArrayBufferLike>grid: ZoneGriddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 910149118..d15b73f39 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4039,6 +4039,7 @@ unit: string | undefinedamp: numbercalm: numberdepth: number+exposure: numberflowX: numberflowZ: numberheight: number@@ -11723,7 +11724,8 @@ amp: Float32Array<ArrayBufferLike>at: (x: number, z: number) => FieldSample | nullcalm: Float32Array<ArrayBufferLike>depth: Float32Array<ArrayBufferLike>-encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array; }+exposure: Float32Array<ArrayBufferLike>flowX: Float32Array<ArrayBufferLike>flowZ: Float32Array<ArrayBufferLike>grid: ZoneGriddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex b5664ee7c..3f8531305 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -4039,6 +4039,7 @@ unit: string | undefinedamp: numbercalm: numberdepth: number+exposure: numberflowX: numberflowZ: numberheight: number@@ -12022,7 +12023,8 @@ amp: Float32Array<ArrayBufferLike>at: (x: number, z: number) => FieldSample | nullcalm: Float32Array<ArrayBufferLike>depth: Float32Array<ArrayBufferLike>-encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array; }+exposure: Float32Array<ArrayBufferLike>flowX: Float32Array<ArrayBufferLike>flowZ: Float32Array<ArrayBufferLike>grid: ZoneGriddiff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.mdindex fa1a1777f..a192265ae 100644--- a/sdk/etc/water.api.md+++ b/sdk/etc/water.api.md@@ -36,6 +36,7 @@ seaLevel: number | undefinedamp: numbercalm: numberdepth: number+exposure: numberflowX: numberflowZ: numberheight: number@@ -98,7 +99,6 @@ n: numberoriginX: numberoriginZ: numberpeak: () => number-rainOwed: numberrecenter: (x: number, z: number) => booleansize: numberstep: (dt: number, speed: number, damping: number, foamFade: number) => void@@ -143,7 +143,8 @@ amp: Float32Array<ArrayBufferLike>at: (x: number, z: number) => FieldSample | nullcalm: Float32Array<ArrayBufferLike>depth: Float32Array<ArrayBufferLike>-encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array; }+exposure: Float32Array<ArrayBufferLike>flowX: Float32Array<ArrayBufferLike>flowZ: Float32Array<ArrayBufferLike>grid: ZoneGriddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0f2c8654e..947ce0310 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4039,6 +4039,7 @@ unit: string | undefinedamp: numbercalm: numberdepth: number+exposure: numberflowX: numberflowZ: numberheight: number@@ -11730,7 +11731,8 @@ amp: Float32Array<ArrayBufferLike>at: (x: number, z: number) => FieldSample | nullcalm: Float32Array<ArrayBufferLike>depth: Float32Array<ArrayBufferLike>-encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; }+encode: (r: ZoneRanges) => { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array; }+exposure: Float32Array<ArrayBufferLike>flowX: Float32Array<ArrayBufferLike>flowZ: Float32Array<ArrayBufferLike>grid: ZoneGriddiff --git a/sdk/src/water/ripples.ts b/sdk/src/water/ripples.tsindex 82c1fffed..53579d380 100644--- a/sdk/src/water/ripples.ts+++ b/sdk/src/water/ripples.ts@@ -25,8 +25,6 @@ export class RippleField {/** World size of one cell. */readonly cell: number;/** The window's minimum corner in the body's xz plane. */- /** Drops of rain owed to the window: the weather asks for a rate, a frame takes whole drops and carries the rest. */- rainOwed = 0;originX = 0;originZ = 0;/** The most height a cell may hold, either way: disturbances that go on (a body moving) saturate here instead of piling up. */diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex a809cb2e8..e5f4a1abd 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -164,10 +164,11 @@ export class Waters {const s = field.sample(x, z);if (!s) return null;const time = this.app_.getResource(Time).elapsed;- const params = this.waves(s.amp);+ const params = this.waves(s.amp, s.exposure);const zone = this.zone_;const still = 1 - Math.min(Math.hypot(s.flowX, s.flowZ) / Math.max(field.ranges().flow * 0.25, 1e-4), 1);- const surf = surfHeight(s.shore, zone.surf * weatherWaves() * s.swell * still, zone.surfLength, zone.waveSpeed, time);+ // Surf is swell come in from open water: sheltered water has as little of it as it is sheltered.+ const surf = surfHeight(s.shore, zone.surf * grown(s.exposure) * s.swell * s.exposure * still, zone.surfLength, zone.waveSpeed, time);// 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) + surf : 0) + (this.ripples_?.heightAt(x, z) ?? 0);const [sx, sz] = waveSlope(params, x, z, time);@@ -216,9 +217,9 @@ export class Waters {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 };+ /** The waves as they stand where the zone says they are `amp` high: the zone's, at that height, raised by the weather as far as the water is open to it. */+ private waves(amp: number, exposure = 1): WaveParams {+ return { ...waveParamsOf(this.zone_), height: amp * grown(exposure), count: this.quality.waves };}}@@ -238,6 +239,33 @@ function weatherWaves(): number {return w && (currentWeatherDrive() & WeatherDrive.Wind) ? w.waves : 1;}+/** How far the weather raises the waves of water `exposure` open to the wind: all the way on open sea, little on a sheltered pond. */+/** @internal */+export function grown(exposure: number): number {+ return 1 + (weatherWaves() - 1) * Math.min(Math.max(exposure, 0), 1);+}++/**+ * How open a body is to the wind, 0 to 1: wind waves grow with the water they blow over (their fetch), so the weather raises them fully+ * on the sea and the more on a lake the wider it is, against eight of the zone's wave lengths; a river's fetch is its width.+ */+/** @internal */+export function exposureOf(body: ZoneBody, waveLength: number): number {+ if (body.kind === 'ocean') return 1;+ let fetch: number;+ if (body.kind === 'lake') {+ let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;+ 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);+ }+ fetch = Math.min(maxX - minX, maxZ - minZ);+ } else {+ fetch = body.stations.reduce((n, s) => n + s.half * 2, 0) / Math.max(body.stations.length, 1);+ }+ return Math.min(Math.max(fetch / Math.max(waveLength * 8, 1e-6), 0.1), 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();@@ -250,18 +278,11 @@ export function waveParamsOf(zone: Pick<WaterZoneData, 'waveLength' | 'waveSpeed}/**- * 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.+ * How hard it rains on the water: the weather's rain, which the Water shader rings out as drops on the surface (`u_rain`). Rain is+ * drawn, not simulated: it puts nothing in the ripples a zone keeps, and no foam.*/-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);- }+export function rainOnWater(): number {+ return weatherRain();}type Quat = { x: number; y: number; z: number; w: number };@@ -326,6 +347,7 @@ interface Surface {material: number;heights: number;field: number;+ exposure: number;/** Which bake the textures hold. */baked: WaterField | null;ripple: number;@@ -471,9 +493,10 @@ export class WaterPlugin implements Plugin {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) };}+ for (const b of bodies) b.exposure = exposureOf(b, zone.waveLength);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, zone.surfLength]) };+ return { bodies, grid, zone, key: JSON.stringify([keyParts, grid, ground, zone.surfLength, zone.waveLength]) };}/** The world height of the ground, where a terrain is built. */@@ -504,7 +527,7 @@ export class WaterPlugin implements Plugin {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 };+ s = { entity: 0 as Entity, mesh: 0, meshKey, instance: 0, material: zone.material, heights: 0, field: 0, exposure: 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);@@ -542,7 +565,7 @@ export class WaterPlugin implements Plugin {private upload(app: App, s: Surface, field: WaterField): void {this.dropFieldTextures(s);const ranges = field.ranges(this.waters_.zone_.surfLength * 4);- const { heights, field: rest } = field.encode(ranges);+ const { heights, field: rest, exposure } = 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;@@ -550,10 +573,13 @@ export class WaterPlugin implements Plugin {{ 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.exposure = createTextureFromPixels(app.wasmModule, { width: w, height: h, pixels: empty ? new Uint8Array(16).fill(255) : exposure }, 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));+ set('u_zoneExposure', Material.tex(s.exposure));// 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 });@@ -582,6 +608,7 @@ export class WaterPlugin implements Plugin {set('u_cellSize', zone.cellSize);set('u_geoWaves', q.displacement ? 1 : 0);set('u_waveHeight', waves.height);+ set('u_rain', rainOnWater());set('u_waveLength', waves.length);set('u_waveSpeed', waves.speed);set('u_waveDirection', waves.direction);@@ -611,7 +638,6 @@ export class WaterPlugin implements Plugin {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;@@ -659,8 +685,10 @@ export class WaterPlugin implements Plugin {const rm = getResourceManager();if (s.heights) rm?.releaseTexture(s.heights);if (s.field) rm?.releaseTexture(s.field);+ if (s.exposure) rm?.releaseTexture(s.exposure);s.heights = 0;s.field = 0;+ s.exposure = 0;s.baked = null;}diff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.tsindex ad2d1f79c..1309ac5a8 100644--- a/sdk/src/water/waterShader.ts+++ b/sdk/src/water/waterShader.ts@@ -31,6 +31,8 @@ const WATER = `#pragma shader "Water"// The small ripples the long waves carry: how steep and how long each is.#pragma param u_rippleStrength float default(0.3) range(0,1) ui(slider)#pragma param u_rippleLength float default(2.5) range(0.1,40) ui(slider)+// How hard it rains on the water (the weather writes it): drops ring out on the surface, a few to every u_rippleLength.+#pragma param u_rain float default(0) range(0,4) ui(slider)#pragma param u_roughness float default(0.04) range(0,1) ui(slider)// How far what is seen through the water is shifted by its waves, and the depth of water at which that stops growing.#pragma param u_refractionStrength float default(1) range(0,4) ui(slider)@@ -58,6 +60,8 @@ const WATER = `#pragma shader "Water"#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)+// How open each place's water is to the wind (its fetch), 0 to 1: the weather raises the waves that much of the way. The sea is open.+#pragma param u_zoneExposure 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)@@ -116,7 +120,7 @@ float waterWaveHeight(vec2 p, float time, float cell) {}// 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) {+vec4 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);@@ -128,8 +132,11 @@ vec3 waterZoneAt(vec2 p) {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 weather (u_waveHeight) raises a body's waves only as far as the wind has room to: w is that share, and z is put so that+ // u_waveHeight times it is the waves' height there.+ float e = textureLod(u_zoneExposure, clamp(uv, 0.0, 1.0), 0.0).r;+ vec4 zone = vec4(u_zoneHeight.x + h * u_zoneHeight.y, da.x * u_zoneRange.w, da.y * u_zoneRange.y * mix(1.0, u_waveHeight, e) / max(u_waveHeight, 1e-3), e);+ return !inside && u_oceanOn > 0.5 ? vec4(u_oceanLevel, 1e6, u_oceanWaves, 1.0) : zone;}// The zone's field at p, decoded: the shore distance, the current, and the share of its waves a place keeps. Past the region: the ocean's.vec4 waterZoneField(vec2 p) {@@ -163,10 +170,10 @@ void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {float cell = u_cellSize > 0.0 ? u_cellSize * exp2(es_vertexColor.r * 7.0) : 0.0;// The water's rest height there, how high its body's waves stand (a multiple of u_waveHeight, the weather's) and the share kept toward// the shore; and the surf running in on it, which a current carries none of.- vec3 zone = u_zoneOn > 0.5 ? waterZoneAt(p) : vec3(0.0, 0.0, 1.0);+ vec4 zone = u_zoneOn > 0.5 ? waterZoneAt(p) : vec4(0.0, 0.0, 1.0, 1.0);vec4 field = u_zoneOn > 0.5 ? waterZoneField(p) : vec4(1e6, 0.0, 0.0, 1.0);float still = 1.0 - clamp(length(field.yz) / max(u_zoneRange.z * 0.25, 1e-4), 0.0, 1.0);- float surf = waterSurf(field.x, u_surfHeight * u_waveHeight * zone.z * still, u_time.x).x;+ float surf = waterSurf(field.x, u_surfHeight * u_waveHeight * zone.z * zone.w * still, u_time.x).x;local.y += zone.x + (waterWaveHeight(p, u_time.x, cell) * zone.z * field.w + surf) * u_geoWaves;}#pragma end@@ -190,7 +197,7 @@ fn waterWaveHeight(p : vec2f, time : f32, cell : f32) -> f32 {}return height;}-fn waterZoneAt(p : vec2f) -> vec3f {+fn waterZoneAt(p : vec2f) -> vec4f {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));@@ -204,8 +211,10 @@ fn waterZoneAt(p : vec2f) -> vec3f {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);+ let e = textureSampleLevel(u_zoneExposure, u_zoneExposure_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).r;+ if (!inside && mc.u_oceanOn > 0.5) { return vec4f(mc.u_oceanLevel, 1e6, mc.u_oceanWaves, 1.0); }+ return vec4f(mc.u_zoneHeight.x + h * mc.u_zoneHeight.y, da.x * mc.u_zoneRange.w,+ da.y * mc.u_zoneRange.y * mix(1.0, mc.u_waveHeight, e) / max(mc.u_waveHeight, 1e-3), e);}fn waterZoneField(p : vec2f) -> vec4f {let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));@@ -239,11 +248,11 @@ fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, velet 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 zone = vec3f(0.0, 0.0, 1.0);+ var zone = vec4f(0.0, 0.0, 1.0, 1.0);var field = vec4f(1e6, 0.0, 0.0, 1.0);if (mc.u_zoneOn > 0.5) { zone = waterZoneAt(p); field = waterZoneField(p); }let still = 1.0 - clamp(length(field.yz) / max(mc.u_zoneRange.z * 0.25, 1e-4), 0.0, 1.0);- let surf = waterSurf(field.x, mc.u_surfHeight * mc.u_waveHeight * zone.z * still, tc.u_time.x).x;+ let surf = waterSurf(field.x, mc.u_surfHeight * mc.u_waveHeight * zone.z * zone.w * still, tc.u_time.x).x;(*local).y = (*local).y + zone.x + (waterWaveHeight(p, tc.u_time.x, cell) * zone.z * field.w + surf) * mc.u_geoWaves;}#pragma end@@ -285,10 +294,51 @@ float waterNoise(vec2 p) {return mix(mix(waterHash(i), waterHash(i + vec2(1.0, 0.0)), f.x),mix(waterHash(i + vec2(0.0, 1.0)), waterHash(i + vec2(1.0, 1.0)), f.x), f.y);}-/// The ripples' height at p: two layers of noise drifting in different directions.-float ripples(vec2 p, float time) {- return waterNoise(p / u_rippleLength + vec2(0.31, 0.12) * time) * 0.6- + waterNoise(p / (u_rippleLength * 0.43) - vec2(0.17, 0.4) * time) * 0.4;+/// The slope of the ripples the wind raises at p: six short waves within forty degrees of it, from u_rippleLength down to a fifth of it, each+/// running at the speed its length gives deep water and at a phase of its own, each as steep as u_rippleStrength a third. A sum of waves+/// has no cells or blobs, which drifting noise has. A ripple shorter than a pixel would shimmer: each fades out with distance.+vec2 rippleSlope(vec2 p, float time, float dist) {+ const vec3 SET[6] = vec3[6](vec3(-12.0, 1.0, 0.0), vec3(23.0, 0.71, 1.7), vec3(-35.0, 0.53, 3.1),+ vec3(8.0, 0.39, 4.4), vec3(41.0, 0.29, 0.9), vec3(-27.0, 0.21, 2.6));+ float base = radians(u_waveDirection);+ vec2 slope = vec2(0.0);+ for (int i = 0; i < 6; ++i) {+ float len = u_rippleLength * SET[i].y;+ float k = 6.2831853 / len;+ float a = base + radians(SET[i].x);+ vec2 d = vec2(sin(a), cos(a));+ float theta = k * dot(d, p) - sqrt(9.8 * k) * u_waveSpeed * time + SET[i].z;+ float seen = clamp(1.0 - dist / (len * 150.0), 0.0, 1.0);+ slope += d * (cos(theta) * seen * 0.33);+ }+ return slope * u_rippleStrength;+}++/// The slope rain adds at p: in every cell of two offset grids a third of u_rippleLength across, a drop lands at a place and a moment of+/// its own once a cycle, and a ring runs out from it and dies away. Harder rain wets more of the cells. No foam: a raindrop makes none.+vec2 rainRings(vec2 p, float time, float rain) {+ vec2 slope = vec2(0.0);+ if (rain <= 0.0) return slope;+ float cellSize = u_rippleLength * 0.35;+ const float K = 52.0;+ for (int layer = 0; layer < 2; layer++) {+ vec2 q = p / cellSize + float(layer) * vec2(0.37, 0.71);+ vec2 cell = floor(q) + float(layer) * 113.0;+ float h = waterHash(cell);+ float rate = 0.8 + 0.5 * h;+ float cycle = time * rate + h * 7.31;+ vec2 drop = cell + floor(cycle) * vec2(17.0, 31.0);+ if (waterHash(drop + 0.5) > clamp(rain * 0.4, 0.0, 0.9)) continue;+ float t = fract(cycle);+ vec2 centre = floor(q) + 0.25 + 0.5 * vec2(waterHash(drop + 3.1), waterHash(drop + 5.7));+ vec2 d = q - centre;+ float r = max(length(d), 1e-4);+ float x = r - t * 0.45;+ float env = (1.0 - t) * (1.0 - t) * exp(-x * x * 900.0);+ float dh = (cos(x * K) - x * 1800.0 / K * sin(x * K)) * env;+ slope += d / r * dh * 0.3;+ }+ return slope;}/// The slope of the water's surface at p (d height / d x, d height / d z) and how near the waves are to a crest, 0 to 1.@@ -321,7 +371,7 @@ 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) {+vec4 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);@@ -333,8 +383,11 @@ vec3 waterZoneAt(vec2 p) {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 weather (u_waveHeight) raises a body's waves only as far as the wind has room to: w is that share, and z is put so that+ // u_waveHeight times it is the waves' height there.+ float e = textureLod(u_zoneExposure, clamp(uv, 0.0, 1.0), 0.0).r;+ vec4 zone = vec4(u_zoneHeight.x + h * u_zoneHeight.y, da.x * u_zoneRange.w, da.y * u_zoneRange.y * mix(1.0, u_waveHeight, e) / max(u_waveHeight, 1e-3), e);+ return !inside && u_oceanOn > 0.5 ? vec4(u_oceanLevel, 1e6, u_oceanWaves, 1.0) : zone;}// The zone's field at p, decoded: the shore distance, the current, and the share of its waves a place keeps. Past the region: the ocean's.vec4 waterZoneField(vec2 p) {@@ -428,11 +481,7 @@ vec4 waterReflect(vec3 p, vec3 r, float eyeDist) {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 * calm);+ return slope + rippleSlope(p, time, dist) * calm;}void main() {@@ -450,7 +499,7 @@ void main() {// 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);+ vec4 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;@@ -461,7 +510,7 @@ void main() {vec2 flow = zoneOn && zoneIn ? (zoneTex.gb - 0.5) * 2.0 * u_zoneRange.z : vec2(0.0);// The surf: its height across the shore distance gives its slope along the way to the shore, and where it breaks it is white.float still = 1.0 - clamp(length(flow) / max(u_zoneRange.z * 0.25, 1e-4), 0.0, 1.0);- float surfH = zoneOn ? u_surfHeight * u_waveHeight * zone.z * still : 0.0;+ float surfH = zoneOn ? u_surfHeight * u_waveHeight * zone.z * zone.w * still : 0.0;float surfStep = max(u_zoneSize.x / float(textureSize(u_zoneField, 0).x), 1e-3);vec2 toSea = vec2(waterZoneField(wp + vec2(surfStep, 0.0)).x - waterZoneField(wp - vec2(surfStep, 0.0)).x,waterZoneField(wp + vec2(0.0, surfStep)).x - waterZoneField(wp - vec2(0.0, surfStep)).x) / (2.0 * surfStep);@@ -497,7 +546,9 @@ void main() {} else {slope = waterSurface(wp, time, waterDist, damp, calm, crest);}- slope += ripSlope + toSea * (surfRise * u_geoWaves);+ // Rain rings are fine: where a pixel grows past a ring's crests they would shimmer, so they fade out before it.+ float rainFade = 1.0 - smoothstep(u_rippleLength * 8.0, u_rippleLength * 20.0, waterDist);+ slope += ripSlope + toSea * (surfRise * u_geoWaves) + rainRings(wp, time, u_rain) * rainFade;vec3 N = normalize(vec3(-slope.x, 1.0, -slope.y));vec3 Ngeo = vec3(0.0, 1.0, 0.0);#ifdef MESH_NORMALS@@ -581,7 +632,8 @@ void main() {SurfaceExt ext = surfaceExtNone(N);ext.misc.x = 0.0204;vec3 albedo = mix(scatterColor * murk, u_foamColor.rgb, foam);- float roughness = mix(u_roughness, 0.7, foam);+ // Rain stipples the surface finer than any ring: it reflects a little less sharply.+ float roughness = mix(u_roughness + 0.05 * clamp(u_rain, 0.0, 1.0), 0.7, foam);vec3 lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, roughness, 1.0, 1.0, ext);float cosV = clamp(dot(N, viewDir), 0.0, 1.0);float fresnel = 0.0204 + (1.0 - 0.0204) * pow(1.0 - cosV, 5.0);@@ -652,9 +704,47 @@ fn waterNoise(p : vec2f) -> f32 {return mix(mix(waterHash(i), waterHash(i + vec2f(1.0, 0.0)), f.x),mix(waterHash(i + vec2f(0.0, 1.0)), waterHash(i + vec2f(1.0, 1.0)), f.x), f.y);}-fn ripples(p : vec2f, time : f32) -> f32 {- return waterNoise(p / mc.u_rippleLength + vec2f(0.31, 0.12) * time) * 0.6- + waterNoise(p / (mc.u_rippleLength * 0.43) - vec2f(0.17, 0.4) * time) * 0.4;+fn rippleSlope(p : vec2f, time : f32, dist : f32) -> vec2f {+ let SET = array<vec3f, 6>(vec3f(-12.0, 1.0, 0.0), vec3f(23.0, 0.71, 1.7), vec3f(-35.0, 0.53, 3.1),+ vec3f(8.0, 0.39, 4.4), vec3f(41.0, 0.29, 0.9), vec3f(-27.0, 0.21, 2.6));+ let base = radians(mc.u_waveDirection);+ var slope = vec2f(0.0);+ for (var i = 0; i < 6; i++) {+ let w = SET[i];+ let len = mc.u_rippleLength * w.y;+ let k = 6.2831853 / len;+ let a = base + radians(w.x);+ let d = vec2f(sin(a), cos(a));+ let theta = k * dot(d, p) - sqrt(9.8 * k) * mc.u_waveSpeed * time + w.z;+ let seen = clamp(1.0 - dist / (len * 150.0), 0.0, 1.0);+ slope = slope + d * (cos(theta) * seen * 0.33);+ }+ return slope * mc.u_rippleStrength;+}++fn rainRings(p : vec2f, time : f32, rain : f32) -> vec2f {+ var slope = vec2f(0.0);+ if (rain <= 0.0) { return slope; }+ let cellSize = mc.u_rippleLength * 0.35;+ let K = 52.0;+ for (var layer = 0; layer < 2; layer++) {+ let q = p / cellSize + f32(layer) * vec2f(0.37, 0.71);+ let cell = floor(q) + f32(layer) * 113.0;+ let h = waterHash(cell);+ let rate = 0.8 + 0.5 * h;+ let cycle = time * rate + h * 7.31;+ let drop = cell + floor(cycle) * vec2f(17.0, 31.0);+ if (waterHash(drop + 0.5) > clamp(rain * 0.4, 0.0, 0.9)) { continue; }+ let t = fract(cycle);+ let centre = floor(q) + 0.25 + 0.5 * vec2f(waterHash(drop + 3.1), waterHash(drop + 5.7));+ let d = q - centre;+ let r = max(length(d), 1e-4);+ let x = r - t * 0.45;+ let env = (1.0 - t) * (1.0 - t) * exp(-x * x * 900.0);+ let dh = (cos(x * K) - x * 1800.0 / K * sin(x * K)) * env;+ slope = slope + d / r * dh * 0.3;+ }+ return slope;}struct Waves { slope : vec2f, crest : f32 };@@ -687,7 +777,7 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {}${CAUSTICS_WGSL}-fn waterZoneAt(p : vec2f) -> vec3f {+fn waterZoneAt(p : vec2f) -> vec4f {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));@@ -701,8 +791,10 @@ fn waterZoneAt(p : vec2f) -> vec3f {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);+ let e = textureSampleLevel(u_zoneExposure, u_zoneExposure_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).r;+ if (!inside && mc.u_oceanOn > 0.5) { return vec4f(mc.u_oceanLevel, 1e6, mc.u_oceanWaves, 1.0); }+ return vec4f(mc.u_zoneHeight.x + h * mc.u_zoneHeight.y, da.x * mc.u_zoneRange.w,+ da.y * mc.u_zoneRange.y * mix(1.0, mc.u_waveHeight, e) / max(mc.u_waveHeight, 1e-3), e);}fn waterZoneField(p : vec2f) -> vec4f {let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));@@ -795,11 +887,7 @@ 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, 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 * amp + ripple * (mc.u_rippleStrength * mc.u_rippleLength * rippleFade * calm), waves.crest * calm);+ return vec3f(waves.slope * amp + rippleSlope(p, time, dist) * calm, waves.crest * calm);}#ifdef ES_GBUFFER@@ -841,7 +929,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec}let still = 1.0 - clamp(length(flow) / max(mc.u_zoneRange.z * 0.25, 1e-4), 0.0, 1.0);var surfH = 0.0;- if (zoneOn) { surfH = mc.u_surfHeight * mc.u_waveHeight * zone.z * still; }+ if (zoneOn) { surfH = mc.u_surfHeight * mc.u_waveHeight * zone.z * zone.w * still; }let surfStep = max(mc.u_zoneSize.x / f32(textureDimensions(u_zoneField, 0).x), 1e-3);let toSea = vec2f(waterZoneField(wp + vec2f(surfStep, 0.0)).x - waterZoneField(wp - vec2f(surfStep, 0.0)).x,waterZoneField(wp + vec2f(0.0, surfStep)).x - waterZoneField(wp - vec2f(0.0, surfStep)).x) / (2.0 * surfStep);@@ -876,7 +964,8 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec}var waves : Waves;waves.crest = surface.z;- var slope = surface.xy + ripSlope + toSea * (surfRise * mc.u_geoWaves);+ let rainFade = 1.0 - smoothstep(mc.u_rippleLength * 8.0, mc.u_rippleLength * 20.0, waterDist);+ var slope = surface.xy + ripSlope + toSea * (surfRise * mc.u_geoWaves) + rainRings(wp, time, mc.u_rain) * rainFade;var N = normalize(vec3f(-slope.x, 1.0, -slope.y));var Ngeo = vec3f(0.0, 1.0, 0.0);#ifdef MESH_NORMALS@@ -953,7 +1042,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vecvar ext = surfaceExtNone(N);ext.misc.x = 0.0204;let albedo = mix(scatterColor * murk, mc.u_foamColor.rgb, vec3f(foam));- let roughness = mix(mc.u_roughness, 0.7, foam);+ let roughness = mix(mc.u_roughness + 0.05 * clamp(mc.u_rain, 0.0, 1.0), 0.7, foam);let lit = applyLightingSurface(albedo, N, P, viewDir, 0.0, roughness, 1.0, 1.0, ext);let cosV = clamp(dot(N, viewDir), 0.0, 1.0);var fresnel = 0.0204 + (1.0 - 0.0204) * pow(1.0 - cosV, 5.0);diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.tsindex aeefaa0f7..1a71dd2b8 100644--- a/sdk/src/water/zone.ts+++ b/sdk/src/water/zone.ts@@ -89,11 +89,15 @@ export const WaterZone: ComponentDef<WaterZoneData> = defineComponent<WaterZoneD* An ocean, as the zone takes it: at `level` wherever the ground is below it and joined to the open sea, which is past the region's* edge. A basin below the sea's level that no low ground joins to the edge is dry land, not sea.*/-export interface ZoneOcean { kind: 'ocean'; key: number; level: number; waveHeight: number; shoreWidth: number }+export interface ZoneOcean {+ kind: 'ocean'; key: number; level: number; waveHeight: number; shoreWidth: number;+ /** How open the water is to the wind, 0 to 1 (its fetch): how far the weather raises its waves. Open sea, 1 when absent. */+ exposure?: 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;+ kind: 'lake'; key: number; level: number; waveHeight: number; shoreWidth: number; exposure?: number;outline: readonly Point2[];/** A world (x, z) in the outline's own space, and back. */toLocal(x: number, z: number): [number, number];@@ -104,7 +108,7 @@ export interface ZoneLake {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 interface ZoneRiver { kind: 'river'; key: number; waveHeight: number; shoreWidth: number; exposure?: number; stations: readonly RiverStation[] }export type ZoneBody = ZoneOcean | ZoneLake | ZoneRiver;@@ -132,6 +136,8 @@ export interface FieldSample {/** The signed distance to the nearest shore (positive on the water) and how deep the water is over the ground. */shore: number;depth: number;+ /** How open it is to the wind, 0 to 1: how far the weather raises its waves (see {@link ZoneOcean.exposure}). */+ exposure: 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. */@@ -153,6 +159,7 @@ export class WaterField {readonly flowX: Float32Array;readonly flowZ: Float32Array;readonly depth: Float32Array;+ readonly exposure: 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. */@@ -170,6 +177,7 @@ export class WaterField {this.flowX = new Float32Array(n);this.flowZ = new Float32Array(n);this.depth = new Float32Array(n);+ this.exposure = new Float32Array(n).fill(1);this.owner = new Int32Array(n);}@@ -212,7 +220,7 @@ export class WaterField {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 = Number.isNaN(grounds[k]!) ? null : grounds[k]!;- let w = 0, h = 0, a = 0, c = 0, sw = 0, fx = 0, fz = 0, best = -Infinity, owner = -1, ownerW = 0, held = 0;+ let w = 0, h = 0, a = 0, c = 0, sw = 0, ex = 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;@@ -223,6 +231,7 @@ export class WaterField {if (weight <= 0) continue;held = Math.max(held, weight);w += weight; h += say.height * weight; a += say.amp * weight; c += say.calm * weight; sw += bounded[b]!.waveHeight * weight; fx += say.fx * weight; fz += say.fz * weight;+ ex += (bounded[b]!.exposure ?? 1) * weight;if (weight > ownerW) { ownerW = weight; owner = bounded[b]!.key; }}if (ocean) {@@ -233,6 +242,7 @@ export class WaterField {if (weight > 0) {const calm = shoreDamp(deep, ocean.shoreWidth);w += weight; h += ocean.level * weight; a += ocean.waveHeight * calm * weight; c += calm * weight; sw += ocean.waveHeight * weight;+ ex += (ocean.exposure ?? 1) * weight;if (weight > ownerW) { ownerW = weight; owner = ocean.key; }}}@@ -243,6 +253,7 @@ export class WaterField {field.amp[k] = a / w;field.calm[k] = c / w;field.swell[k] = sw / w;+ field.exposure[k] = ex / w;field.flowX[k] = fx / w;field.flowZ[k] = fz / w;} else {@@ -273,7 +284,7 @@ export class WaterField {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), swell: lerp2(this.swell), flowX: lerp2(this.flowX), flowZ: lerp2(this.flowZ),- shore: lerp2(this.shore), depth: lerp2(this.depth),+ shore: lerp2(this.shore), depth: lerp2(this.depth), exposure: lerp2(this.exposure),};}@@ -286,7 +297,7 @@ export class WaterField {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, swell: o.waveHeight, flowX: 0, flowZ: 0, shore: DEEP, depth: DEEP };+ return { key: o.key, height: o.level, amp: o.waveHeight, calm: 1, swell: o.waveHeight, flowX: 0, flowZ: 0, shore: DEEP, depth: DEEP, exposure: o.exposure ?? 1 };}/** The ranges the encoding spans, from what the field holds; the shore distance reaches `shoreReach` at least (as far out as the surf is drawn). */@@ -314,11 +325,11 @@ export class WaterField {/*** 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 swell (the body's 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`.+ * exposure (filtered): r how open the water is to the wind. Each over its range in `r`.*/- encode(r: ZoneRanges): { heights: Uint8Array; field: Uint8Array } {+ encode(r: ZoneRanges): { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array } {const n = this.height.length;- const heights = new Uint8Array(n * 4), field = new Uint8Array(n * 4);+ const heights = new Uint8Array(n * 4), field = new Uint8Array(n * 4), exposure = 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);@@ -330,8 +341,10 @@ export class WaterField {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]!);+ exposure[k * 4] = byte(this.exposure[k]!);+ exposure[k * 4 + 3] = 255;}- return { heights, field };+ return { heights, field, exposure };}}@@ -464,7 +477,10 @@ function* levelShore(field: WaterField, texel: number): Generator<number, void,}}-/** 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. */+/**+ * A texel no body holds takes the height (and how open it is to the wind) of the nearest that one does: two passes of a chamfer sweep over+ * which texel is nearest. The shore's filtered reads then see the water's own, not the dry land's.+ */function* fillDry(field: WaterField): Generator<number, void, void> {const { nx, nz } = field.grid;const n = nx * nz;@@ -496,6 +512,7 @@ function* fillDry(field: WaterField): Generator<number, void, void> {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;+ if (src[k]! >= 0) field.exposure[k] = field.exposure[src[k]!]!;}}diff --git a/sdk/tests/water-weather.test.ts b/sdk/tests/water-weather.test.tsindex 9bed93419..185e37edd 100644--- a/sdk/tests/water-weather.test.ts+++ b/sdk/tests/water-weather.test.ts@@ -1,8 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { afterEach, describe, expect, it } from 'vitest';-import { waveParamsOf, rainOnRipples } from '../src/water/waterPlugin';-import { WaterZone } from '../src/water/zone';+import { waveParamsOf, rainOnWater, grown, exposureOf } from '../src/water/waterPlugin';+import { WaterField, WaterZone, type ZoneLake } from '../src/water/zone';import { RippleField } from '../src/water/ripples';import {blendWeather, setCurrentWeather, WeatherDrive, WEATHER_CLEAR, WEATHER_MIST, WEATHER_RAIN, WEATHER_STORM, WEATHER_NONE,@@ -48,36 +48,51 @@ describe('the waves under a weather', () => {});});-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;- };+describe('rain on the water', () => {+ it('is the weather\'s rain, and none under a clear sky or a weather that does not drive the rain', () => {+ under(WEATHER_RAIN);+ expect(rainOnWater()).toBeGreaterThan(0);+ under(WEATHER_CLEAR);+ expect(rainOnWater()).toBe(0);+ under(WEATHER_STORM, WeatherDrive.All & ~WeatherDrive.Rain);+ expect(rainOnWater()).toBe(0);+ });- it('falls as drops over the window while it rains', () => {+ it('is drawn, not simulated: a storm puts nothing in the ripples a zone keeps', () => {+ under(WEATHER_STORM);const field = new RippleField(64, 64);- under(WEATHER_RAIN);- rainOnRipples(field, 0.5);- expect(disturbed(field)).toBeGreaterThan(0);+ field.step(1, 10, 0.5, 1);+ expect(field.peak()).toBe(0);});+});- it('is none under a clear sky, or when the weather does not drive the rain', () => {- const clear = new RippleField(64, 64);+describe('how open water is to the wind', () => {+ const lake = (half: number, exposure?: number): ZoneLake => ({+ kind: 'lake', key: 1, level: 0, waveHeight: 1, shoreWidth: 1, exposure,+ outline: [{ x: -half, y: -half }, { x: half, y: -half }, { x: half, y: half }, { x: -half, y: half }],+ toLocal: (x, z) => [x, z], toWorld: (x, z) => [x, z],+ });++ it('is whole on the sea, and on a lake the more the wider it is', () => {+ expect(exposureOf({ kind: 'ocean', key: 3, level: 0, waveHeight: 1, shoreWidth: 1 }, 100)).toBe(1);+ const pond = exposureOf(lake(20), 100), mere = exposureOf(lake(200), 100);+ expect(pond).toBeLessThan(mere);+ expect(mere).toBeLessThanOrEqual(1);+ expect(pond).toBeGreaterThan(0);+ });++ it('lets a storm raise a sheltered lake\'s waves less than the sea\'s, and changes nothing in calm weather', () => {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);+ expect(grown(0.2)).toBe(1);+ under(WEATHER_STORM);+ expect(grown(1)).toBeCloseTo(blendWeather(WEATHER_STORM, WEATHER_NONE, 0).waves, 6);+ expect(grown(0.2)).toBeLessThan(grown(1));+ expect(grown(0.2)).toBeGreaterThan(1);});- 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);+ it('is baked with the water, and the dry ground by a lake keeps the lake\'s, so its shore is not read as open sea', () => {+ const field = WaterField.bake({ minX: -40, minZ: -40, sizeX: 80, sizeZ: 80, nx: 81, nz: 81 }, [lake(20, 0.3)]);+ expect(field.sample(0, 0)!.exposure).toBeCloseTo(0.3, 3);+ expect(field.at(30, 0)!.exposure).toBeCloseTo(0.3, 3);});});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 1a8ce8ceb..77ca611d8 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2784,4 +2784,6 @@ export const NOTED = {{"note":"Shadows follow what the camera draws."},"feat(terrain): an area without a heightmap is a window on its provider's ground, and ground read from a provider stays the world's when its terrain moves":{"note":"An area without a heightmap is a window on its provider's ground."},+ "fix(water): rain rings out on the surface instead of denting the ripples, wind ripples are waves not noise, and storms raise sheltered water less":+ {"note":"Rain and storms on water."},};