A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(water): a sea is eight waves spread about the wind, not four - each shorter and lower than the last at a heading of its own, so the swell no longer reads as bands; the shader's waves are written out from the one table the CPU sums, and a quality level allows 3, 5 or 8 of them
yhhcc73a8a4e14e
diff --git a/desktop b/desktopindex b5ed7ca35..bd42a882f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit b5ed7ca35e1abaab37d420189f928c03b924abcd+Subproject commit bd42a882f57c435c2282b28918d80c66f2b92eeadiff --git a/docs/astro/src/content/docs/graphics/water.mdx b/docs/astro/src/content/docs/graphics/water.mdxindex 588c780db..74a2efbfb 100644--- a/docs/astro/src/content/docs/graphics/water.mdx+++ b/docs/astro/src/content/docs/graphics/water.mdx@@ -64,7 +64,7 @@ terrain changes, at a cost of the texels times the bodies.## Waves-Four peaked sines (`exp(sin(theta) - 1)`: a crest narrower than its trough) a few directions apart, each with a length, a height and a speed+Eight peaked sines (`exp(sin(theta) - 1)`: a crest narrower than its trough) spread about the wind, each shorter than the last, 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 thefield: 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 wateris 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,@@ -262,7 +262,7 @@ Water spends what the project's quality level says it may. The five fields are i| Field | Low | Medium | High | What it does ||---|---|---|---|---|-| `waterWaves` | 2 | 3 | 4 | How many of the four waves are summed: in the geometry, the shading, and what `Waters.sample` answers. |+| `waterWaves` | 3 | 5 | 8 | How many of the eight waves are summed, longest first: in the geometry, the shading, and what `Waters.sample` answers. || `waterRippleCells` | 32 | 64 | 128 | The most cells along a side of the ripple grid; the zone's own `ripples` is held to it, and 0 keeps none. || `waterDisplacement` | off | on | on | Whether the waves lift the geometry. Off is the **lite water**: a surface at the water's rest height whose waves are in the shading only. || `waterMirror` | off | on | on | Whether the surface seen from below mirrors the world under it (the screen-space march). |@@ -350,4 +350,4 @@ What is not there yet, so nobody is surprised:- The mirror from below is screen-space: it shows only what the frame has on screen, and a ray that leaves the picture or meets nothing finds the water's own colour.- Ripples only bend the shading and carry foam: they do not lift the geometry, and they are one window following the camera, so water far from the camera keeps none and two camerasin a split screen share the first's. Foam that a ripple leaves is not carried by a river's current, and the waves the geometry is lifted by are not carried by it either (only the shading's).-- The waves are the four peaked sines, not a spectrum, and they lift the surface without pushing it sideways.+- The waves are eight peaked sines spread about the wind, not a simulated spectrum, and they lift the surface without pushing it sideways.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx b/docs/astro/src/content/docs/zh-cn/graphics/water.mdxindex 8df462ebb..53c37fd8f 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/water.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/water.mdx@@ -53,7 +53,7 @@ description: 若干 WaterBody 组件说明海洋、湖泊或河流在哪里,一## 波浪-四道波峰比波谷更尖的正弦波(`exp(sin(theta) - 1)`),相差几个方向,各自的波长、高度和速度是区域的 `waveLength`、`waveSpeed`、`waveDirection` 的份额。所有水体共用它们;它们在某处有多高,由场里那一处决定:所在水体的 `waveHeight`,乘以岸线留下的份额,再乘以天气的份额(驱动风的 `Weather` 会按水面迎风的开阔程度放大波浪:风浪随吹过的水面长度增长,所以海完全受天气影响,湖按其宽度与八个 `waveLength` 之比受影响,河几乎不受影响)。它们会**移动几何体**:着色器按波高抬起每个顶点,片元按同一个公式逐像素取斜率,所以被光照的表面就是画出来的表面,和天空交界的轮廓也随波浪起伏。+八道波峰比波谷更尖的正弦波(`exp(sin(theta) - 1)`),绕风向散开、一道比一道短,各自的波长、高度和速度是区域的 `waveLength`、`waveSpeed`、`waveDirection` 的份额。所有水体共用它们;它们在某处有多高,由场里那一处决定:所在水体的 `waveHeight`,乘以岸线留下的份额,再乘以天气的份额(驱动风的 `Weather` 会按水面迎风的开阔程度放大波浪:风浪随吹过的水面长度增长,所以海完全受天气影响,湖按其宽度与八个 `waveLength` 之比受影响,河几乎不受影响)。它们会**移动几何体**:着色器按波高抬起每个顶点,片元按同一个公式逐像素取斜率,所以被光照的表面就是画出来的表面,和天空交界的轮廓也随波浪起伏。波浪在世界的 xz 平面上度量,把水面竖直向上抬起。参数以世界单位计:以米为单位的场景用默认值,以厘米为单位的要把长度相应缩放。@@ -171,7 +171,7 @@ Details 只显示水体这种形态用得到的字段:湖有尺寸和边界,河| 字段 | 低 | 中 | 高 | 作用 ||---|---|---|---|---|-| `waterWaves` | 2 | 3 | 4 | 四道波里累加几道:几何、着色以及 `Waters.sample` 的回答都按它。 |+| `waterWaves` | 3 | 5 | 8 | 八道波里从最长的起累加几道:几何、着色以及 `Waters.sample` 的回答都按它。 || `waterRippleCells` | 32 | 64 | 128 | 涟漪网格每边最多多少格;区域自己的 `ripples` 会被限制到它,0 表示不保留。 || `waterDisplacement` | 关 | 开 | 开 | 波浪是否抬起几何体。关就是**轻量水**:位于水面静止高度的表面,波浪只在着色里。 || `waterMirror` | 关 | 开 | 开 | 从下面看水面时,是否映出它下面的世界(屏幕空间步进)。 |@@ -222,4 +222,4 @@ Details 只显示水体这种形态用得到的字段:湖有尺寸和边界,河- 焦散和光束只跟随第一盏平行光,来自一个图案而不是模拟:这张网并不响应波浪的真实形状。从上面看时,焦散把水下的东西当作朝上的面(画面里那里没有法线),所以水面下的一面墙会像地板一样被照亮。- 从下面看的镜子是屏幕空间的:它只显示帧里在屏幕上的东西,射线离开画面或什么也没碰到时,找到的是水自己的颜色。- 涟漪只弯折着色并携带泡沫:不会抬起几何体;它们是跟随相机的一个窗口,所以离相机远的水什么也不保留,分屏时两个相机共用第一个的。涟漪留下的泡沫不会被河流的水流带走,抬起几何体的波浪也不会(只有着色里的会)。-- 波浪是这四道波峰尖的正弦,不是波谱,并且只把表面抬起,不会把它推向一侧。+- 波浪是这八道绕风向散开的波峰尖的正弦,不是模拟出的波谱,并且只把表面抬起,不会把它推向一侧。diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex 20ce0d60e..b00ede974 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -357,7 +357,7 @@ export {type PreSceneDrawCallback,type PreSceneDrawInfo,} from './render/customDraw';-export { QualityController, judgeFrames, parseQualityConfig, resolveQualityProfile, defaultQualityProfile, defaultQualityMode } from './render/quality';+export { QualityController, judgeFrames, parseQualityConfig, resolveQualityProfile, defaultQualityProfile, defaultQualityMode, MOST_WATER_WAVES } from './render/quality';export type {QualityConfig, QualityProfile, QualityLevel, QualityMode,QualityReport, QualitySample, FrameVerdict, DeviceQualityInfo, DeviceQualityRule,diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.tsindex 8e1443d16..23e0ae46f 100644--- a/sdk/src/render/quality.ts+++ b/sdk/src/render/quality.ts@@ -15,6 +15,9 @@ export interface DeviceQualityInfo {cores?: number;}+/** The size of the set a body of water's waves are taken from (water/waves.ts: WAVE_SET_SIZE). */+export const MOST_WATER_WAVES = 8;+export interface QualityProfile {renderScale: number;minRenderScale: number;@@ -53,7 +56,7 @@ export interface QualityProfile {depthPrepass: boolean;postProcess: boolean;ssao: boolean;- /** How many of a body of water's four waves are summed: in the geometry, the shading and what the surface answers for code. 1 to 4. */+ /** How many of a body of water's waves are summed, longest first: in the geometry, the shading and what the surface answers for code. 1 to the size of the water's set. */waterWaves: number;/** The most cells along a side of the ripple grid a body of water keeps; the body's own `ripples` is held to it. 0 keeps none. */waterRippleCells: number;@@ -155,7 +158,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {shadowAtlasSize: 1024, shadowCellSize: 256, shadowCascades: 2,planarReflectionScale: 0.25, planarReflectionMaxSize: 512, planarReflectionUpdatesPerSecond: 0, depthPrepass: false,shadowDistance: 0, detailScale: 0.5, particleLimit: 1000, postProcess: true, ssao: false,- waterWaves: 2, waterRippleCells: 32, waterDisplacement: false, waterMirror: false, waterCaustics: false,+ waterWaves: 3, waterRippleCells: 32, waterDisplacement: false, waterMirror: false, waterCaustics: false,skipEffects: ['ssr', 'taa', 'depthOfField', 'lightShafts', 'motionBlur', 'lensFlare', 'gtao', 'subsurface', 'voxelGI', 'dynamicGI'],shelterMaskSize: 256, shadowSoftSamples: 8, lighting: 'direct', dynamicGIReduced: true, drawCallBudget: 150, textureStreaming: true, textureStreamingBudget: 128,},@@ -164,7 +167,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {shadowAtlasSize: 2048, shadowCellSize: 512, shadowCascades: 3,planarReflectionScale: 0.5, planarReflectionMaxSize: 1024, planarReflectionUpdatesPerSecond: 0, depthPrepass: true,shadowDistance: 0, detailScale: 0.8, particleLimit: 5000, postProcess: true, ssao: true,- waterWaves: 3, waterRippleCells: 64, waterDisplacement: true, waterMirror: true, waterCaustics: true,+ waterWaves: 5, waterRippleCells: 64, waterDisplacement: true, waterMirror: true, waterCaustics: true,skipEffects: ['ssr', 'depthOfField'],shelterMaskSize: 512, shadowSoftSamples: 12, lighting: 'direct', dynamicGIReduced: true, drawCallBudget: 400, textureStreaming: true, textureStreamingBudget: 256,},@@ -175,7 +178,7 @@ const PROFILES: Record<QualityLevel, QualityProfile> = {shadowAtlasSize: 4096, shadowCellSize: 1024, shadowCascades: 4,planarReflectionScale: 1, planarReflectionMaxSize: 2048, planarReflectionUpdatesPerSecond: 0, depthPrepass: true,shadowDistance: 0, detailScale: 1, particleLimit: 20000, postProcess: true, ssao: true,- waterWaves: 4, waterRippleCells: 128, waterDisplacement: true, waterMirror: true, waterCaustics: true,+ waterWaves: 8, waterRippleCells: 128, waterDisplacement: true, waterMirror: true, waterCaustics: true,skipEffects: [],shelterMaskSize: 1024, shadowSoftSamples: 16, lighting: 'full', dynamicGIReduced: false, drawCallBudget: 1500, textureStreaming: false, textureStreamingBudget: 0,},@@ -281,7 +284,7 @@ function resolveProfile(level: QualityLevel, value: unknown): QualityProfile {postProcess: typeof r.postProcess === 'boolean' ? r.postProcess : base.postProcess,ssao: typeof r.ssao === 'boolean' ? r.ssao : base.ssao,dynamicGIReduced: typeof r.dynamicGIReduced === 'boolean' ? r.dynamicGIReduced : base.dynamicGIReduced,- waterWaves: Math.round(finite(r.waterWaves, base.waterWaves, 1, 4)),+ waterWaves: Math.round(finite(r.waterWaves, base.waterWaves, 1, MOST_WATER_WAVES)),waterRippleCells: Math.round(finite(r.waterRippleCells, base.waterRippleCells, 0, 256)),waterDisplacement: typeof r.waterDisplacement === 'boolean' ? r.waterDisplacement : base.waterDisplacement,waterMirror: typeof r.waterMirror === 'boolean' ? r.waterMirror : base.waterMirror,diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex 71ce1ae0b..721c56476 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -34,7 +34,7 @@ import { BlendMode } from '../render/blend';import { log } from '../util/logger';import { bakesOf } from '../runtime/bakes';import type { Entity } from '../types';-import { surfHeight, waveHeight, waveSlope, type WaveParams } from './waves';+import { surfHeight, waveHeight, waveSlope, WAVE_SET_SIZE, type WaveParams } from './waves';import { buildOceanMesh, oceanReach, oceanSnap } from './waterMesh';import { worldUnitsPerMeter } from '../ecs/worldUnits';import { type Point2 } from './shore';@@ -124,7 +124,7 @@ export interface WaterQuality {}/** Everything on: a project with no quality policy, off a minigame. */-export const FULL_WATER: WaterQuality = { waves: 4, rippleCells: 256, displacement: true, mirror: true, caustics: true };+export const FULL_WATER: WaterQuality = { waves: WAVE_SET_SIZE, rippleCells: 256, displacement: true, mirror: true, caustics: true };/*** What water is allowed: the active quality profile when the project has a quality policy running; else the low profile on a minigame, which has the least to spend anddiff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.tsindex ac0c484d9..cd1a837a0 100644--- a/sdk/src/water/waterShader.ts+++ b/sdk/src/water/waterShader.ts@@ -8,6 +8,24 @@*/import { makeBuiltinShaderTemplate } from '../render/builtinShaders';import { CAUSTICS_GLSL, CAUSTICS_WGSL } from '../render/waterCaustics';+import { WAVE_SET, WAVE_SET_SIZE } from './waves';++// The waves, written into the shader from the one table the CPU sums (waves.ts).+const num = (v: number): string => v.toFixed(6);+const WAVE_ROWS = WAVE_SET.map(([heading, length, height, speed]) => `(${num(heading)}, ${num(length)}, ${num(height)}, ${num(speed)})`);+const WAVES_GLSL = `const vec4 SET[${WAVE_SET_SIZE}] = vec4[${WAVE_SET_SIZE}](${WAVE_ROWS.map((r) => `vec4${r}`).join(', ')});`;+const WAVES_WGSL = `var wave = array<vec4f, ${WAVE_SET_SIZE}>(${WAVE_ROWS.map((r) => `vec4f${r}`).join(', ')});`;+/** One wave's arguments to `peakedWave`: its turn off the wind, its frequency and its speed as multiples of the longest's, its share of the height. */+const waveArgs = ([heading, length, height, speed]: readonly [number, number, number, number]): string => {+ const a = heading * Math.PI / 180;+ return `${num(Math.cos(a))}, ${num(Math.sin(a))}, ${num(1 / length)}, ${num(speed / Math.sqrt(length))}, ${num(height)}`;+};+const SLOPES_GLSL = WAVE_SET.map((w, i) => i === 0+ ? ` vec3 sum = peakedWave(bend.xy, along, k, run, far, ${waveArgs(w)});\n float weightSum = ${num(w[2])};`+ : ` if (u_waveCount > ${i}.5) { sum += peakedWave(bend.xy, along, k, run, far, ${waveArgs(w)}); weightSum += ${num(w[2])}; }`).join('\n');+const SLOPES_WGSL = WAVE_SET.map((w, i) => i === 0+ ? ` var sum = peakedWave(bend.xy, along, k, run, far, ${waveArgs(w)});\n var weightSum = ${num(w[2])};`+ : ` if (mc.u_waveCount > ${i}.5) { sum = sum + peakedWave(bend.xy, along, k, run, far, ${waveArgs(w)}); weightSum = weightSum + ${num(w[2])}; }`).join('\n');// A horizontal body of water: waves that travel, the scene seen through it bent and tinted by how much water lies in front of it, the sky// and the lights reflected off it, and foam where it meets what it lies on and on the crests. It reads the picture of the opaque scene@@ -86,7 +104,7 @@ const WATER = `#pragma shader "Water"#pragma param u_causticSpeed float default(0.35) range(0,4) ui(slider)// What the quality level allows (the WaterZone writes these): how many of the four waves are summed, whether the surface seen from below mirrors the world under it,// and whether the sun's web of light is drawn on what lies under the water.-#pragma param u_waveCount float default(4) range(1,4) ui(slider)+#pragma param u_waveCount float default(${WAVE_SET_SIZE}) range(1,${WAVE_SET_SIZE}) ui(slider)#pragma param u_mirror float default(1) range(0,1) ui(slider)#pragma param u_causticOn float default(1) range(0,1) ui(slider)// The disturbance the water keeps (WaterZone ripples): a window of the xz plane, red the height of the ripples (0.5 at rest, u_rippleRange above or below at 1 and 0)@@ -119,7 +137,7 @@ const WATER = `#pragma shader "Water"#pragma vertexbounds 16#pragma vertexoffset-// The height of the waves at p: the same four peaked sines the fragment takes its slope from, so the surface that is lit is the one that is drawn.+// The height of the waves at p: the same peaked sines the fragment takes its slope from, so the surface that is lit is the one that is drawn.// Where the waves are read for the true place p, bent by the given span (waves.ts: waveBend): crests of straight sines a few directions apart// add up to long parallel lines, a sea scored with strokes that turn with the wind. xy to read at; zw dx/dz and dz/dx, for a slope. One// sine an axis: this runs for every pixel of the water, and with a term more a phone paid 11 ms a frame for it.@@ -130,10 +148,10 @@ vec4 waterBend(vec2 p, float span) {}float waterWaveHeight(vec2 p, float time, float cell) {vec2 at = waterBend(p, u_waveLength).xy;- const vec4 SET[4] = vec4[4](vec4(0.0, 1.0, 1.0, 1.0), vec4(28.0, 0.62, 0.55, 1.1), vec4(-37.0, 0.37, 0.3, 1.2), vec4(71.0, 0.21, 0.15, 1.35));+ ${WAVES_GLSL}float height = 0.0;float base = radians(u_waveDirection);- for (int i = 0; i < 4; ++i) {+ for (int i = 0; i < ${WAVE_SET_SIZE}; ++i) {if (float(i) >= u_waveCount) break;float length_ = u_waveLength * SET[i].y;float k = 6.2831853 / length_;@@ -234,10 +252,10 @@ fn waterBend(p : vec2f, span : f32) -> vec4f {}fn waterWaveHeight(p : vec2f, time : f32, cell : f32) -> f32 {let at = waterBend(p, mc.u_waveLength).xy;- var wave = array<vec4f, 4>(vec4f(0.0, 1.0, 1.0, 1.0), vec4f(28.0, 0.62, 0.55, 1.1), vec4f(-37.0, 0.37, 0.3, 1.2), vec4f(71.0, 0.21, 0.15, 1.35));+ ${WAVES_WGSL}var height = 0.0;let base = radians(mc.u_waveDirection);- for (var i : i32 = 0; i < 4; i = i + 1) {+ for (var i : i32 = 0; i < ${WAVE_SET_SIZE}; i = i + 1) {if (f32(i) >= mc.u_waveCount) { break; }let spec = wave[i];let span = mc.u_waveLength * spec.y;@@ -426,7 +444,7 @@ vec2 rainRings(vec2 p, float time, float rain) {}/// 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.-/// Four waves a few directions apart, each a peaked sine (exp(sin - 1)) whose crests are narrower than its troughs.+/// The set's waves, each a peaked sine (exp(sin - 1)) whose crests are narrower than its troughs.// One of them: xy its slope, without its height; z its crest.vec3 peakedWave(vec2 at, vec2 along, float k, float run, float far, float turnCos, float turnSin, float perLength, float perRun, float share) {vec2 d = vec2(along.x * turnCos + along.y * turnSin, along.y * turnCos - along.x * turnSin);@@ -442,12 +460,7 @@ vec2 waveSlope(vec2 p, float time, float dist, out float crest) {float k = 6.2831853 / u_waveLength;float run = sqrt(9.8 * k) * u_waveSpeed * time;float far = dist / (u_waveLength * 220.0);- // Headings 0, 28, -37 and 71 degrees off the wind; lengths 1, 0.62, 0.37 and 0.21 of the longest; heights 1, 0.55, 0.3 and 0.15 of it.- vec3 sum = peakedWave(bend.xy, along, k, run, far, 1.000000, 0.000000, 1.000000, 1.000000, 1.0);- float weightSum = 1.0;- if (u_waveCount > 1.5) { sum += peakedWave(bend.xy, along, k, run, far, 0.882948, 0.469472, 1.612903, 1.397001, 0.55); weightSum += 0.55; }- if (u_waveCount > 2.5) { sum += peakedWave(bend.xy, along, k, run, far, 0.798636, -0.601815, 2.702703, 1.972788, 0.3); weightSum += 0.3; }- if (u_waveCount > 3.5) { sum += peakedWave(bend.xy, along, k, run, far, 0.325568, 0.945519, 4.761905, 2.945942, 0.15); weightSum += 0.15; }+${SLOPES_GLSL}vec2 slope = sum.xy * u_waveHeight;crest = sum.z / weightSum;return vec2(slope.x + slope.y * bend.w, slope.y + slope.x * bend.z);@@ -957,11 +970,7 @@ fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {let k = 6.2831853 / mc.u_waveLength;let run = sqrt(9.8 * k) * mc.u_waveSpeed * time;let far = dist / (mc.u_waveLength * 220.0);- var sum = peakedWave(bend.xy, along, k, run, far, 1.000000, 0.000000, 1.000000, 1.000000, 1.0);- var weightSum = 1.0;- if (mc.u_waveCount > 1.5) { sum = sum + peakedWave(bend.xy, along, k, run, far, 0.882948, 0.469472, 1.612903, 1.397001, 0.55); weightSum = weightSum + 0.55; }- if (mc.u_waveCount > 2.5) { sum = sum + peakedWave(bend.xy, along, k, run, far, 0.798636, -0.601815, 2.702703, 1.972788, 0.3); weightSum = weightSum + 0.3; }- if (mc.u_waveCount > 3.5) { sum = sum + peakedWave(bend.xy, along, k, run, far, 0.325568, 0.945519, 4.761905, 2.945942, 0.15); weightSum = weightSum + 0.15; }+${SLOPES_WGSL}let slope = sum.xy * mc.u_waveHeight;var out : Waves;out.slope = vec2f(slope.x + slope.y * bend.w, slope.y + slope.x * bend.z);diff --git a/sdk/src/water/waves.ts b/sdk/src/water/waves.tsindex 3f3da3d38..0d82ecef8 100644--- a/sdk/src/water/waves.ts+++ b/sdk/src/water/waves.ts@@ -4,10 +4,10 @@* @file waves.ts* @brief The height of the water, in one formula the CPU and the Water shader share.*- * @details Four peaked sines (`exp(sin(theta) - 1)`: a crest narrower than its trough) a few directions apart, each with its own length,- * weight and speed taken from four numbers. The shader's `waterWaveHeight` and `waveSlope` are the same arithmetic written in- * GLSL and WGSL, so what a floating object reads here is what is drawn there. Change a constant in one place and the other- * two places have to change with it; the table below is the one the shaders repeat.+ * @details A set of peaked sines (`exp(sin(theta) - 1)`: a crest narrower than its trough) spread about the wind, each with its own length,+ * height and speed. The shader's `waterWaveHeight` and `waveSlope` are the same arithmetic in GLSL and WGSL, written out FROM the+ * table below when the shader's source is assembled (waterShader.ts), so what a floating object reads here is what is drawn there+ * and there is one place to change a wave.** Each wave is taken at a place bent off the true one (`waveBend`). Straight sines a few directions apart add up to crests* that are long parallel lines, which is how a sea of them looked from above: scored with diagonal strokes, turning with the@@ -16,17 +16,38 @@* Everything here is in the body's own space: x and z along its surface, the height along its up.*/+/** How many waves a sea is the sum of at most. */+export const WAVE_SET_SIZE = 8;+/** How far to either side of the wind the waves head, in degrees. */+const SPREAD = 65;+/** Each wave's length as a share of the one before it. */+const SHORTER = 0.78;+/** What the heights of the whole set add up to, as a share of the body's height: the most a crest can stand above the rest plane. */+export const WAVE_SET_HEIGHT = 2;++/**+ * The set a sea is summed from, longest first: the first heads with the wind, each after it is shorter by the same share, lower as nearly as+ * much (a wind sea's waves are about as steep at every length) and off the wind by a golden-ratio step, so no two headings are near and no+ * two lengths share a multiple. Every wave travels at the speed its length gives deep water.+ */+function buildWaveSet(): readonly (readonly [number, number, number, number])[] {+ const raw: [number, number, number, number][] = [];+ for (let i = 0; i < WAVE_SET_SIZE; i++) {+ const length = SHORTER ** i;+ const turn = i * 0.6180339887;+ raw.push([i === 0 ? 0 : SPREAD * ((turn - Math.floor(turn)) * 2 - 1), length, length ** 0.9, 1]);+ }+ const total = raw.reduce((sum, w) => sum + w[2], 0);+ const round = (v: number, digits: number): number => Number(v.toFixed(digits));+ return raw.map(([heading, length, height, speed]) => [round(heading, 1), round(length, 4), round(height * WAVE_SET_HEIGHT / total, 4), speed] as const);+}+/** Each wave of the set: its heading off the base direction (degrees), its length and its height as shares of the body's, and its speed share. */-export const WAVE_SET: readonly (readonly [number, number, number, number])[] = [- [0, 1, 1, 1],- [28, 0.62, 0.55, 1.1],- [-37, 0.37, 0.3, 1.2],- [71, 0.21, 0.15, 1.35],-];+export const WAVE_SET: readonly (readonly [number, number, number, number])[] = buildWaveSet();/** What shapes the waves: a WaterZone's and its bodies' heights, and the parameters of the Water material they are written to. */export interface WaveParams {- /** Height of the tallest wave, in world units. */+ /** Half of the most a crest stands above the rest plane (the set's heights add up to twice this), in world units. */height: number;/** Length of the longest wave. */length: number;@@ -34,7 +55,7 @@ export interface WaveParams {speed: number;/** The base heading, in degrees. */direction: number;- /** How many of the set's waves are summed, 1 to 4 (the quality level's); all of them when absent. */+ /** How many of the set's waves are summed, longest first (the quality level's); all of them when absent. */count?: number;}diff --git a/sdk/tests/water-quality.test.ts b/sdk/tests/water-quality.test.tsindex 8ab15a1dd..778405712 100644--- a/sdk/tests/water-quality.test.ts+++ b/sdk/tests/water-quality.test.ts@@ -1,20 +1,35 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { describe, expect, it } from 'vitest';-import { waveBend, waveHeight, waveSlope, waveCount, type WaveParams } from '../src/water/waves';+import { WAVE_SET, WAVE_SET_HEIGHT, WAVE_SET_SIZE, waveBend, waveHeight, waveSlope, waveCount, type WaveParams } from '../src/water/waves';import { FULL_WATER, waterQualityOf } from '../src/water/waterPlugin';-import { defaultQualityProfile, resolveQualityProfile, parseQualityConfig } from '../src/render/quality';+import { defaultQualityProfile, resolveQualityProfile, parseQualityConfig, MOST_WATER_WAVES } from '../src/render/quality';import { applyUnderwaterToEffects, type UnderwaterState } from '../src/postprocess/underwater';import type { BlendedEffect } from '../src/postprocess/volumeBlending';const params: WaveParams = { height: 1, length: 20, speed: 1, direction: 30 };+describe('the set of waves', () => {+ it('is longest first with the wind, each after it shorter, lower and at a heading of its own, and adds up to the height it says', () => {+ expect(WAVE_SET).toHaveLength(WAVE_SET_SIZE);+ expect(WAVE_SET[0]![0]).toBe(0);+ expect(WAVE_SET[0]![1]).toBe(1);+ for (let i = 1; i < WAVE_SET.length; i++) {+ expect(WAVE_SET[i]![1]).toBeLessThan(WAVE_SET[i - 1]![1]);+ expect(WAVE_SET[i]![2]).toBeLessThan(WAVE_SET[i - 1]![2]);+ }+ const headings = WAVE_SET.map((w) => w[0]).sort((a, b) => a - b);+ for (let i = 1; i < headings.length; i++) expect(headings[i]! - headings[i - 1]!).toBeGreaterThan(3);+ expect(WAVE_SET.reduce((sum, w) => sum + w[2], 0)).toBeCloseTo(WAVE_SET_HEIGHT, 2);+ });+});+describe('the wave count', () => {- it('is the whole set when absent, and is held to 1 to 4', () => {- expect(waveCount(params)).toBe(4);+ it('is the whole set when absent, and is held to the set', () => {+ expect(waveCount(params)).toBe(WAVE_SET_SIZE);expect(waveCount({ ...params, count: 2 })).toBe(2);expect(waveCount({ ...params, count: 0 })).toBe(1);- expect(waveCount({ ...params, count: 9 })).toBe(4);+ expect(waveCount({ ...params, count: 99 })).toBe(WAVE_SET_SIZE);});it('sums fewer waves for a lower count, and one wave is the longest alone', () => {@@ -22,17 +37,17 @@ describe('the wave count', () => {const all = waveHeight(params, x, z, t), two = waveHeight({ ...params, count: 2 }, x, z, t), one = waveHeight({ ...params, count: 1 }, x, z, t);expect(one).not.toBeCloseTo(all, 6);expect(two).not.toBeCloseTo(all, 6);- expect(waveHeight({ ...params, count: 4 }, x, z, t)).toBe(all);+ expect(waveHeight({ ...params, count: WAVE_SET_SIZE }, x, z, t)).toBe(all);// The one wave is the set's first, at its own length and height.const k = 2 * Math.PI / 20, a = 30 * Math.PI / 180;const [bx, bz] = waveBend(x, z, 20);const theta = k * (Math.sin(a) * bx + Math.cos(a) * bz) - Math.sqrt(9.8 * k) * t;- expect(one).toBeCloseTo(Math.exp(Math.sin(theta) - 1), 9);+ expect(one).toBeCloseTo(WAVE_SET[0]![2] * Math.exp(Math.sin(theta) - 1), 9);});it('takes the slope from the same waves the height has', () => {const x = 1, z = 2, t = 0.4, h = 1e-4;- for (const count of [1, 2, 3, 4]) {+ for (const count of [1, 2, 5, WAVE_SET_SIZE]) {const p = { ...params, count };const [sx, sz] = waveSlope(p, x, z, t);const dx = (waveHeight(p, x + h, z, t) - waveHeight(p, x - h, z, t)) / (2 * h);@@ -50,13 +65,13 @@ describe('what a quality level allows water', () => {it('is the low profile on a minigame with no policy: flat, no mirror, no web of light', () => {const q = waterQualityOf(null, true);- expect(q).toEqual({ waves: 2, rippleCells: 32, displacement: false, mirror: false, caustics: false });+ expect(q).toEqual({ waves: 3, rippleCells: 32, displacement: false, mirror: false, caustics: false });});it('follows the profile of the level a project is at, so a project can change what a level means', () => {- expect(waterQualityOf(defaultQualityProfile('high'), false)).toEqual({ waves: 4, rippleCells: 128, displacement: true, mirror: true, caustics: true });- const own = resolveQualityProfile('low', { waterMirror: true, waterDisplacement: true, waterWaves: 3 });- expect(waterQualityOf(own, true)).toMatchObject({ waves: 3, displacement: true, mirror: true, caustics: false });+ expect(waterQualityOf(defaultQualityProfile('high'), false)).toEqual({ waves: WAVE_SET_SIZE, rippleCells: 128, displacement: true, mirror: true, caustics: true });+ const own = resolveQualityProfile('low', { waterMirror: true, waterDisplacement: true, waterWaves: 4 });+ expect(waterQualityOf(own, true)).toMatchObject({ waves: 4, displacement: true, mirror: true, caustics: false });// A profile wins over the minigame rule: the project said what it wants.expect(waterQualityOf(defaultQualityProfile('high'), true).displacement).toBe(true);});@@ -72,7 +87,8 @@ describe('what a quality level allows water', () => {it('is read and bounded from a project\'s quality block', () => {const q = parseQualityConfig({ mode: 'low', profiles: { low: { waterWaves: 99, waterRippleCells: -5, waterMirror: 'yes', waterCaustics: true } } });const low = q.profiles!.low!;- expect(low.waterWaves).toBe(4);+ expect(low.waterWaves).toBe(WAVE_SET_SIZE);+ expect(MOST_WATER_WAVES).toBe(WAVE_SET_SIZE);expect(low.waterRippleCells).toBe(0);expect(low.waterMirror).toBe(false);expect(low.waterCaustics).toBe(true);diff --git a/sdk/tests/water.test.ts b/sdk/tests/water.test.tsindex 9b9a911c9..7a366ea12 100644--- a/sdk/tests/water.test.ts+++ b/sdk/tests/water.test.ts@@ -32,7 +32,7 @@ function facing(p: Float32Array, a: number, b: number, c: number): number {}describe('the waves', () => {- it('is the sum of the set\'s four peaked sines', () => {+ it('is the sum of the set\'s peaked sines', () => {const t = 1.3;const [x, z] = waveBend(3.7, -2.2, params.length);let expected = 0;@@ -80,7 +80,7 @@ describe('the waves', () => {WAVE_SET.forEach(([heading, lengthShare, heightShare, speedShare]) => {const radians = heading * Math.PI / 180;const numbers = [Math.cos(radians), Math.sin(radians), 1 / lengthShare, speedShare / Math.sqrt(lengthShare)].map((n) => n.toFixed(6));- const call = `run, far, ${numbers.join(', ')}, ${Number.isInteger(heightShare) ? heightShare.toFixed(1) : heightShare})`;+ const call = `run, far, ${numbers.join(', ')}, ${heightShare.toFixed(6)})`;expect(source.split(call).length - 1, call).toBe(2);});});