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): surf runs in toward the shore, breaks white and runs up the ground
yhhaf3f04a7bd01
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bd6126266..16997a607 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,8 @@ published separately; it ships inside the editor.- **Water zones.** Oceans, lakes and rivers are now drawn as one surface. A `WaterBody` says what water is where (its form, outline or Spline, shore width, current and how high its waves stand), and a new `WaterZone` bakes every body over its region into one field: the surface's height, the distance to the shore, the waves' height, the current and the depth over the terrain. One mesh of rings that follows the camera reads it, so a river runs into a lake or the sea at one height with its banks running on into the shore, its current fades into the still water, and no shore foams across its mouth; a lake or a river over the sea is the lake's, not the sea's, and the sea's waves calm and foam where it shallows over the terrain. The zone holds what the bodies share: the material, the waves' length, speed and heading, the mesh's detail and the ripples. A scene without one gets a zone over its lakes and rivers, and the ocean goes on past it. `Waters.sample` reads the same field, so what floats or looks out from under the water meets the surface that is drawn. In the editor the zone's region is outlined in the viewport.- **Wind and rain on the water.** The weather drives the wind: each preset has a wind and a wave strength (mist calms, a storm raises the waves to over twice their height), the Water Body's waves and the foliage's sway follow it in play, and a Weather that does not drive the wind (`WeatherDrive.Wind`) leaves them as authored. Rain falls on water that keeps ripples as rings, as hard as the weather rains, and the rain effect no longer lays a wet floor or puddles over the water itself.+- **Surf on the shore.** Waves run in toward every shore of a water zone, stand up as the water shoals, break white and run up the ground past the waterline before falling back. `WaterZone.surf` sets how high a breaker stands against its body's waves and `surfLength` the length of the surf's waves; a current carries none, and `Waters.sample` rides the same surf. The zone now measures the distance to the shore across the ground for every body, an ocean over a beach included, where an ocean used to measure its depth.+### Changed- **`WaterBody` keeps only what a body says.** Its `material`, `cellSize`, `cells`, `rings`, `waveLength`, `waveSpeed`, `waveDirection` and ripple fields have moved to the new `WaterZone`, which every body shares; `shoreWidth` now calms the waves toward the shore of an ocean and a river as well as a lake. A body of water is no longer tilted with its entity: it is turned about up only. `ShoreField`, `buildRectMesh`, `buildBoxMesh` and `buildRiverMesh` are gone from `esengine/water`.diff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdxindex 8707e2079..4483870cd 100644--- a/docs/astro/src/content/docs/graphics/water.mdx+++ b/docs/astro/src/content/docs/graphics/water.mdx@@ -37,6 +37,7 @@ A `WaterZone` says where the water is drawn, how finely, and what every body sha| `resolution` | Texels along the region's longer side: how finely shores and rivers are traced. || `material` | A material on the Water shader for the whole surface. Empty uses the stock water. || `waveLength`, `waveSpeed`, `waveDirection` | The waves every body shares ([Waves](#waves)). |+| `surf`, `surfLength` | The surf breaking on the shores: how high a breaker stands against its body's waves (0 draws none), and the length of the surf's waves ([Surf](#surf)). || `cellSize`, `cells`, `rings` | The surface's mesh: the cell size of its finest ring, cells along a ring's side, and how many rings ([Geometry](#geometry)). || `ripples`, `rippleSize`, `rippleSpeed`, `rippleDamping`, `foamFade` | The ripples the zone keeps ([Ripples](#ripples)). |@@ -70,6 +71,16 @@ the silhouette against the sky rises and falls with the waves.The waves are measured on the world's xz plane and lift the surface straight up. Parameters are in world units: a scene in metres wants the defaults, one incentimetres wants the lengths scaled.+## Surf++Where water meets the ground, waves run in toward the shore. The zone measures how far each place is from the nearest shore across the ground (the same+for an ocean over a beach as for a lake), and over the last four `surfLength`s of water the surf stands up on that distance: waves with a steep face toward+the 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 where+they 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 there+too, 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.+`Waters.sample` adds the same surf, so what floats near a beach rides it.+## GeometryThe whole surface is one mesh: rings of the same number of cells (`cells` a side), the finest of `cellSize` cells, each twice as coarse as the one inside itdiff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdxindex c7a5b5905..c2bc69fa7 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx@@ -32,6 +32,7 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一| `resolution` | 区域较长一边上的纹素数:岸线和河流描得有多细。 || `material` | 整个水面使用的 Water 着色器材质。留空用内置的水。 || `waveLength`、`waveSpeed`、`waveDirection` | 所有水体共用的波浪([波浪](#波浪))。 |+| `surf`、`surfLength` | 拍岸浪:浪头相对所在水体的波浪有多高(0 不画),以及拍岸浪的波长([拍岸浪](#拍岸浪))。 || `cellSize`、`cells`、`rings` | 水面的网格:最细一圈的格子大小、每圈一边多少格,以及有几圈([几何体](#几何体))。 || `ripples`、`rippleSize`、`rippleSpeed`、`rippleDamping`、`foamFade` | 区域保留的涟漪([涟漪](#涟漪))。 |@@ -54,6 +55,10 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一波浪在世界的 xz 平面上度量,把水面竖直向上抬起。参数以世界单位计:以米为单位的场景用默认值,以厘米为单位的要把长度相应缩放。+## 拍岸浪++水与地面相接处,浪朝岸边推进。区域量出每一处沿地面到最近岸线的距离(海洋漫过沙滩和湖泊都是同一种量法),在最后四个 `surfLength` 的水面上,拍岸浪按这个距离立起来:朝岸的一面陡、背面长,以同波长深水波的速度乘 `waveSpeed` 向岸推进。水变浅时浪变高,在这段水域的靠岸部分破碎发白,浪峰过后白沫还会留一阵;过了岸线浪会冲上地面:那里也画出水面,略高于静水面,地面高过它的地方由深度测试裁掉,所以水线会爬上沙滩再退回来。浪头高度是所在水体的 `waveHeight` 乘 `surf`(含天气对波浪的缩放);有水流的地方没有拍岸浪,所以河流和河口保持平静。`Waters.sample` 也加上同样的拍岸浪,沙滩附近的漂浮物会随之起伏。+## 几何体整个水面是一个网格:一圈圈格子数相同的网格(每边 `cells` 格),最细一圈是 `cellSize` 的格子,每圈的格子是里面那圈的两倍,中间留出里面那圈的洞,所以它从中心伸出 `cells * cellSize * 2^(rings - 1) / 2` 远,又把三角形花在近处。它跟着相机、落在所有圈都对齐的格点上,材质的原点同步移动,所以网格在水下面移动,而水留在世界里不动。它的顶点钩子在每个顶点读区域的场(高度逐纹素读取,先解码再混合),把顶点抬到那里的水面高度再加上波浪;场说那里没有水的像素会被裁掉。diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 43f0acc3c..b5625b5be 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -7326,6 +7326,20 @@"doc": "The heading of the waves, in degrees.","range": "0–360"},+ {+ "key": "surf",+ "type": "number",+ "default": "0.6",+ "doc": "How high the surf breaking on a shore stands against its body's waves. 0 draws none. A current carries none.",+ "range": "0–4"+ },+ {+ "key": "surfLength",+ "type": "number",+ "default": "8",+ "doc": "The length of the surf's waves, in world units. They run in over four lengths of water, break, and run up the ground past the shore.",+ "range": "0.1–100000"+ },{"key": "cellSize","type": "number",@@ -7391,6 +7405,8 @@"waveLength","waveSpeed","waveDirection",+ "surf",+ "surfLength","cellSize","cells","rings",diff --git a/examples/terrain-water/assets/scenes/main.esscene b/examples/terrain-water/assets/scenes/main.essceneindex 007d8279a..d630a7d7f 100644--- a/examples/terrain-water/assets/scenes/main.esscene+++ b/examples/terrain-water/assets/scenes/main.esscene@@ -264,6 +264,8 @@"waveLength": 1600,"waveSpeed": 1,"waveDirection": 200,+ "surf": 0.8,+ "surfLength": 700,"cellSize": 100,"cells": 64,"rings": 7,diff --git a/examples/terrain-water/tools/build.mjs b/examples/terrain-water/tools/build.mjsindex 7aac5b447..99f6c2e1d 100644--- a/examples/terrain-water/tools/build.mjs+++ b/examples/terrain-water/tools/build.mjs@@ -458,7 +458,7 @@ function scene() {add('Water', [{ type: 'Transform', data: {} },{ type: 'WaterZone', data: { sizeX: WORLD.size, sizeZ: WORLD.size, resolution: 1024, material: 'assets/materials/water.esmaterial',- waveLength: 1600, waveSpeed: 1, waveDirection: 200, cellSize: 100, cells: 64, rings: 7,+ waveLength: 1600, waveSpeed: 1, waveDirection: 200, surf: 0.8, surfLength: 700, cellSize: 100, cells: 64, rings: 7,ripples: 128, rippleSize: 6000, rippleSpeed: 600, rippleDamping: 0.8, foamFade: 0.4 } },]);add('Sea', [diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 1f4b56293..bc0e82491 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3889,6 +3889,7 @@ flowZ: numberheight: numberkey: numbershore: number+swell: number```## FillMethod — enum @beta@@ -11242,9 +11243,10 @@ grid: ZoneGridheight: Float32Array<ArrayBufferLike>ocean: ZoneOcean | nullowner: Int32Array<ArrayBufferLike>-ranges: () => ZoneRanges+ranges: (shoreReach?: number) => ZoneRangessample: (x: number, z: number) => FieldSample | nullshore: Float32Array<ArrayBufferLike>+swell: Float32Array<ArrayBufferLike>static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterFieldstatic new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterFieldstatic prototype: WaterField@@ -11293,6 +11295,8 @@ rippleSpeed: numberripples: numbersizeX: numbersizeZ: number+surf: number+surfLength: numberwaveDirection: numberwaveLength: numberwaveSpeed: numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 24589b4bd..26d918fbb 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3897,6 +3897,7 @@ flowZ: numberheight: numberkey: numbershore: number+swell: number```## FillMethod — enum @beta@@ -11455,9 +11456,10 @@ grid: ZoneGridheight: Float32Array<ArrayBufferLike>ocean: ZoneOcean | nullowner: Int32Array<ArrayBufferLike>-ranges: () => ZoneRanges+ranges: (shoreReach?: number) => ZoneRangessample: (x: number, z: number) => FieldSample | nullshore: Float32Array<ArrayBufferLike>+swell: Float32Array<ArrayBufferLike>static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterFieldstatic new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterFieldstatic prototype: WaterField@@ -11506,6 +11508,8 @@ rippleSpeed: numberripples: numbersizeX: numbersizeZ: number+surf: number+surfLength: numberwaveDirection: numberwaveLength: numberwaveSpeed: numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex d0c8e9024..26cd55b4c 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3884,6 +3884,7 @@ flowZ: numberheight: numberkey: numbershore: number+swell: number```## FillMethod — enum @beta@@ -11237,9 +11238,10 @@ grid: ZoneGridheight: Float32Array<ArrayBufferLike>ocean: ZoneOcean | nullowner: Int32Array<ArrayBufferLike>-ranges: () => ZoneRanges+ranges: (shoreReach?: number) => ZoneRangessample: (x: number, z: number) => FieldSample | nullshore: Float32Array<ArrayBufferLike>+swell: Float32Array<ArrayBufferLike>static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterFieldstatic new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterFieldstatic prototype: WaterField@@ -11288,6 +11290,8 @@ rippleSpeed: numberripples: numbersizeX: numbersizeZ: number+surf: number+surfLength: numberwaveDirection: numberwaveLength: numberwaveSpeed: numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5b7e6f621..702504e34 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3884,6 +3884,7 @@ flowZ: numberheight: numberkey: numbershore: number+swell: number```## FillMethod — enum @beta@@ -11536,9 +11537,10 @@ grid: ZoneGridheight: Float32Array<ArrayBufferLike>ocean: ZoneOcean | nullowner: Int32Array<ArrayBufferLike>-ranges: () => ZoneRanges+ranges: (shoreReach?: number) => ZoneRangessample: (x: number, z: number) => FieldSample | nullshore: Float32Array<ArrayBufferLike>+swell: Float32Array<ArrayBufferLike>static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterFieldstatic new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterFieldstatic prototype: WaterField@@ -11587,6 +11589,8 @@ rippleSpeed: numberripples: numbersizeX: numbersizeZ: number+surf: number+surfLength: numberwaveDirection: numberwaveLength: numberwaveSpeed: numberdiff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.mdindex ec7bfa2db..a5159e105 100644--- a/sdk/etc/water.api.md+++ b/sdk/etc/water.api.md@@ -13,6 +13,7 @@ flowZ: numberheight: numberkey: numbershore: number+swell: number```## Floating — const @experimental@@ -120,9 +121,10 @@ grid: ZoneGridheight: Float32Array<ArrayBufferLike>ocean: ZoneOcean | nullowner: Int32Array<ArrayBufferLike>-ranges: () => ZoneRanges+ranges: (shoreReach?: number) => ZoneRangessample: (x: number, z: number) => FieldSample | nullshore: Float32Array<ArrayBufferLike>+swell: Float32Array<ArrayBufferLike>static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterFieldstatic new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterFieldstatic prototype: WaterField@@ -171,6 +173,8 @@ rippleSpeed: numberripples: numbersizeX: numbersizeZ: number+surf: number+surfLength: numberwaveDirection: numberwaveLength: numberwaveSpeed: numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex a24187754..fb609ec68 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3884,6 +3884,7 @@ flowZ: numberheight: numberkey: numbershore: number+swell: number```## FillMethod — enum @beta@@ -11244,9 +11245,10 @@ grid: ZoneGridheight: Float32Array<ArrayBufferLike>ocean: ZoneOcean | nullowner: Int32Array<ArrayBufferLike>-ranges: () => ZoneRanges+ranges: (shoreReach?: number) => ZoneRangessample: (x: number, z: number) => FieldSample | nullshore: Float32Array<ArrayBufferLike>+swell: Float32Array<ArrayBufferLike>static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterFieldstatic new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterFieldstatic prototype: WaterField@@ -11295,6 +11297,8 @@ rippleSpeed: numberripples: numbersizeX: numbersizeZ: number+surf: number+surfLength: numberwaveDirection: numberwaveLength: numberwaveSpeed: numberdiff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex be099ec67..7397d3fab 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -31,7 +31,7 @@ import { TerrainsRes } from '../terrain/terrainPlugin';import { BlendMode } from '../render/blend';import { log } from '../util/logger';import type { Entity } from '../types';-import { waveHeight, waveSlope, type WaveParams } from './waves';+import { surfHeight, waveHeight, waveSlope, type WaveParams } from './waves';import { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';import { type Point2 } from './shore';import { Spline, type SplineData } from '../spline/splinePlugin';@@ -150,8 +150,11 @@ export class Waters {if (!s) return null;const time = this.app_.getResource(Time).elapsed;const params = this.waves(s.amp);+ 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);// The lite water is flat: its waves are in the shading, so the height code reads is the rest plane's.- const h = s.height + (this.quality.displacement ? waveHeight(params, x, z, time) : 0) + (this.ripples_?.heightAt(x, z) ?? 0);+ const 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);const len = Math.hypot(sx, 1, sz);return {@@ -415,7 +418,7 @@ export class WaterPlugin implements Plugin {}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]) };+ return { bodies, grid, zone, key: JSON.stringify([keyParts, grid, ground, zone.surfLength]) };}/** The world height of the ground, where a terrain is built. */@@ -483,7 +486,7 @@ export class WaterPlugin implements Plugin {/** Puts the baked field where the shader reads it: the heights texel by texel, the rest filtered. */private upload(app: App, s: Surface, field: WaterField): void {this.dropFieldTextures(s);- const ranges = field.ranges();+ const ranges = field.ranges(this.waters_.zone_.surfLength * 4);const { heights, field: rest } = field.encode(ranges);const { nx, nz, minX, minZ, sizeX, sizeZ } = field.grid;const empty = nx < 2 || nz < 2;@@ -530,6 +533,9 @@ export class WaterPlugin implements Plugin {set('u_oceanOn', ocean ? 1 : 0);set('u_oceanLevel', ocean ? ocean.level : 0);set('u_oceanWaves', ocean ? ocean.waveHeight : 0);+ set('u_surfHeight', zone.surf);+ set('u_surfLength', zone.surfLength);+ set('u_surfSpeed', zone.waveSpeed);}/**diff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.tsindex 49045d20d..f72f47e89 100644--- a/sdk/src/water/waterShader.ts+++ b/sdk/src/water/waterShader.ts@@ -62,6 +62,11 @@ const WATER = `#pragma shader "Water"#pragma param u_oceanOn float default(0) range(0,1) ui(slider)#pragma param u_oceanLevel float default(0) range(-100000,100000) ui(slider)#pragma param u_oceanWaves float default(1) range(0,100) ui(slider)+// The surf (the WaterZone writes these): how high a breaker stands against its body's waves (with the weather in), how long the surf's waves+// are, and a multiplier on their speed. 0 draws none.+#pragma param u_surfHeight float default(0) range(0,4) ui(slider)+#pragma param u_surfLength float default(10) range(0.1,100000) ui(slider)+#pragma param u_surfSpeed float default(1) range(0,4) ui(slider)// How long, in seconds, each of the two copies of the surface the shader carries down a current lives before the other takes over.#pragma param u_flowCycle float default(2) range(0.2,20) ui(slider)// How much of the waves lifts the geometry: 0 draws the surface flat and moves it only in the shading (the lite water).@@ -123,13 +128,41 @@ vec3 waterZoneAt(vec2 p) {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 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) {+ vec2 uv = (p - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));+ vec4 f = textureLod(u_zoneField, clamp(uv, 0.0, 1.0), 0.0);+ bool inside = all(greaterThanEqual(uv, vec2(0.0))) && all(lessThanEqual(uv, vec2(1.0)));+ if (!inside) return u_oceanOn > 0.5 ? vec4(1e6, 0.0, 0.0, 1.0) : vec4(-1.0, 0.0, 0.0, 0.0);+ return vec4((f.r - 0.5) * 2.0 * u_zoneRange.x, (f.gb - 0.5) * 2.0 * u_zoneRange.z, f.a);+}+// The surf at a shore distance (waves.ts surfHeight): x its height, y how broken it is (white water on and behind a breaking crest).+vec2 waterSurf(float shore, float height, float time) {+ if (height <= 0.0 || u_surfLength <= 0.0) return vec2(0.0);+ float reach = u_surfLength * 4.0;+ if (shore > reach || shore < -reach * 0.2) return vec2(0.0);+ float celerity = sqrt(9.8 * u_surfLength / 6.2831853) * u_surfSpeed;+ float u = fract(shore / u_surfLength + celerity * time / u_surfLength);+ float g = u > 0.8 ? smoothstep(0.0, 1.0, (u - 0.8) / 0.2) : 1.0 - smoothstep(0.0, 1.0, u / 0.8);+ float shoal = 1.0 - smoothstep(0.0, 1.0, (shore - reach * 0.25) / (reach * 0.75));+ float runUp = shore >= 0.0 ? 1.0 : 1.0 - smoothstep(0.0, 1.0, -shore / (reach * 0.2));+ float env = shoal * runUp;+ // It breaks in the inner third: the crest whitens, and the water behind it stays white a while.+ float breaking = 1.0 - smoothstep(reach * 0.15, reach * 0.4, shore);+ float white = breaking * max(smoothstep(0.75, 1.0, g), (1.0 - smoothstep(0.0, 0.35, u)) * 0.8) * env;+ return vec2(height * g * g * env, white);+}void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {if (u_waveSpace < 0.5) return;vec2 p = uv + u_origin;float cell = u_cellSize > 0.0 ? u_cellSize * exp2(es_vertexColor.r * 7.0) : 0.0;- // The water's rest height there and how high its waves stand (a multiple of u_waveHeight, which the zone sets to the weather's).+ // 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);- local.y += zone.x + waterWaveHeight(p, u_time.x, cell) * zone.z * u_geoWaves;+ 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;+ local.y += zone.x + (waterWaveHeight(p, u_time.x, cell) * zone.z * field.w + surf) * u_geoWaves;}#pragma end@@ -169,14 +202,43 @@ fn waterZoneAt(p : vec2f) -> vec3f {if (!inside && mc.u_oceanOn > 0.5) { return vec3f(mc.u_oceanLevel, 1e6, mc.u_oceanWaves); }return vec3f(mc.u_zoneHeight.x + h * mc.u_zoneHeight.y, da.x * mc.u_zoneRange.w, da.y * mc.u_zoneRange.y);}+fn waterZoneField(p : vec2f) -> vec4f {+ let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));+ let f = textureSampleLevel(u_zoneField, u_zoneField_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0);+ let inside = all(uv >= vec2f(0.0)) && all(uv <= vec2f(1.0));+ if (!inside) {+ if (mc.u_oceanOn > 0.5) { return vec4f(1e6, 0.0, 0.0, 1.0); }+ return vec4f(-1.0, 0.0, 0.0, 0.0);+ }+ return vec4f((f.r - 0.5) * 2.0 * mc.u_zoneRange.x, (f.gb - vec2f(0.5)) * 2.0 * mc.u_zoneRange.z, f.a);+}+fn waterSurf(shore : f32, height : f32, time : f32) -> vec2f {+ if (height <= 0.0 || mc.u_surfLength <= 0.0) { return vec2f(0.0); }+ let reach = mc.u_surfLength * 4.0;+ if (shore > reach || shore < -reach * 0.2) { return vec2f(0.0); }+ let celerity = sqrt(9.8 * mc.u_surfLength / 6.2831853) * mc.u_surfSpeed;+ let u = fract(shore / mc.u_surfLength + celerity * time / mc.u_surfLength);+ var g = 1.0 - smoothstep(0.0, 1.0, u / 0.8);+ if (u > 0.8) { g = smoothstep(0.0, 1.0, (u - 0.8) / 0.2); }+ let shoal = 1.0 - smoothstep(0.0, 1.0, (shore - reach * 0.25) / (reach * 0.75));+ var runUp = 1.0;+ if (shore < 0.0) { runUp = 1.0 - smoothstep(0.0, 1.0, -shore / (reach * 0.2)); }+ let env = shoal * runUp;+ let breaking = 1.0 - smoothstep(reach * 0.15, reach * 0.4, shore);+ let white = breaking * max(smoothstep(0.75, 1.0, g), (1.0 - smoothstep(0.0, 0.35, u)) * 0.8) * env;+ return vec2f(height * g * g * env, white);+}fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {if (mc.u_waveSpace < 0.5) { return; }let p = uv + mc.u_origin;var cell = 0.0;if (mc.u_cellSize > 0.0) { cell = mc.u_cellSize * exp2(es_vertexColor.r * 7.0); }var zone = vec3f(0.0, 0.0, 1.0);- if (mc.u_zoneOn > 0.5) { zone = waterZoneAt(p); }- (*local).y = (*local).y + zone.x + waterWaveHeight(p, tc.u_time.x, cell) * zone.z * mc.u_geoWaves;+ 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;+ (*local).y = (*local).y + zone.x + (waterWaveHeight(p, tc.u_time.x, cell) * zone.z * field.w + surf) * mc.u_geoWaves;}#pragma end@@ -268,6 +330,30 @@ vec3 waterZoneAt(vec2 p) {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 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) {+ vec2 uv = (p - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));+ vec4 f = textureLod(u_zoneField, clamp(uv, 0.0, 1.0), 0.0);+ bool inside = all(greaterThanEqual(uv, vec2(0.0))) && all(lessThanEqual(uv, vec2(1.0)));+ if (!inside) return u_oceanOn > 0.5 ? vec4(1e6, 0.0, 0.0, 1.0) : vec4(-1.0, 0.0, 0.0, 0.0);+ return vec4((f.r - 0.5) * 2.0 * u_zoneRange.x, (f.gb - 0.5) * 2.0 * u_zoneRange.z, f.a);+}+// The surf at a shore distance (waves.ts surfHeight): x its height, y how broken it is (white water on and behind a breaking crest).+vec2 waterSurf(float shore, float height, float time) {+ if (height <= 0.0 || u_surfLength <= 0.0) return vec2(0.0);+ float reach = u_surfLength * 4.0;+ if (shore > reach || shore < -reach * 0.2) return vec2(0.0);+ float celerity = sqrt(9.8 * u_surfLength / 6.2831853) * u_surfSpeed;+ float u = fract(shore / u_surfLength + celerity * time / u_surfLength);+ float g = u > 0.8 ? smoothstep(0.0, 1.0, (u - 0.8) / 0.2) : 1.0 - smoothstep(0.0, 1.0, u / 0.8);+ float shoal = 1.0 - smoothstep(0.0, 1.0, (shore - reach * 0.25) / (reach * 0.75));+ float runUp = shore >= 0.0 ? 1.0 : 1.0 - smoothstep(0.0, 1.0, -shore / (reach * 0.2));+ float env = shoal * runUp;+ // It breaks in the inner third: the crest whitens, and the water behind it stays white a while.+ float breaking = 1.0 - smoothstep(reach * 0.15, reach * 0.4, shore);+ float white = breaking * max(smoothstep(0.75, 1.0, g), (1.0 - smoothstep(0.0, 0.35, u)) * 0.8) * env;+ return vec2(height * g * g * env, white);+}/// The first directional light that shines: xyz is where it stands in the sky, w 1 if there is one, color its colour and strength, tiles its place in the shadow atlas.void waterSun(out vec4 dir, out vec4 color, out ivec2 tiles) {dir = vec4(0.0);@@ -360,9 +446,17 @@ void main() {float shoreDist = !zoneOn ? 1e6 : zoneIn ? (zoneTex.r - 0.5) * 2.0 * u_zoneRange.x : u_oceanOn > 0.5 ? 1e6 : -1.0;float shoreDepth = zoneOn ? zone.y : 1e6;// How high the waves stand (a multiple of u_waveHeight), and the share of them kept toward the shore, which calms the small ripples and the crests too.- float damp = zoneOn ? zone.z : 1.0;float calm = !zoneOn ? 1.0 : zoneIn ? zoneTex.a : 1.0;+ float damp = zoneOn ? zone.z * calm : 1.0;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 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);+ vec2 surf = waterSurf(shoreDist, surfH, time);+ float surfRise = (waterSurf(shoreDist + surfStep * 0.5, surfH, time).x - waterSurf(shoreDist - surfStep * 0.5, surfH, time).x) / surfStep;// The ripples at this pixel: their height on four sides gives the slope they add, and the foam is what they left (reads taken before any branch).vec2 ripUv = (wp - u_rippleOrigin) / max(u_rippleSize, 1e-4);vec4 ripC = texture(u_rippleMap, ripUv);@@ -390,7 +484,7 @@ void main() {} else {slope = waterSurface(wp, time, waterDist, damp, calm, crest);}- slope += ripSlope;+ slope += ripSlope + toSea * (surfRise * u_geoWaves);vec3 N = normalize(vec3(-slope.x, 1.0, -slope.y));vec3 Ngeo = vec3(0.0, 1.0, 0.0);#ifdef MESH_NORMALS@@ -466,7 +560,8 @@ void main() {shore = max(shore, clamp((1.0 - min(shoreDist, shoreDepth) / (u_foamWidth * pulse)) * 1.5 - breakup * 0.8, 0.0, 1.0));}float onCrest = u_foamCrest > 0.0 ? smoothstep(1.0 - 0.3 * u_foamCrest, 1.0, crest) * smoothstep(0.35, 0.75, breakup) : 0.0;- float foam = clamp(max(max(shore, onCrest * u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), 0.0, 1.0);+ float surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4);+ float foam = clamp(max(max(max(shore, onCrest * u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 0.0, 1.0);SurfaceExt ext = surfaceExtNone(N);ext.misc.x = 0.0204;@@ -489,8 +584,9 @@ void main() {mirror = met.a > 0.5 ? met.rgb : mix(u_shallowColor.rgb, u_deepColor.rgb, 0.5) * 0.25;}seen += mirror * fresnel * (1.0 - foam);- // Past the shore there is no water.- if (shoreDist < 0.0) discard;+ // Past the shore there is no water, but for the surf running up dry ground (where the ground is no lower than the water: the depth test+ // then cuts it where the ground rises above it).+ if (shoreDist < 0.0 && (surf.x <= 0.0 || shoreDepth > 1e-3)) discard;fragColor = vec4(lit + seen, haveColor ? 1.0 : 0.85);#ifdef ES_GBUFFER// 0.72: a surface, and water (see readSurface): what lands on it is the water's, not a wet floor's.@@ -579,6 +675,32 @@ fn waterZoneAt(p : vec2f) -> vec3f {if (!inside && mc.u_oceanOn > 0.5) { return vec3f(mc.u_oceanLevel, 1e6, mc.u_oceanWaves); }return vec3f(mc.u_zoneHeight.x + h * mc.u_zoneHeight.y, da.x * mc.u_zoneRange.w, da.y * mc.u_zoneRange.y);}+fn waterZoneField(p : vec2f) -> vec4f {+ let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));+ let f = textureSampleLevel(u_zoneField, u_zoneField_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0);+ let inside = all(uv >= vec2f(0.0)) && all(uv <= vec2f(1.0));+ if (!inside) {+ if (mc.u_oceanOn > 0.5) { return vec4f(1e6, 0.0, 0.0, 1.0); }+ return vec4f(-1.0, 0.0, 0.0, 0.0);+ }+ return vec4f((f.r - 0.5) * 2.0 * mc.u_zoneRange.x, (f.gb - vec2f(0.5)) * 2.0 * mc.u_zoneRange.z, f.a);+}+fn waterSurf(shore : f32, height : f32, time : f32) -> vec2f {+ if (height <= 0.0 || mc.u_surfLength <= 0.0) { return vec2f(0.0); }+ let reach = mc.u_surfLength * 4.0;+ if (shore > reach || shore < -reach * 0.2) { return vec2f(0.0); }+ let celerity = sqrt(9.8 * mc.u_surfLength / 6.2831853) * mc.u_surfSpeed;+ let u = fract(shore / mc.u_surfLength + celerity * time / mc.u_surfLength);+ var g = 1.0 - smoothstep(0.0, 1.0, u / 0.8);+ if (u > 0.8) { g = smoothstep(0.0, 1.0, (u - 0.8) / 0.2); }+ let shoal = 1.0 - smoothstep(0.0, 1.0, (shore - reach * 0.25) / (reach * 0.75));+ var runUp = 1.0;+ if (shore < 0.0) { runUp = 1.0 - smoothstep(0.0, 1.0, -shore / (reach * 0.2)); }+ let env = shoal * runUp;+ let breaking = 1.0 - smoothstep(reach * 0.15, reach * 0.4, shore);+ let white = breaking * max(smoothstep(0.75, 1.0, g), (1.0 - smoothstep(0.0, 0.35, u)) * 0.8) * env;+ return vec2f(height * g * g * env, white);+}struct WaterSun { dir : vec4f, color : vec4f, tiles : vec2i };/// The first directional light that shines: dir.xyz is where it stands in the sky, dir.w 1 if there is one.fn waterSun() -> WaterSun {@@ -682,10 +804,18 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vecvar flow = vec2f(0.0);if (zoneOn) {shoreDepth = zone.y;- damp = zone.z;if (zoneIn) { shoreDist = (zoneTex.r - 0.5) * 2.0 * mc.u_zoneRange.x; flow = (zoneTex.gb - vec2f(0.5)) * 2.0 * mc.u_zoneRange.z; calm = zoneTex.a; }else if (mc.u_oceanOn < 0.5) { shoreDist = -1.0; }+ damp = zone.z * calm;}+ 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; }+ 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);+ let surf = waterSurf(shoreDist, surfH, time);+ let surfRise = (waterSurf(shoreDist + surfStep * 0.5, surfH, time).x - waterSurf(shoreDist - surfStep * 0.5, surfH, time).x) / surfStep;// The ripples at this pixel: their height on four sides gives the slope they add, and the foam is what they left (taken in uniform control flow).let ripUv = (wp - mc.u_rippleOrigin) / max(mc.u_rippleSize, 1e-4);let ripC = textureSample(u_rippleMap, u_rippleMap_s, ripUv);@@ -713,7 +843,7 @@ 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;+ var slope = surface.xy + ripSlope + toSea * (surfRise * mc.u_geoWaves);var N = normalize(vec3f(-slope.x, 1.0, -slope.y));var Ngeo = vec3f(0.0, 1.0, 0.0);#ifdef MESH_NORMALS@@ -783,7 +913,8 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec}var onCrest = 0.0;if (mc.u_foamCrest > 0.0) { onCrest = smoothstep(1.0 - 0.3 * mc.u_foamCrest, 1.0, waves.crest) * smoothstep(0.35, 0.75, breakup); }- let foam = clamp(max(max(shore, onCrest * mc.u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), 0.0, 1.0);+ let surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4);+ let foam = clamp(max(max(max(shore, onCrest * mc.u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 0.0, 1.0);var ext = surfaceExtNone(N);ext.misc.x = 0.0204;@@ -806,7 +937,7 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vecseen = seen + mirror * fresnel * (1.0 - foam);var alpha = 0.85;if (haveColor) { alpha = 1.0; }- if (shoreDist < 0.0) { discard; }+ if (shoreDist < 0.0 && (surf.x <= 0.0 || shoreDepth > 1e-3)) { discard; }#ifdef ES_GBUFFERvar frag : FragOut;frag.color = vec4f(lit + seen, alpha);diff --git a/sdk/src/water/waves.ts b/sdk/src/water/waves.tsindex bb185d672..821d2cea0 100644--- a/sdk/src/water/waves.ts+++ b/sdk/src/water/waves.ts@@ -86,3 +86,37 @@ export function waveSlope(p: WaveParams, x: number, z: number, time: number): [n}return [sx, sz];}++/**+ * The surf: waves that run in toward the shore across the last `4 * length` of water, steepen and break on it, and run up the ground past+ * it. `shore` is the distance to the shore (above zero on the water), `height` how high a breaker stands at most. Each has a steep face+ * toward the shore and a long back, and they travel at the speed of a deep-water wave of their length times `speed`. The Water shader+ * draws the same.+ */+export function surfHeight(shore: number, height: number, length: number, speed: number, time: number): number {+ if (height <= 0 || length <= 0) return 0;+ const reach = length * 4;+ if (shore > reach || shore < -reach * 0.2) return 0;+ const celerity = Math.sqrt(GRAVITY * length / TAU) * speed;+ const u = fract(shore / length + (celerity * time) / length);+ // Seaward of a crest the water falls away slowly; shoreward its face is steep.+ const face = 0.2;+ const g = u > 1 - face ? smooth01((u - (1 - face)) / face) : 1 - smooth01(u / (1 - face));+ return height * g * g * surfEnvelope(shore, reach);+}++/** How much of the surf stands at `shore`: none out past its reach, rising as the water shoals, and dying as it runs up the ground. */+export function surfEnvelope(shore: number, reach: number): number {+ const shoal = 1 - smooth01((shore - reach * 0.25) / (reach * 0.75));+ const runUp = shore >= 0 ? 1 : 1 - smooth01(-shore / (reach * 0.2));+ return shoal * runUp;+}++function fract(x: number): number {+ return x - Math.floor(x);+}++function smooth01(t: number): number {+ const c = Math.min(Math.max(t, 0), 1);+ return c * c * (3 - 2 * c);+}diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.tsindex d5e052bec..0257a0d4e 100644--- a/sdk/src/water/zone.ts+++ b/sdk/src/water/zone.ts@@ -35,6 +35,9 @@ export interface WaterZoneData {waveLength: number;waveSpeed: number;waveDirection: number;+ /** The surf: how high a breaker stands against its body's waves (0 draws none), and how long the surf's waves are, in world units. */+ surf: number;+ surfLength: number;/** The surface's mesh: the cell size of its finest ring, cells along a ring's side, and how many rings (each twice as coarse) follow the camera. */cellSize: number;cells: number;@@ -56,7 +59,7 @@ export interface WaterZoneData {*/export const WaterZone: ComponentDef<WaterZoneData> = defineComponent<WaterZoneData>('WaterZone', {sizeX: 200, sizeZ: 200, resolution: 256, material: 0,- waveLength: 14, waveSpeed: 1, waveDirection: 30,+ waveLength: 14, waveSpeed: 1, waveDirection: 30, surf: 0.6, surfLength: 8,cellSize: 1, cells: 64, rings: 5,ripples: 0, rippleSize: 64, rippleSpeed: 6, rippleDamping: 0.8, foamFade: 0.4,}, {@@ -69,6 +72,8 @@ export const WaterZone: ComponentDef<WaterZoneData> = defineComponent<WaterZoneDwaveLength: { min: 0.5, max: 3000, category: 'Waves', tooltip: 'The length of the longest wave. Every body shares the waves; each sets how high they stand.' },waveSpeed: { min: 0, max: 4, category: 'Waves', tooltip: 'A multiplier on how fast the waves travel.' },waveDirection: { min: 0, max: 360, category: 'Waves', tooltip: 'The heading of the waves, in degrees.' },+ surf: { min: 0, max: 4, category: 'Waves', tooltip: 'How high the surf breaking on a shore stands against its body\'s waves. 0 draws none. A current carries none.' },+ surfLength: { min: 0.1, max: 100000, category: 'Waves', tooltip: 'The length of the surf\'s waves, in world units. They run in over four lengths of water, break, and run up the ground past the shore.' },cellSize: { min: 0.05, category: 'Detail', tooltip: 'The cell size of the finest ring of the surface. Waves shorter than six cells are not drawn as geometry there (the shading still shows them).' },cells: { min: 4, max: 256, step: 4, category: 'Detail', tooltip: 'Cells along a ring\'s side.' },rings: { min: 1, max: 10, step: 1, category: 'Detail', tooltip: 'Rings of the surface, each twice as coarse as the one inside it.' },@@ -117,6 +122,8 @@ export interface FieldSample {height: number;amp: number;calm: number;+ /** The height its body's waves stand to away from any shore: what the surf breaking on the shore is measured against. */+ swell: number;flowX: number;flowZ: number;/** The signed distance to the nearest shore (positive on the water) and how deep the water is over the ground. */@@ -139,6 +146,7 @@ export class WaterField {readonly shore: Float32Array;readonly amp: Float32Array;readonly calm: Float32Array;+ readonly swell: Float32Array;readonly flowX: Float32Array;readonly flowZ: Float32Array;readonly depth: Float32Array;@@ -155,6 +163,7 @@ export class WaterField {this.shore = new Float32Array(n);this.amp = new Float32Array(n);this.calm = new Float32Array(n);+ this.swell = new Float32Array(n);this.flowX = new Float32Array(n);this.flowZ = new Float32Array(n);this.depth = new Float32Array(n);@@ -180,7 +189,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 = ground ? ground(x, z) : null;- let w = 0, h = 0, a = 0, c = 0, fx = 0, fz = 0, best = -Infinity, owner = -1, ownerW = 0, held = 0;+ let w = 0, h = 0, a = 0, c = 0, sw = 0, fx = 0, fz = 0, best = -Infinity, owner = -1, ownerW = 0, held = 0;for (let b = 0; b < bounded.length; b++) {const box = boxes[b]!;if (x < box[0] - blend || x > box[2] + blend || z < box[1] - blend || z > box[3] + blend) continue;@@ -190,7 +199,7 @@ export class WaterField {const weight = smooth(-blend, blend, say.shore);if (weight <= 0) continue;held = Math.max(held, weight);- w += weight; h += say.height * weight; a += say.amp * weight; c += say.calm * weight; fx += say.fx * weight; fz += say.fz * weight;+ 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;if (weight > ownerW) { ownerW = weight; owner = bounded[b]!.key; }}if (ocean) {@@ -199,7 +208,7 @@ export class WaterField {const weight = smooth(-blend, blend, deep) * (1 - held);if (weight > 0) {const calm = shoreDamp(deep, ocean.shoreWidth);- w += weight; h += ocean.level * weight; a += ocean.waveHeight * calm * weight; c += calm * weight;+ w += weight; h += ocean.level * weight; a += ocean.waveHeight * calm * weight; c += calm * weight; sw += ocean.waveHeight * weight;if (weight > ownerW) { ownerW = weight; owner = ocean.key; }}}@@ -209,6 +218,7 @@ export class WaterField {field.height[k] = h / w;field.amp[k] = a / w;field.calm[k] = c / w;+ field.swell[k] = sw / w;field.flowX[k] = fx / w;field.flowZ[k] = fz / w;} else {@@ -217,6 +227,7 @@ export class WaterField {field.depth[k] = g === null ? DEEP : Math.max(0, (w > 0 ? h / w : 0) - g);}}+ levelShore(field, texel);fillDry(field);return field;}@@ -237,7 +248,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), flowX: lerp2(this.flowX), flowZ: lerp2(this.flowZ),+ 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),};}@@ -251,16 +262,23 @@ 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, 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 };}- /** The ranges the encoding spans, from what the field holds. */- ranges(): ZoneRanges {+ /** 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). */+ ranges(shoreReach = 0): ZoneRanges {+ const r = this.ranges_ ??= this.measure();+ return { ...r, shore: Math.max(r.shore, shoreReach * 1.25) };+ }++ private ranges_: ZoneRanges | null = null;++ private measure(): ZoneRanges {let lo = Infinity, hi = -Infinity, amp = 0, flow = 0;for (let k = 0; k < this.height.length; k++) {const h = this.height[k]!;if (Number.isFinite(h)) { lo = Math.min(lo, h); hi = Math.max(hi, h); }- amp = Math.max(amp, this.amp[k]!);+ amp = Math.max(amp, this.swell[k]!);flow = Math.max(flow, Math.abs(this.flowX[k]!), Math.abs(this.flowZ[k]!));}if (this.ocean) { lo = Math.min(lo, this.ocean.level); hi = Math.max(hi, this.ocean.level); amp = Math.max(amp, this.ocean.waveHeight); }@@ -271,7 +289,7 @@ 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 waves' height. field (filtered): r the shore distance (0.5 at it); gb the current (0.5 still); a the calm.+ * 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`.*/encode(r: ZoneRanges): { heights: Uint8Array; field: Uint8Array } {@@ -283,7 +301,7 @@ export class WaterField {heights[k * 4] = h >> 8;heights[k * 4 + 1] = h & 255;heights[k * 4 + 2] = byte(this.depth[k]! / r.depth);- heights[k * 4 + 3] = byte(this.amp[k]! / r.amp);+ heights[k * 4 + 3] = byte(this.swell[k]! / r.amp);field[k * 4] = byte(this.shore[k]! / (2 * r.shore) + 0.5);field[k * 4 + 1] = byte(this.flowX[k]! / (2 * r.flow) + 0.5);field[k * 4 + 2] = byte(this.flowZ[k]! / (2 * r.flow) + 0.5);@@ -349,6 +367,52 @@ function boundsOf(body: ZoneLake | ZoneRiver): [number, number, number, number]return [minX, minZ, maxX, maxZ];}+/**+ * The shore distance made one measure everywhere: how far across the ground the nearest edge of ANY water is, the sign the bodies gave. A body's+ * own say is exact only near its edge (an ocean's is its depth, a lake's ends at its outline even where a river carries the water on), so the+ * texels on either side of an edge keep it, held to a texel, and every other texel is that plus how far it is from the nearest of them+ * (each texel carries its nearest edge texel, two sweeps).+ */+function levelShore(field: WaterField, texel: number): void {+ const { nx, nz, sizeX, sizeZ } = field.grid;+ const n = nx * nz;+ if (nx < 2 || nz < 2) return;+ const dx = sizeX / (nx - 1), dz = sizeZ / (nz - 1);+ const wet = (k: number): boolean => field.shore[k]! > 0;+ const seed = new Int32Array(n).fill(-1);+ const offset = new Float32Array(n);+ const dist = new Float32Array(n).fill(Infinity);+ for (let j = 0; j < nz; j++) for (let i = 0; i < nx; i++) {+ const k = j * nx + i, w = wet(k);+ const edge = (i > 0 && wet(k - 1) !== w) || (i < nx - 1 && wet(k + 1) !== w) || (j > 0 && wet(k - nx) !== w) || (j < nz - 1 && wet(k + nx) !== w);+ if (!edge) continue;+ seed[k] = k;+ offset[k] = Math.min(Math.abs(field.shore[k]!), texel);+ dist[k] = offset[k]!;+ }+ const relax = (k: number, from: number): void => {+ const s = seed[from]!;+ if (s < 0) return;+ const ex = ((k % nx) - (s % nx)) * dx, ez = (Math.floor(k / nx) - Math.floor(s / nx)) * dz;+ const d = Math.hypot(ex, ez) + offset[s]!;+ if (d < dist[k]!) { dist[k] = d; seed[k] = s; }+ };+ for (let j = 0; j < nz; j++) for (let i = 0; i < nx; i++) {+ const k = j * nx + i;+ if (i > 0) relax(k, k - 1);+ if (j > 0) { relax(k, k - nx); if (i > 0) relax(k, k - nx - 1); if (i < nx - 1) relax(k, k - nx + 1); }+ }+ for (let j = nz - 1; j >= 0; j--) for (let i = nx - 1; i >= 0; i--) {+ const k = j * nx + i;+ if (i < nx - 1) relax(k, k + 1);+ if (j < nz - 1) { relax(k, k + nx); if (i < nx - 1) relax(k, k + nx + 1); if (i > 0) relax(k, k + nx - 1); }+ }+ for (let k = 0; k < n; k++) {+ if (!Number.isFinite(dist[k]!)) continue;+ field.shore[k] = wet(k) ? dist[k]! : -dist[k]!;+ }+}+/** A texel no body holds takes the height of the nearest that one does: two passes of a chamfer sweep over which texel is nearest. */function fillDry(field: WaterField): void {const { nx, nz } = field.grid;diff --git a/sdk/tests/water-zone.test.ts b/sdk/tests/water-zone.test.tsindex 1f49a8b07..37d0dc0c2 100644--- a/sdk/tests/water-zone.test.ts+++ b/sdk/tests/water-zone.test.ts@@ -3,6 +3,7 @@import { describe, expect, it } from 'vitest';import { WaterField, currentShare, type RiverStation, type ZoneBody, type ZoneGrid, type ZoneLake, type ZoneOcean, type ZoneRiver } from '../src/water/zone';import { polygonSdf, shoreDamp, type Point2 } from '../src/water/shore';+import { surfEnvelope, surfHeight } from '../src/water/waves';// A square lake 40 across round the origin, its surface at y = 0.const square: Point2[] = [{ x: -20, y: -20 }, { x: 20, y: -20 }, { x: 20, y: 20 }, { x: -20, y: 20 }];@@ -148,3 +149,34 @@ describe('a river\'s current', () => {expect(currentShare(60, 6)).toBe(0.125);});});++describe('the shore distance', () => {+ it('is how far across the ground the water\'s edge is, for an ocean over a gentle beach as for a lake', () => {+ // The beach rises one unit in twenty from x = 0: at x = -20 the sea is one deep and twenty from its edge.+ const field = bake([ocean(0)], (x) => x * 0.05);+ expect(field.sample(-20, 0)!.shore).toBeCloseTo(20, 0);+ expect(field.at(10, 0)!.shore).toBeCloseTo(-10, 0);+ });+});++describe('the surf', () => {+ const at = (shore: number, t: number): number => surfHeight(shore, 1, 10, 1, t);++ it('runs in toward the shore', () => {+ // The crest nearest the shore, found at two moments: it has come closer.+ const crest = (t: number): number => {+ let best = -1, where = 0;+ for (let d = 0; d <= 20; d += 0.05) { const h = at(d, t); if (h > best) { best = h; where = d; } }+ return where;+ };+ const t0 = 0.3;+ expect(crest(t0 + 0.2)).toBeLessThan(crest(t0));+ });++ it('is none past four lengths out or far up the ground, and stands highest as it shoals', () => {+ expect(surfEnvelope(45, 40)).toBe(0);+ expect(surfEnvelope(-9, 40)).toBe(0);+ expect(surfEnvelope(5, 40)).toBe(1);+ for (let t = 0; t < 3; t += 0.37) expect(at(41, t)).toBe(0);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 4b2698a6e..4c3d84466 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2720,4 +2720,6 @@ export const NOTED = {{"internal":"The editor half of the wind note: a Weather added in Details drives the wind with the rest."},"feat(editor): the viewport outlines a WaterZone, and the water checks author their water in one":{"internal":"The editor half of Water zones, which carries the note."},+ "feat(water): surf runs in toward the shore, breaks white and runs up the ground":+ {"note":"Surf on the shore."},};