Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(water): surf crests come in from open water as lines instead of tracing every turn of the shore

yhhc2a248c4cb31
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9612222b6..6ea9cd6e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,7 @@ published separately; it ships inside the editor.
- **Rays against the terrain, anywhere.** `Terrains.raycast(origin, direction, maxDistance)` meets the ground's triangles exactly (the ones collision and `heightAt` use) wherever the ray goes, with no physics world and no collision tile there, for a line of sight, a pick or a landing spot.
- **Far versions for generated decoration.** A recipe member can name its far version (`far`: crossed cards, or a tent for a conifer, showing a rectangle of its texture), drawn past its layer's `lodDistance`, and decoration that leans with the ground (`attach: 'align'`) now leans in its merged mesh too.
- **Terrain modifiers, and zones that level their ground.** `Terrains.setModifier` lays a change over the ground (`flattenModifier` levels a circle or a turned box, blending back over its edge) that what is drawn, the queries, rays and collision all follow, remaking only the pages and collision tiles it reaches; `heightBeneathAt` reads the ground as it was made. A `WorldZone` with `flatten` levels its plot to the ground's height at its centre.
+- **Surf comes in from open water as lines.** Its crests followed every turn of the shore, bending into a river's mouth from far out; they now follow a distance of their own, the open water's edge with a river's water taken for land, smoothed over the surf's length, so they come in straight and turn to the shore only as they near it. Where the surf rises, breaks and runs up is still the real shore's, and a river's current calms it over a spread past the mouth rather than cutting it off at the river's side.
- **A river gives way where it runs into the sea or a lake.** Over half its width past their shore it fades into them, its current with it, where it used to stop within a texel and a half and leave its sides running on into the open water: the surf, which no current carries, broke off along those lines. The surf now runs on along the coast and round into the mouth.
- **Water meets the shore along a smooth line.** Close up, a river's banks and the surf on a beach ran in steps a texel of the water zone wide: the baked shore distance is now stored finely near the shore (a signed square root of it), and past the shore the surf's film and the shallows' foam are told dry from wet by the picture's depth at each pixel rather than by the baked depth, which only knew whole texels.
- **The distance to the shore is a distance.** Near the water's edge the baked shore distance was the water's depth (or, on land, the height above the water), so `Waters.shoreAt`, a generated world's `shoreDistance` and the surf's reach mixed heights with distances; the depth is now turned into the distance across the ground by the ground's slope there. Waves still calm as the water shallows.
diff --git a/examples/terrain-water/assets/scenes/main.esscene b/examples/terrain-water/assets/scenes/main.esscene
index 9977b5c49..92f0e40ec 100644
--- a/examples/terrain-water/assets/scenes/main.esscene
+++ b/examples/terrain-water/assets/scenes/main.esscene
@@ -262,9 +262,9 @@
"cellSize": 30,
"detail": 1,
"heightmap": "assets/textures/height.png",
+ "heightmapFormat": 1,
"splatmap": "assets/textures/splat.png",
- "material": "assets/materials/ground.esmaterial",
- "heightmapFormat": 1
+ "material": "assets/materials/ground.esmaterial"
}
}
]
@@ -661,7 +661,7 @@
},
{
"x": 1800,
- "y": 30,
+ "y": 0,
"z": 7900,
"width": 1500
},
diff --git a/examples/terrain-water/assets/textures/height.png b/examples/terrain-water/assets/textures/height.png
index ae1935448..67361ac0f 100644
Binary files a/examples/terrain-water/assets/textures/height.png and b/examples/terrain-water/assets/textures/height.png differ
diff --git a/examples/terrain-water/assets/textures/splat.png b/examples/terrain-water/assets/textures/splat.png
index 8ea9ec35e..ca91b07ac 100644
Binary files a/examples/terrain-water/assets/textures/splat.png and b/examples/terrain-water/assets/textures/splat.png differ
diff --git a/examples/terrain-water/tools/build.mjs b/examples/terrain-water/tools/build.mjs
index cd838d8ab..d5f9b7e87 100644
--- a/examples/terrain-water/tools/build.mjs
+++ b/examples/terrain-water/tools/build.mjs
@@ -49,7 +49,7 @@ const WORLD = {
{ x: 2100, y: 600, z: 2800, width: 1000 },
{ x: 1200, y: 420, z: 4500, width: 1150 },
{ x: 2000, y: 200, z: 6300, width: 1300 },
- { x: 1800, y: 30, z: 7900, width: 1500 },
+ { x: 1800, y: 0, z: 7900, width: 1500 },
{ x: 1900, y: -40, z: 8900, width: 1700 },
],
snow: 4000,
diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.ts
index 1a8ec0393..a3b5b84d7 100644
--- a/sdk/src/water/waterPlugin.ts
+++ b/sdk/src/water/waterPlugin.ts
@@ -170,9 +170,9 @@ export class Waters {
const time = this.app_.getResource(Time).elapsed;
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 still = s.still;
// 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);
+ const surf = surfHeight(s.shore, zone.surf * grown(s.exposure) * s.swell * s.exposure * still, zone.surfLength, zone.waveSpeed, time, s.surf);
// 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);
@@ -419,7 +419,7 @@ export class WaterPlugin implements Plugin {
// A big zone is a second or more of work: it is spread over frames and shown while it runs.
this.baking_?.cancel();
const key = inputs.key;
- const job = bakesOf(app).run('Baking the water', WaterField.baking(inputs.grid, inputs.bodies, this.ground(app)));
+ const job = bakesOf(app).run('Baking the water', WaterField.baking(inputs.grid, inputs.bodies, this.ground(app), inputs.zone.surfLength));
this.baking_ = { key, cancel: job.cancel };
waters.baking = true;
void job.done.then((field) => {
diff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.ts
index 61abde193..4d9ffda6e 100644
--- a/sdk/src/water/waterShader.ts
+++ b/sdk/src/water/waterShader.ts
@@ -148,13 +148,27 @@ vec4 waterZoneField(vec2 p) {
float e = (f.r - 0.5) * 2.0;
return vec4(e * abs(e) * 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) {
+// The distance the surf runs in by at p: the shore's with a river's water taken for land and smoothed over the surf's length, so the crests
+// come in as lines that turn to the shore as they near it and run straight across a river's mouth. Past the region: the ocean's.
+float waterZoneSurf(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)));
+ float e = (textureLod(u_zoneExposure, clamp(uv, 0.0, 1.0), 0.0).g - 0.5) * 2.0;
+ return inside ? e * abs(e) * u_zoneRange.x : u_oceanOn > 0.5 ? 1e6 : -1.0;
+}
+// How much of the surf a current leaves at p: none in a river, and more and more of it away from where the river runs out into open water.
+float waterZoneStill(vec2 p) {
+ vec2 uv = (p - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));
+ return textureLod(u_zoneExposure, clamp(uv, 0.0, 1.0), 0.0).b;
+}
+// The surf (waves.ts surfHeight): its crests are lines of phase (the distance the surf runs in by), and it rises, breaks and runs up by
+// shore, the real distance to the shore. x its height, y how broken it is (white water on and behind a breaking crest).
+vec2 waterSurf(float phase, 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 u = fract(phase / 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));
@@ -174,8 +188,8 @@ void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
// the shore; and the surf running in on it, which a current carries none of.
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 * zone.w * still, u_time.x).x;
+ float still = u_zoneOn > 0.5 ? waterZoneStill(p) : 1.0;
+ float surf = waterSurf(u_zoneOn > 0.5 ? waterZoneSurf(p) : 1e6, 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
@@ -230,12 +244,27 @@ fn waterZoneField(p : vec2f) -> vec4f {
let e = (f.r - 0.5) * 2.0;
return vec4f(e * abs(e) * 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 {
+// The distance the surf runs in by at p: the shore's with a river's water taken for land and smoothed over the surf's length, so the crests
+// come in as lines that turn to the shore as they near it and run straight across a river's mouth. Past the region: the ocean's.
+fn waterZoneSurf(p : vec2f) -> f32 {
+ 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 e = (textureSampleLevel(u_zoneExposure, u_zoneExposure_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).g - 0.5) * 2.0;
+ if (inside) { return e * abs(e) * mc.u_zoneRange.x; }
+ if (mc.u_oceanOn > 0.5) { return 1e6; }
+ return -1.0;
+}
+// How much of the surf a current leaves at p: none in a river, and more and more of it away from where the river runs out into open water.
+fn waterZoneStill(p : vec2f) -> f32 {
+ let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));
+ return textureSampleLevel(u_zoneExposure, u_zoneExposure_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).b;
+}
+fn waterSurf(phase : f32, 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);
+ let u = fract(phase / 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));
@@ -255,8 +284,11 @@ fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, ve
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 * zone.w * still, tc.u_time.x).x;
+ var still = 1.0;
+ if (mc.u_zoneOn > 0.5) { still = waterZoneStill(p); }
+ var surfAt = 1e6;
+ if (mc.u_zoneOn > 0.5) { surfAt = waterZoneSurf(p); }
+ let surf = waterSurf(surfAt, 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
@@ -403,13 +435,27 @@ vec4 waterZoneField(vec2 p) {
float e = (f.r - 0.5) * 2.0;
return vec4(e * abs(e) * 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) {
+// The distance the surf runs in by at p: the shore's with a river's water taken for land and smoothed over the surf's length, so the crests
+// come in as lines that turn to the shore as they near it and run straight across a river's mouth. Past the region: the ocean's.
+float waterZoneSurf(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)));
+ float e = (textureLod(u_zoneExposure, clamp(uv, 0.0, 1.0), 0.0).g - 0.5) * 2.0;
+ return inside ? e * abs(e) * u_zoneRange.x : u_oceanOn > 0.5 ? 1e6 : -1.0;
+}
+// How much of the surf a current leaves at p: none in a river, and more and more of it away from where the river runs out into open water.
+float waterZoneStill(vec2 p) {
+ vec2 uv = (p - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));
+ return textureLod(u_zoneExposure, clamp(uv, 0.0, 1.0), 0.0).b;
+}
+// The surf (waves.ts surfHeight): its crests are lines of phase (the distance the surf runs in by), and it rises, breaks and runs up by
+// shore, the real distance to the shore. x its height, y how broken it is (white water on and behind a breaking crest).
+vec2 waterSurf(float phase, 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 u = fract(phase / 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));
@@ -516,16 +562,18 @@ void main() {
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 still = zoneOn ? waterZoneStill(wp) : 1.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);
+ float surfDist = zoneOn ? waterZoneSurf(wp) : 1e6;
+ vec2 toSea = vec2(waterZoneSurf(wp + vec2(surfStep, 0.0)) - waterZoneSurf(wp - vec2(surfStep, 0.0)),
+ waterZoneSurf(wp + vec2(0.0, surfStep)) - waterZoneSurf(wp - vec2(0.0, surfStep))) / (2.0 * surfStep);
// A distance to the shore climbs one unit a unit everywhere but on the ridge between two shores, where it turns back: there the way to
// the shore is no one way, and the surf's slope fades out rather than flipping on a line.
toSea *= smoothstep(0.55, 0.9, length(toSea));
- 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;
+ vec2 surf = waterSurf(surfDist, shoreDist, surfH, time);
+ float surfRise = (waterSurf(surfDist + surfStep * 0.5, shoreDist + surfStep * 0.5, surfH, time).x
+ - waterSurf(surfDist - surfStep * 0.5, 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);
@@ -823,12 +871,27 @@ fn waterZoneField(p : vec2f) -> vec4f {
let e = (f.r - 0.5) * 2.0;
return vec4f(e * abs(e) * 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 {
+// The distance the surf runs in by at p: the shore's with a river's water taken for land and smoothed over the surf's length, so the crests
+// come in as lines that turn to the shore as they near it and run straight across a river's mouth. Past the region: the ocean's.
+fn waterZoneSurf(p : vec2f) -> f32 {
+ 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 e = (textureSampleLevel(u_zoneExposure, u_zoneExposure_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).g - 0.5) * 2.0;
+ if (inside) { return e * abs(e) * mc.u_zoneRange.x; }
+ if (mc.u_oceanOn > 0.5) { return 1e6; }
+ return -1.0;
+}
+// How much of the surf a current leaves at p: none in a river, and more and more of it away from where the river runs out into open water.
+fn waterZoneStill(p : vec2f) -> f32 {
+ let uv = (p - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));
+ return textureSampleLevel(u_zoneExposure, u_zoneExposure_s, clamp(uv, vec2f(0.0), vec2f(1.0)), 0.0).b;
+}
+fn waterSurf(phase : f32, 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);
+ let u = fract(phase / 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));
@@ -944,15 +1007,19 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vec
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 still = 1.0;
+ if (zoneOn) { still = waterZoneStill(wp); }
var surfH = 0.0;
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 toSeaRaw = 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);
+ var surfDist = 1e6;
+ if (zoneOn) { surfDist = waterZoneSurf(wp); }
+ let toSeaRaw = vec2f(waterZoneSurf(wp + vec2f(surfStep, 0.0)) - waterZoneSurf(wp - vec2f(surfStep, 0.0)),
+ waterZoneSurf(wp + vec2f(0.0, surfStep)) - waterZoneSurf(wp - vec2f(0.0, surfStep))) / (2.0 * surfStep);
let toSea = toSeaRaw * smoothstep(0.55, 0.9, length(toSeaRaw));
- 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;
+ let surf = waterSurf(surfDist, shoreDist, surfH, time);
+ let surfRise = (waterSurf(surfDist + surfStep * 0.5, shoreDist + surfStep * 0.5, surfH, time).x
+ - waterSurf(surfDist - surfStep * 0.5, 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);
diff --git a/sdk/src/water/waves.ts b/sdk/src/water/waves.ts
index 821d2cea0..ed30b7dcf 100644
--- a/sdk/src/water/waves.ts
+++ b/sdk/src/water/waves.ts
@@ -89,16 +89,17 @@ export function waveSlope(p: WaveParams, x: number, z: number, time: number): [n
/**
* 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
+ * it. `shore` is the distance to the shore (above zero on the water), `height` how high a breaker stands at most; the crests are lines
+ * of `phase` (by default the shore distance; a zone's is that smoothed, so they come in straight from open water). 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 {
+export function surfHeight(shore: number, height: number, length: number, speed: number, time: number, phase = shore): 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);
+ const u = fract(phase / 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));
diff --git a/sdk/src/water/zone.ts b/sdk/src/water/zone.ts
index 2c49791f5..292f114fe 100644
--- a/sdk/src/water/zone.ts
+++ b/sdk/src/water/zone.ts
@@ -136,6 +136,10 @@ 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;
+ /** The distance the surf runs in by: the shore's, a river's water taken for land, smoothed over the surf's length. */
+ surf: number;
+ /** How much of the surf a current leaves: 0 in a river, rising away from its mouth over half the surf's length. */
+ still: number;
/** How open it is to the wind, 0 to 1: how far the weather raises its waves (see {@link ZoneOcean.exposure}). */
exposure: number;
}
@@ -161,6 +165,10 @@ export class WaterField {
readonly flowX: Float32Array;
readonly flowZ: Float32Array;
readonly depth: Float32Array;
+ /** The distance the surf runs in by (see {@link FieldSample.surf}). */
+ readonly surf: Float32Array;
+ /** How much of the surf a current leaves (see {@link FieldSample.still}). */
+ readonly still: 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;
@@ -179,6 +187,8 @@ export class WaterField {
this.flowX = new Float32Array(n);
this.flowZ = new Float32Array(n);
this.depth = new Float32Array(n);
+ this.surf = new Float32Array(n);
+ this.still = new Float32Array(n).fill(1);
this.exposure = new Float32Array(n).fill(1);
this.owner = new Int32Array(n);
}
@@ -189,8 +199,8 @@ export class WaterField {
* The lakes come first, then the rivers have what they leave (a river runs into a lake and is the lake there), and the ocean what both leave. A texel no body holds keeps the height of the nearest water, so the
* surface's vertices there (which the shore cuts away) do not pull the water's edge down to nothing.
*/
- static bake(grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround): WaterField {
- const job = WaterField.baking(grid, bodies, ground);
+ static bake(grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength = 0): WaterField {
+ const job = WaterField.baking(grid, bodies, ground, surfLength);
for (;;) {
const next = job.next();
if (next.done) return next.value;
@@ -198,7 +208,7 @@ export class WaterField {
}
/** {@link WaterField.bake} as a job that yields its progress (0 to 1) every few rows, for spreading over frames. */
- static *baking(grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround): Generator<number, WaterField, void> {
+ static *baking(grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength = 0): Generator<number, WaterField, void> {
const ocean = (bodies.find((b) => b.kind === 'ocean') as ZoneOcean | undefined) ?? null;
const field = new WaterField(grid, ocean);
const texel = Math.max(grid.sizeX / Math.max(grid.nx - 1, 1), grid.sizeZ / Math.max(grid.nz - 1, 1));
@@ -207,6 +217,8 @@ export class WaterField {
const bounded = [...bodies.filter((b) => b.kind === 'lake'), ...bodies.filter((b) => b.kind === 'river')] as (ZoneLake | ZoneRiver)[];
const boxes = bounded.map((b) => boundsOf(b));
const grounds = new Float64Array(grid.nx * grid.nz).fill(Number.NaN);
+ // How much of each texel's water is a river's: the surf takes it for land.
+ const rivers = new Float32Array(grid.nx * grid.nz);
for (let j = 0; j < grid.nz; j++) {
if (j % 32 === 0) yield 0.3 * (j / grid.nz);
for (let i = 0; i < grid.nx; i++) {
@@ -233,7 +245,7 @@ export class WaterField {
const z = grid.minZ + (j / Math.max(grid.nz - 1, 1)) * grid.sizeZ;
const g = Number.isNaN(grounds[k]!) ? null : grounds[k]!;
const slope = g === null ? MIN_SLOPE : slopeAt(i, j);
- 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, lakeShore = -Infinity;
+ 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, lakeShore = -Infinity, riverW = 0;
// Ground below the sea's level that the open sea does not reach is a dry basin: as far above the sea as a texel.
const seaDeep = !ocean ? -DEEP : g === null ? DEEP : g < ocean.level && !sea![k] ? -texel : (ocean.level - g) / slope;
for (let b = 0; b < bounded.length; b++) {
@@ -246,11 +258,15 @@ export class WaterField {
// A river gives way to the lake or the sea it runs into over half its width past their shore, its current fading
// with it: cut off at their shore, its sides would run on into the open water as lines the surf stops at.
const fade = Math.max(say.half, blend);
+ // Its mouth on the sea is where its surface comes down to the sea's (its bed may lie under the sea's level far
+ // upstream): how far past that it is, from how far under it its surface runs and how fast it falls along its course.
+ const pastSea = ocean ? (ocean.level - say.height) / Math.max(say.grade, 1e-3) : -DEEP;
const weight = bounded[b]!.kind === 'river'
- ? inside * (1 - smooth(0, fade, lakeShore)) * (1 - smooth(0, fade, seaDeep)) : inside;
+ ? inside * (1 - smooth(0, fade, lakeShore)) * (1 - smooth(0, fade, pastSea)) : inside;
if (bounded[b]!.kind === 'lake') lakeShore = Math.max(lakeShore, say.shore);
if (weight <= 0) continue;
held = Math.max(held, weight);
+ if (bounded[b]!.kind === 'river') riverW += 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; }
@@ -276,6 +292,7 @@ export class WaterField {
field.exposure[k] = ex / w;
field.flowX[k] = fx / w;
field.flowZ[k] = fz / w;
+ rivers[k] = riverW / w;
} else {
field.height[k] = Number.NaN;
}
@@ -284,6 +301,7 @@ export class WaterField {
}
yield* levelShore(field, texel);
yield* fillDry(field);
+ surfDistance(field, rivers, texel, surfLength);
return field;
}
@@ -304,7 +322,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), exposure: lerp2(this.exposure),
+ shore: lerp2(this.shore), depth: lerp2(this.depth), surf: lerp2(this.surf), still: lerp2(this.still), exposure: lerp2(this.exposure),
};
}
@@ -317,7 +335,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, exposure: o.exposure ?? 1 };
+ return { key: o.key, height: o.level, amp: o.waveHeight, calm: 1, swell: o.waveHeight, flowX: 0, flowZ: 0, shore: DEEP, depth: DEEP, surf: DEEP, still: 1, 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). */
@@ -345,7 +363,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, as its square root (fine where the water is shallow, where the shore is drawn by it); a the swell (the body's waves' height). field (filtered): r the shore distance (0.5 at it, a signed square root); gb the current (0.5 still); a the calm.
- * exposure (filtered): r how open the water is to the wind. Each over its range in `r`.
+ * exposure (filtered): r how open the water is to the wind; g the distance the surf runs in by; b how much surf a current leaves. Each over its range in `r`.
*/
encode(r: ZoneRanges): { heights: Uint8Array; field: Uint8Array; exposure: Uint8Array } {
const n = this.height.length;
@@ -364,6 +382,10 @@ export class WaterField {
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]!);
+ // g: the distance the surf runs in by, as a signed square root like the shore's.
+ const surf = Math.max(Math.min(this.surf[k]! / r.shore, 1), -1);
+ exposure[k * 4 + 1] = byte(Math.sign(surf) * Math.sqrt(Math.abs(surf)) / 2 + 0.5);
+ exposure[k * 4 + 2] = byte(this.still[k]!);
exposure[k * 4 + 3] = 255;
}
return { heights, field, exposure };
@@ -372,7 +394,7 @@ export class WaterField {
/** What one body says about a point: its height there, how far inside it the point is, its waves and its current. Null where it says nothing. */
function sayOf(body: ZoneLake | ZoneRiver, x: number, z: number, g: number | null, slope: number):
- { height: number; shore: number; amp: number; calm: number; fx: number; fz: number; half: number } | null {
+ { height: number; shore: number; amp: number; calm: number; fx: number; fz: number; half: number; grade: number } | null {
if (body.kind === 'lake') {
const [lx, lz] = body.toLocal(x, z);
// The depth as a distance across the ground to where the water meets it (the ground's slope there sets how far that is).
@@ -381,7 +403,7 @@ function sayOf(body: ZoneLake | ZoneRiver, x: number, z: number, g: number | nul
const shore = Math.min(polygonSdf(body.outline, lx, lz), depth / slope);
// The waves calm toward the shore and as the water shallows, which on a flat shelf far from any shore is the depth alone.
const calm = shoreDamp(Math.min(shore, depth), body.shoreWidth);
- return { height: body.level, shore, amp: body.waveHeight * calm, calm, fx: 0, fz: 0, half: 0 };
+ return { height: body.level, shore, amp: body.waveHeight * calm, calm, fx: 0, fz: 0, half: 0, grade: 0 };
}
const st = body.stations;
if (st.length < 2) return null;
@@ -409,7 +431,7 @@ function sayOf(body: ZoneLake | ZoneRiver, x: number, z: number, g: number | nul
const length = st.reduce((n, p, i) => (i ? n + Math.hypot(p.x - st[i - 1]!.x, p.z - st[i - 1]!.z) : 0), 0);
const run = smooth(0, 2 * half, along * length) * smooth(0, 2 * half, (1 - along) * length);
const calm = shoreDamp(Math.min(shore, depth), body.shoreWidth);
- return { height: y, shore, amp: body.waveHeight * calm, calm, fx: dx * speed * run, fz: dz * speed * run, half };
+ return { height: y, shore, amp: body.waveHeight * calm, calm, fx: dx * speed * run, fz: dz * speed * run, half, grade: Math.abs(b.y - a.y) / Math.max(Math.hypot(b.x - a.x, b.z - a.z), 1e-6) };
}
/**
@@ -540,6 +562,76 @@ function* fillDry(field: WaterField): Generator<number, void, void> {
}
}
+/**
+ * The distance the surf runs in by: the shore distance with a river's water taken for land (a current carries no surf, and its mouth is
+ * no bay the crests bend into), smoothed over the surf's length. A crest is a line of it: smoothed, the crests come in from the open
+ * water as lines and turn to follow the shore only as they near it, instead of tracing every turn of it from far out.
+ */
+function surfDistance(field: WaterField, rivers: Float32Array, texel: number, surfLength: number): void {
+ const { nx, nz } = field.grid;
+ const n = nx * nz;
+ // Distances across the texels (8-neighbour chamfer) from the open water's edge: into the water above zero, onto the land (a river's
+ // water with it) below. The surf needs where the crests line up, which this keeps, not the shore to a texel, which the real one has.
+ const wet = new Uint8Array(n);
+ for (let k = 0; k < n; k++) wet[k] = field.shore[k]! > 0 && rivers[k]! < 0.5 ? 1 : 0;
+ const cap = Math.max(surfLength * 8, texel * 16);
+ const toWater = chamfer(nx, nz, wet, 0), toLand = chamfer(nx, nz, wet, 1);
+ for (let k = 0; k < n; k++) field.surf[k] = Math.min(Math.max((toLand[k]! - toWater[k]!) * texel, -cap), cap);
+ blur(field.surf, nx, nz, Math.round(surfLength / Math.max(texel, 1e-6)));
+ // A river's current carries no surf, and spreads as it runs out into open water: the surf comes back over half its length.
+ for (let k = 0; k < n; k++) field.still[k] = 1 - rivers[k]!;
+ blur(field.still, nx, nz, Math.round((surfLength * 0.5) / Math.max(texel, 1e-6)));
+ // Spread out past the mouth, never in: the river itself, banks and all, keeps none (the land beside it would lend it some).
+ for (let k = 0; k < n; k++) field.still[k] = Math.min(field.still[k]!, 1 - rivers[k]!);
+}
+
+/** `values` (a grid nx by nz) blurred in place over `radius` texels: three box passes each way, near enough a Gaussian, at a cost that
+ * does not grow with the radius. */
+function blur(values: Float32Array, nx: number, nz: number, radius: number): void {
+ if (radius < 1 || nx < 2 || nz < 2) return;
+ const line = new Float32Array(Math.max(nx, nz));
+ const pass = (count: number, length: number, at: (c: number, i: number) => number): void => {
+ for (let c = 0; c < count; c++) {
+ for (let i = 0; i < length; i++) line[i] = values[at(c, i)]!;
+ let sum = 0;
+ for (let i = -radius; i <= radius; i++) sum += line[Math.min(Math.max(i, 0), length - 1)]!;
+ for (let i = 0; i < length; i++) {
+ values[at(c, i)] = sum / (2 * radius + 1);
+ sum += line[Math.min(i + radius + 1, length - 1)]! - line[Math.max(i - radius, 0)]!;
+ }
+ }
+ };
+ for (let p = 0; p < 3; p++) {
+ pass(nz, nx, (j, i) => j * nx + i);
+ pass(nx, nz, (i, j) => j * nx + i);
+ }
+}
+
+/** How many texels each texel is from the nearest one whose `wet` is not `from` (half a texel at the edge, 0 on the other side). */
+function chamfer(nx: number, nz: number, wet: Uint8Array, from: number): Float32Array {
+ const n = nx * nz;
+ const d = new Float32Array(n);
+ for (let k = 0; k < n; k++) d[k] = wet[k] === from ? 1e9 : 0;
+ const relax = (k: number, o: number, w: number): void => { if (d[o]! + w < d[k]!) d[k] = d[o]! + w; };
+ for (let j = 0; j < nz; j++) for (let i = 0; i < nx; i++) {
+ const k = j * nx + i;
+ if (i > 0) relax(k, k - 1, 1);
+ if (j > 0) relax(k, k - nx, 1);
+ if (i > 0 && j > 0) relax(k, k - nx - 1, Math.SQRT2);
+ if (i < nx - 1 && j > 0) relax(k, k - nx + 1, Math.SQRT2);
+ }
+ for (let j = nz - 1; j >= 0; j--) for (let i = nx - 1; i >= 0; i--) {
+ const k = j * nx + i;
+ if (i < nx - 1) relax(k, k + 1, 1);
+ if (j < nz - 1) relax(k, k + nx, 1);
+ if (i < nx - 1 && j < nz - 1) relax(k, k + nx + 1, Math.SQRT2);
+ if (i > 0 && j < nz - 1) relax(k, k + nx - 1, Math.SQRT2);
+ }
+ // The edge lies between two texels: half a texel from each.
+ for (let k = 0; k < n; k++) if (d[k]! > 0 && d[k]! < 1e9) d[k] = d[k]! - 0.5;
+ return d;
+}
+
function smooth(a: number, b: number, x: number): number {
const t = Math.min(Math.max((x - a) / (b - a), 0), 1);
return t * t * (3 - 2 * t);
diff --git a/sdk/tests/water-zone.test.ts b/sdk/tests/water-zone.test.ts
index e1879895a..f52b5d230 100644
--- a/sdk/tests/water-zone.test.ts
+++ b/sdk/tests/water-zone.test.ts
@@ -182,3 +182,25 @@ describe('the surf', () => {
for (let t = 0; t < 3; t += 0.37) expect(at(41, t)).toBe(0);
});
});
+
+describe('the distance the surf runs in by', () => {
+ // A beach along z = 0 (the sea to +z, rising 1 in 10 inland) with a river cut through it along x = 0, its mouth on the beach.
+ const g: ZoneGrid = { minX: -200, minZ: -100, sizeX: 400, sizeZ: 200, nx: 401, nz: 201 };
+ const ground = (x: number, z: number): number => (Math.abs(x) < 12 && z < 10 ? -Math.min(8, (12 - Math.abs(x)) * 0.5) : -z * 0.1);
+ const stations: RiverStation[] = [];
+ for (let z = -100; z <= 10; z += 5) stations.push({ x: 0, z, y: 0.5, half: 12, dx: 0, dz: 1, speed: 3 });
+ const mouth: ZoneRiver = { kind: 'river', key: 9, waveHeight: 0, shoreWidth: 2, stations };
+ const field = WaterField.bake(g, [{ kind: 'ocean', key: 3, level: 0, waveHeight: 2, shoreWidth: 6 }, mouth], ground, 80);
+
+ it('runs straight across a river mouth, where the shore itself bends into it', () => {
+ // Off the mouth the shore distance dips toward the river's water; the surf's runs on as along the open beach.
+ const off = field.sample(0, 20)!, beach = field.sample(120, 20)!;
+ expect(Math.abs(off.surf - beach.surf)).toBeLessThan(Math.abs(off.shore - beach.shore));
+ expect(Math.abs(off.surf - beach.surf)).toBeLessThan(10);
+ });
+
+ it('takes a river for land', () => {
+ expect(field.sample(0, -50)!.surf).toBeLessThan(0);
+ expect(field.sample(0, -50)!.shore).toBeGreaterThan(0);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 6526dfaca..3b3a31e6e 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2814,4 +2814,6 @@ export const NOTED = {
{"note":"Water meets the shore along a smooth line."},
"fix(water): a river fades into the sea or lake it runs into, so the surf is not cut along its sides":
{"note":"A river gives way where it runs into the sea or a lake."},
+ "fix(water): surf crests come in from open water as lines instead of tracing every turn of the shore":
+ {"note":"Surf comes in from open water as lines."},
};