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
perf(water): a sea on a phone costs half of what it did, 45 ms to 21.5, with the same picture
yhh28c08b53a195
diff --git a/desktop b/desktopindex 41c9c58b4..37893949f 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 41c9c58b43c07d3fb2b8d0699bb6183a20596505+Subproject commit 37893949f3700b5810b310035d27677130f79cd3diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdxindex 0b7b5f74d..6ae526902 100644--- a/docs/astro/src/content/docs/graphics/materials.mdx+++ b/docs/astro/src/content/docs/graphics/materials.mdx@@ -172,6 +172,7 @@ One file holds every stage plus its metadata, separated by pragmas:| `#pragma param …` | A reflected material parameter (table below). || `#pragma switch NAME [default(on)]` | Material-facing static permutation toggle (a `#define`). || `#pragma feature NAME` | Engine-chosen compile-time variant keyword. |+| `#pragma lighting direct` | A `Lit` shader lit by the sixteen lights of the block and hard-edged shadows only. It compiles without the tiled lights past those sixteen, the 2D light masks, and soft and hair shadows, which every pixel pays for on a phone whether a scene uses them or not. The Water shader declares it. || `#pragma coverage PARAM` | While the float param `PARAM` is above zero, the shader's output alpha is coverage — a cutout's alpha sharpened to about a pixel around the cutoff (`cutoutCoverage(alpha, cutoff, fwidth(alpha))`). An opaque draw into a multisampled target then turns it into multisample coverage, so the cutout's edge is antialiased instead of stair-stepped; without multisampling it is the hard cut. The cut is at the cutoff at every distance, as glTF's MASK is: a cutout seen small keeps its area because the cook rescales its mips' alpha to the coverage the full image has at the cutoff. The built-in Model shader declares `u_alphaCutoff`. || `#pragma hairshadow PARAM` | While the float param `PARAM` is above zero, meshes drawn with the material are hair for shadows: the sun's cascades gain one fitted to them alone, and a shader that sets `g_hairShadow` before it lights reads the shadow as a density along the light instead of a hard compare. The value is the density. The built-in Hair shader declares `u_hairShadow`. || `#pragma gbuffer` | A `PostProcess` shader reads the scene's surface record (see [the G-buffer](/docs/graphics/post-processing/#the-g-buffer)) at `u_gbuffer`. Declaring it is what makes the frame draw one; a chain whose shaders do not never pays for it. |diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdxindex 4855193d3..bc2885437 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx@@ -142,6 +142,7 @@ Terrain、Foliage、Water、Hair、Skin、Eye 这几个模板属于各自的模| `#pragma switch NAME [default(on)]` | 材质可控的静态排列开关(一个 `#define`)。 || `#pragma coverage PARAM` | 浮点参数 `PARAM` 大于零时,着色器输出的 alpha 就是覆盖率——镂空的 alpha 在阈值附近锐化到约一个像素宽(`cutoutCoverage(alpha, cutoff, fwidth(alpha))`)。不透明物体画进多重采样目标时,它会转成多重采样覆盖率,镂空边缘就有抗锯齿而不是台阶;没有多重采样时就是硬切。任何距离都在阈值处切,与 glTF 的 MASK 定义一致:镂空缩小显示时之所以还保持原来的面积,是因为烘焙时把每级 mip 的 alpha 缩放到与原图在阈值处相同的覆盖率。内置 Model 着色器声明了 `u_alphaCutoff`。 || `#pragma feature NAME` | 引擎选择的编译期变体关键字。 |+| `#pragma lighting direct` | `Lit` 着色器只接受光源块里的十六盏灯和硬边阴影。编译时去掉十六盏之外的分块光源、2D 光遮罩、软阴影和头发阴影;这些分支无论场景用不用,手机上每个像素都要付出代价。Water 着色器声明了它。 || `#pragma hairshadow PARAM` | 浮点参数 `PARAM` 大于零时,用这个材质画的网格就是阴影意义上的头发:太阳的级联多出一个只拟合它们的级联,并且着色器在打光前设置 `g_hairShadow` 的话,阴影就按沿光线的密度读,而不是硬比较。参数值就是密度。内置 Hair 着色器声明了 `u_hairShadow`。 || `#pragma gbuffer` | `PostProcess` 着色器要读取场景的表面记录(见[G-buffer](/docs/zh-cn/graphics/post-processing/#g-buffer)),在 `u_gbuffer` 处。声明它才会让这一帧画出一份;着色器里没有它的链路永远不付这笔钱。 || `#pragma vertex` / `#pragma fragment` … `#pragma end` | Stage 代码体。**2D 域的顶点段可省略**——引擎注入规范顶点段。 |diff --git a/sdk/src/water/waterShader.ts b/sdk/src/water/waterShader.tsindex abec046d0..c77a36305 100644--- a/sdk/src/water/waterShader.ts+++ b/sdk/src/water/waterShader.ts@@ -17,6 +17,7 @@ import { CAUSTICS_GLSL, CAUSTICS_WGSL } from '../render/waterCaustics';const WATER = `#pragma shader "Water"#pragma version 300 es#pragma domain Lit+#pragma lighting direct// The colour the water scatters back: lighter where it is shallow, darker where it is deep.#pragma param u_shallowColor color default(0.10,0.42,0.46,1)#pragma param u_deepColor color default(0.01,0.08,0.15,1)@@ -385,20 +386,27 @@ float waterNoise(vec2 p) {/// The slope of the ripples the wind raises at p: six short waves within seventy-five degrees of it, from u_rippleLength down to a fifth of it, each/// running at the speed its length gives deep water and at a phase of its own, each as steep as u_rippleStrength a third. A sum of waves/// has no cells or blobs, which drifting noise has. A ripple shorter than a pixel would shimmer: each fades out with distance.+// One of them: turned by (turnCos, turnSin) off the wind, its frequency and its reach perLength times the longest's, its speed perRoot times.+vec2 rippleWave(vec2 p, vec2 along, float k, float run, float far, float turnCos, float turnSin, float perLength, float perRoot, float phase) {+ vec2 d = vec2(along.x * turnCos + along.y * turnSin, along.y * turnCos - along.x * turnSin);+ float theta = k * perLength * dot(d, p) - run * perRoot + phase;+ return d * (cos(theta) * clamp(1.0 - far * perLength, 0.0, 1.0) * 0.33);+}vec2 rippleSlope(vec2 p, float time, float dist) {- const vec3 SET[6] = vec3[6](vec3(-14.0, 1.0, 0.0), vec3(33.0, 0.71, 1.7), vec3(-58.0, 0.53, 3.1),- vec3(11.0, 0.39, 4.4), vec3(74.0, 0.29, 0.9), vec3(-41.0, 0.21, 2.6));+ // What every wave shares, once: the wind's heading, and the longest wave's frequency, how far it has run and how far off it is seen. The rest of each+ // wave is a number written down: a phone does not take these out of the loop for itself, and asked per pixel they were a quarter of what its water cost.float base = radians(u_waveDirection);+ vec2 along = vec2(sin(base), cos(base));+ float k = 6.2831853 / u_rippleLength;+ float run = sqrt(9.8 * k) * u_waveSpeed * time;+ float far = dist / (u_rippleLength * 150.0);vec2 slope = vec2(0.0);- for (int i = 0; i < 6; ++i) {- float len = u_rippleLength * SET[i].y;- float k = 6.2831853 / len;- float a = base + radians(SET[i].x);- vec2 d = vec2(sin(a), cos(a));- float theta = k * dot(d, p) - sqrt(9.8 * k) * u_waveSpeed * time + SET[i].z;- float seen = clamp(1.0 - dist / (len * 150.0), 0.0, 1.0);- slope += d * (cos(theta) * seen * 0.33);- }+ slope += rippleWave(p, along, k, run, far, 0.970296, -0.241922, 1.000000, 1.000000, 0.0); // -14 degrees off the wind, 1 of the length+ slope += rippleWave(p, along, k, run, far, 0.838671, 0.544639, 1.408451, 1.186782, 1.7); // 33 degrees off the wind, 0.71 of the length+ slope += rippleWave(p, along, k, run, far, 0.529919, -0.848048, 1.886792, 1.373606, 3.1); // -58 degrees off the wind, 0.53 of the length+ slope += rippleWave(p, along, k, run, far, 0.981627, 0.190809, 2.564103, 1.601282, 4.4); // 11 degrees off the wind, 0.39 of the length+ slope += rippleWave(p, along, k, run, far, 0.275637, 0.961262, 3.448276, 1.856953, 0.9); // 74 degrees off the wind, 0.29 of the length+ slope += rippleWave(p, along, k, run, far, 0.754710, -0.656059, 4.761905, 2.182179, 2.6); // -41 degrees off the wind, 0.21 of the lengthreturn slope * u_rippleStrength;}@@ -431,31 +439,30 @@ 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.+// One of them, as rippleWave's: 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);+ float theta = k * perLength * dot(d, at) - run * perRun;+ float e = exp(sin(theta) - 1.0);+ // A wave much shorter than a pixel is noise, not a wave: it fades out with distance.+ return vec3(d * (share * e * cos(theta) * k * perLength * clamp(1.0 - far * perLength, 0.0, 1.0)), e * share);+}vec2 waveSlope(vec2 p, float time, float dist, out float crest) {- 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));- vec2 slope = vec2(0.0);- float crestSum = 0.0;- float weightSum = 0.0;float base = radians(u_waveDirection);+ vec2 along = vec2(sin(base), cos(base));vec4 bend = waterBend(p, u_waveLength);- for (int i = 0; i < 4; ++i) {- if (float(i) >= u_waveCount) break;- float length_ = u_waveLength * SET[i].y;- float k = 6.2831853 / length_;- float a = base + radians(SET[i].x);- vec2 d = vec2(sin(a), cos(a));- float omega = sqrt(9.8 * k) * u_waveSpeed * SET[i].w;- float theta = k * dot(d, bend.xy) - omega * time;- float e = exp(sin(theta) - 1.0);- // A wave much shorter than a pixel is noise, not a wave: it fades out with distance.- float seen = clamp(1.0 - dist / (length_ * 220.0), 0.0, 1.0);- slope += d * (u_waveHeight * SET[i].z * e * cos(theta) * k * seen);- crestSum += e * SET[i].z;- weightSum += SET[i].z;- }- slope = vec2(slope.x + slope.y * bend.w, slope.y + slope.x * bend.z);- crest = crestSum / weightSum;- return slope;+ 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; }+ vec2 slope = sum.xy * u_waveHeight;+ crest = sum.z / weightSum;+ return vec2(slope.x + slope.y * bend.w, slope.y + slope.x * bend.z);}${CAUSTICS_GLSL}@@ -622,12 +629,18 @@ void main() {// The surface: the long waves, then the ripples they carry, flattened with distance so the far water is calm rather than aliased.vec2 wp = u_waveSpace > 0.5 ? v_texCoord + u_origin : P.xz;- // The zone's water at this pixel (texture reads, taken before any branch): how far in from the shore, how deep, how high the waves, the current.+ // The zone's water at this pixel: how far in from the shore, how deep, how high the waves, the current. The open sea past the region has it all in+ // uniforms, and every read below is one a pixel there does not pay for (these maps have no mips, so a read at level 0 may sit in a branch).vec2 zoneUv = (wp - u_zoneOrigin) / max(u_zoneSize, vec2(1e-4));- vec4 zoneTex = texture(u_zoneField, clamp(zoneUv, vec2(0.0), vec2(1.0)));- vec4 zone = waterZoneAt(wp);bool zoneIn = all(greaterThanEqual(zoneUv, vec2(0.0))) && all(lessThanEqual(zoneUv, vec2(1.0)));bool zoneOn = u_zoneOn > 0.5 && u_waveSpace > 0.5;+ bool zoneRead = zoneOn && (zoneIn || u_oceanOn < 0.5);+ vec4 zoneTex = vec4(0.5, 0.5, 0.5, 1.0);+ vec4 zone = vec4(u_oceanLevel, 1e6, u_oceanWaves, 1.0);+ if (zoneRead) {+ zoneTex = textureLod(u_zoneField, clamp(zoneUv, vec2(0.0), vec2(1.0)), 0.0);+ zone = waterZoneAt(wp);+ }float shoreE = (zoneTex.r - 0.5) * 2.0;float shoreDist = !zoneOn ? 1e6 : zoneIn ? shoreE * abs(shoreE) * u_zoneRange.x : u_oceanOn > 0.5 ? 1e6 : -1.0;float shoreDepth = zoneOn ? zone.y : 1e6;@@ -636,33 +649,43 @@ 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 = zoneOn ? waterZoneStill(wp) : 1.0;+ float still = zoneRead ? 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);- 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(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 toSea = vec2(0.0);+ vec2 surf = vec2(0.0);+ float surfRise = 0.0;+ // The surf's reach (waterSurf), a step wider for the two reads of its rise: further from the shore it is nothing, and takes no reads to say so.+ float surfReach = u_surfLength * 4.0;+ if (zoneRead && surfH > 0.0 && u_surfLength > 0.0 && shoreDist <= surfReach + surfStep && shoreDist >= -surfReach * 0.05 - surfStep) {+ float surfDist = waterZoneSurf(wp);+ 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));+ surf = waterSurf(surfDist, shoreDist, surfH, time);+ 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.vec2 ripUv = (wp - u_rippleOrigin) / max(u_rippleSize, 1e-4);- vec4 ripC = texture(u_rippleMap, ripUv);- vec2 ripStep = vec2(u_rippleTexel);- float ripCell = max(u_rippleSize * u_rippleTexel, 1e-5);- float ripL = texture(u_rippleMap, ripUv - vec2(ripStep.x, 0.0)).r, ripR = texture(u_rippleMap, ripUv + vec2(ripStep.x, 0.0)).r;- float ripD = texture(u_rippleMap, ripUv - vec2(0.0, ripStep.y)).r, ripU = texture(u_rippleMap, ripUv + vec2(0.0, ripStep.y)).r;bool ripIn = u_rippleOn > 0.5 && u_waveSpace > 0.5 && all(greaterThanEqual(ripUv, vec2(0.0))) && all(lessThanEqual(ripUv, vec2(1.0)));- // The window follows the camera: its edge fades out, so where it ends the ripples thin away instead of stopping on a line.- vec2 ripEdge = min(ripUv, 1.0 - ripUv);- float ripFade = smoothstep(0.0, 0.15, min(ripEdge.x, ripEdge.y));- vec2 ripSlope = ripIn ? vec2(ripR - ripL, ripU - ripD) * u_rippleRange / ripCell * ripFade : vec2(0.0);- float ripFoam = ripIn ? ripC.g * ripFade : 0.0;- // How much foam the foam texture holds here (1 where none was given), read with the ripples, before any branch.- float foamCover = texture(u_foamMap, (wp + u_foamFlow * time) / max(u_foamTile, 1e-4)).r;+ vec2 ripSlope = vec2(0.0);+ float ripFoam = 0.0;+ if (ripIn) {+ float ripCell = max(u_rippleSize * u_rippleTexel, 1e-5);+ float ripL = textureLod(u_rippleMap, ripUv - vec2(u_rippleTexel, 0.0), 0.0).r, ripR = textureLod(u_rippleMap, ripUv + vec2(u_rippleTexel, 0.0), 0.0).r;+ float ripD = textureLod(u_rippleMap, ripUv - vec2(0.0, u_rippleTexel), 0.0).r, ripU = textureLod(u_rippleMap, ripUv + vec2(0.0, u_rippleTexel), 0.0).r;+ // The window follows the camera: its edge fades out, so where it ends the ripples thin away instead of stopping on a line.+ vec2 ripEdge = min(ripUv, 1.0 - ripUv);+ float ripFade = smoothstep(0.0, 0.15, min(ripEdge.x, ripEdge.y));+ ripSlope = vec2(ripR - ripL, ripU - ripD) * u_rippleRange / ripCell * ripFade;+ ripFoam = textureLod(u_rippleMap, ripUv, 0.0).g * ripFade;+ }+ // Where the foam texture is read, and how fast that moves across the screen: taken here because the read itself waits until there is foam.+ vec2 foamUv = (wp + u_foamFlow * time) / max(u_foamTile, 1e-4);+ vec2 foamDx = dFdx(foamUv), foamDy = dFdy(foamUv);float crest;vec2 slope;if (dot(flow, flow) > 1e-6) {@@ -741,10 +764,15 @@ void main() {if (sunDir.w > 0.5 && cosUp > 0.05) {vec3 seabed = P + bentWave * column;float depthBelow = max(dot(P - seabed, Ngeo), 0.0);- vec3 onSurface = seabed + sunDir.xyz * (depthBelow / max(cosUp, 0.15));- float c = causticPattern(onSurface.xz / u_causticScale, time * u_causticSpeed);float reachSun = exp(-dot(u_absorption.rgb, vec3(1.0 / 3.0)) * u_density * depthBelow / max(cosUp, 0.15));- behind *= 1.0 + u_causticStrength * c * cosUp * waterSunVisibility(seabed, sunTiles.x, sunTiles.y) * reachSun * min(sunColor.a, 2.0) * 0.5;+ // The most the web can add here. Where the sun never gets that far down (the whole of a deep sea) that is under a step of an+ // 8-bit colour, and the pattern, a sixth of what a pixel of open water costs, is not worked out for it.+ float causticMost = u_causticStrength * cosUp * reachSun * min(sunColor.a, 2.0) * 0.5;+ if (causticMost > 0.004) {+ vec3 onSurface = seabed + sunDir.xyz * (depthBelow / max(cosUp, 0.15));+ float c = causticPattern(onSurface.xz / u_causticScale, time * u_causticSpeed);+ behind *= 1.0 + causticMost * c * waterSunVisibility(seabed, sunTiles.x, sunTiles.y);+ }}}}@@ -758,28 +786,40 @@ void main() {// Foam: along the shore, where the water is shallow, broken by noise that moves; and on the crests of the waves.float vertical = column * max(abs(viewDir.y), 0.15);- float foamScale = 1.0 / (u_rippleLength * 1.2);- float breakup = waterNoise(wp * foamScale + vec2(time * 0.07, time * 0.05)) * 0.6 + waterNoise(wp * foamScale * 3.0 - vec2(time * 0.13, 0.0)) * 0.4;- float pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);- float shore = haveDepth && u_foamWidth > 0.0 ? clamp((1.0 - vertical / (u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0) : 0.0;- // The baked shore foams too, where the depth buffer cannot say (no chain, no float targets) and along the outline the zone traced.- if (zoneOn && u_foamWidth > 0.0) {- // With the picture's depth the shallows foam by it, pixel by pixel; the baked depth then adds only the traced outline, not its texels.- float baked = haveDepth ? shoreDist : min(shoreDist, shoreDepth);- shore = max(shore, clamp((1.0 - baked / (u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0));- // How the shore takes its waves: against rock or a cliff they burst white; up a gentle beach they wash in a thin line only; and the- // less room the wind has to raise them (a sheltered lake), the less of either.- float pound = waterZoneSteep(wp);- float swash = 1.0 - smoothstep(0.0, surfStep * 1.5, shoreDist);- shore *= mix(swash * 0.6, 1.0, pound) * mix(0.3, 1.0, zone.w);+ float baked = haveDepth ? shoreDist : min(shoreDist, shoreDepth);+ // Most of a sea has none of the foam below, and the noise that breaks it up need not be worked out to find that: the shore's asks for less water than+ // its width (pulse is 1 at most), a crest's for a crest past the line.+ float surfFoam = 0.0;+ float foam = 0.0;+ float crestLine = 1.0 - 0.3 * u_foamCrest;+ if ((u_foamWidth > 0.0 && ((haveDepth && vertical < u_foamWidth) || (zoneOn && baked < u_foamWidth))) || (u_foamCrest > 0.0 && crest > crestLine) || ripFoam > 0.0 || surf.y > 0.0) {+ float foamScale = 1.0 / (u_rippleLength * 1.2);+ float breakup = waterNoise(wp * foamScale + vec2(time * 0.07, time * 0.05)) * 0.6 + waterNoise(wp * foamScale * 3.0 - vec2(time * 0.13, 0.0)) * 0.4;+ float pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);+ float shore = haveDepth && u_foamWidth > 0.0 ? clamp((1.0 - vertical / (u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0) : 0.0;+ // The baked shore foams too, where the depth buffer cannot say (no chain, no float targets) and along the outline the zone traced.+ if (zoneOn && u_foamWidth > 0.0) {+ // With the picture's depth the shallows foam by it, pixel by pixel; the baked depth then adds only the traced outline, not its texels.+ shore = max(shore, clamp((1.0 - baked / (u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0));+ if (shore > 0.0) {+ // How the shore takes its waves: against rock or a cliff they burst white; up a gentle beach they wash in a thin line only; and the+ // less room the wind has to raise them (a sheltered lake), the less of either.+ float pound = waterZoneSteep(wp);+ float swash = 1.0 - smoothstep(0.0, surfStep * 1.5, shoreDist);+ shore *= mix(swash * 0.6, 1.0, pound) * mix(0.3, 1.0, zone.w);+ }+ }+ float onCrest = u_foamCrest > 0.0 ? smoothstep(crestLine, 1.0, crest) * smoothstep(0.35, 0.75, breakup) : 0.0;+ // A breaker whitens as much on a beach as the waves are big, but bursts whitest on rock.+ if (surf.y > 0.0) surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4) * mix(0.2, 1.0, zoneOn ? waterZoneSteep(wp) : 1.0);+ foam = clamp(max(max(max(shore, onCrest * u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 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;- // A breaker whitens as much on a beach as the waves are big, but bursts whitest on rock.- float surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4) * mix(0.2, 1.0, zoneOn ? waterZoneSteep(wp) : 1.0);- float foam = clamp(max(max(max(shore, onCrest * u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 0.0, 1.0);// The texture as coverage: a texel holding c of foam shows where the foam asked for is more than 1 - c, rising to full over the rest,- // so thin foam keeps only the texture's densest marks and thick foam fills it. c = 1 leaves the foam as it was.- foam = clamp((foam - (1.0 - foamCover)) / max(foamCover, 1e-3), 0.0, 1.0);+ // so thin foam keeps only the texture's densest marks and thick foam fills it. c = 1 leaves the foam as it was, and no foam stays none whatever c is.+ if (foam > 0.0) {+ float foamCover = textureGrad(u_foamMap, foamUv, foamDx, foamDy).r;+ foam = clamp((foam - (1.0 - foamCover)) / max(foamCover, 1e-3), 0.0, 1.0);+ }// Foam floats on top: from under the water it is a thin shadow on the light, not a white sheet.if (below) foam *= 0.2;@@ -863,21 +903,24 @@ fn waterNoise(p : vec2f) -> f32 {return mix(mix(waterHash(i), waterHash(i + vec2f(1.0, 0.0)), f.x),mix(waterHash(i + vec2f(0.0, 1.0)), waterHash(i + vec2f(1.0, 1.0)), f.x), f.y);}+fn rippleWave(p : vec2f, along : vec2f, k : f32, run : f32, far : f32, turnCos : f32, turnSin : f32, perLength : f32, perRoot : f32, phase : f32) -> vec2f {+ let d = vec2f(along.x * turnCos + along.y * turnSin, along.y * turnCos - along.x * turnSin);+ let theta = k * perLength * dot(d, p) - run * perRoot + phase;+ return d * (cos(theta) * clamp(1.0 - far * perLength, 0.0, 1.0) * 0.33);+}fn rippleSlope(p : vec2f, time : f32, dist : f32) -> vec2f {- let SET = array<vec3f, 6>(vec3f(-14.0, 1.0, 0.0), vec3f(33.0, 0.71, 1.7), vec3f(-58.0, 0.53, 3.1),- vec3f(11.0, 0.39, 4.4), vec3f(74.0, 0.29, 0.9), vec3f(-41.0, 0.21, 2.6));let base = radians(mc.u_waveDirection);+ let along = vec2f(sin(base), cos(base));+ let k = 6.2831853 / mc.u_rippleLength;+ let run = sqrt(9.8 * k) * mc.u_waveSpeed * time;+ let far = dist / (mc.u_rippleLength * 150.0);var slope = vec2f(0.0);- for (var i = 0; i < 6; i++) {- let w = SET[i];- let len = mc.u_rippleLength * w.y;- let k = 6.2831853 / len;- let a = base + radians(w.x);- let d = vec2f(sin(a), cos(a));- let theta = k * dot(d, p) - sqrt(9.8 * k) * mc.u_waveSpeed * time + w.z;- let seen = clamp(1.0 - dist / (len * 150.0), 0.0, 1.0);- slope = slope + d * (cos(theta) * seen * 0.33);- }+ slope = slope + rippleWave(p, along, k, run, far, 0.970296, -0.241922, 1.000000, 1.000000, 0.0);+ slope = slope + rippleWave(p, along, k, run, far, 0.838671, 0.544639, 1.408451, 1.186782, 1.7);+ slope = slope + rippleWave(p, along, k, run, far, 0.529919, -0.848048, 1.886792, 1.373606, 3.1);+ slope = slope + rippleWave(p, along, k, run, far, 0.981627, 0.190809, 2.564103, 1.601282, 4.4);+ slope = slope + rippleWave(p, along, k, run, far, 0.275637, 0.961262, 3.448276, 1.856953, 0.9);+ slope = slope + rippleWave(p, along, k, run, far, 0.754710, -0.656059, 4.761905, 2.182179, 2.6);return slope * mc.u_rippleStrength;}@@ -908,31 +951,28 @@ fn rainRings(p : vec2f, time : f32, rain : f32) -> vec2f {struct Waves { slope : vec2f, crest : f32 };+fn peakedWave(at : vec2f, along : vec2f, k : f32, run : f32, far : f32, turnCos : f32, turnSin : f32, perLength : f32, perRun : f32, share : f32) -> vec3f {+ let d = vec2f(along.x * turnCos + along.y * turnSin, along.y * turnCos - along.x * turnSin);+ let theta = k * perLength * dot(d, at) - run * perRun;+ let e = exp(sin(theta) - 1.0);+ return vec3f(d * (share * e * cos(theta) * k * perLength * clamp(1.0 - far * perLength, 0.0, 1.0)), e * share);+}fn waveSlope(p : vec2f, time : f32, dist : f32) -> Waves {- 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));- var slope = vec2f(0.0);- var crestSum = 0.0;- var weightSum = 0.0;let base = radians(mc.u_waveDirection);+ let along = vec2f(sin(base), cos(base));let bend = waterBend(p, mc.u_waveLength);- for (var i : i32 = 0; i < 4; i = i + 1) {- if (f32(i) >= mc.u_waveCount) { break; }- let spec = wave[i];- let span = mc.u_waveLength * spec.y;- let k = 6.2831853 / span;- let a = base + radians(spec.x);- let d = vec2f(sin(a), cos(a));- let omega = sqrt(9.8 * k) * mc.u_waveSpeed * spec.w;- let theta = k * dot(d, bend.xy) - omega * time;- let e = exp(sin(theta) - 1.0);- let seen = clamp(1.0 - dist / (span * 220.0), 0.0, 1.0);- slope = slope + d * (mc.u_waveHeight * spec.z * e * cos(theta) * k * seen);- crestSum = crestSum + e * spec.z;- weightSum = weightSum + spec.z;- }+ 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; }+ 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);- out.crest = crestSum / weightSum;+ out.crest = sum.z / weightSum;return out;}@@ -1108,10 +1148,16 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vecvar wp = P.xz;if (mc.u_waveSpace > 0.5) { wp = v.v_texCoord + mc.u_origin; }let zoneUv = (wp - mc.u_zoneOrigin) / max(mc.u_zoneSize, vec2f(1e-4));- let zoneTex = textureSample(u_zoneField, u_zoneField_s, clamp(zoneUv, vec2f(0.0), vec2f(1.0)));- let zone = waterZoneAt(wp);let zoneIn = all(zoneUv >= vec2f(0.0)) && all(zoneUv <= vec2f(1.0));let zoneOn = mc.u_zoneOn > 0.5 && mc.u_waveSpace > 0.5;+ // The open sea past the region has it all in uniforms: see the GLSL.+ let zoneRead = zoneOn && (zoneIn || mc.u_oceanOn < 0.5);+ var zoneTex = vec4f(0.5, 0.5, 0.5, 1.0);+ var zone = vec4f(mc.u_oceanLevel, 1e6, mc.u_oceanWaves, 1.0);+ if (zoneRead) {+ zoneTex = textureSampleLevel(u_zoneField, u_zoneField_s, clamp(zoneUv, vec2f(0.0), vec2f(1.0)), 0.0);+ zone = waterZoneAt(wp);+ }var shoreDist = 1e6;var shoreDepth = 1e6;var damp = 1.0;@@ -1124,34 +1170,44 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vecdamp = zone.z * calm;}var still = 1.0;- if (zoneOn) { still = waterZoneStill(wp); }+ if (zoneRead) { 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);- 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(surfDist, shoreDist, surfH, time);- let surfRise = (waterSurf(surfDist + surfStep * 0.5, shoreDist + surfStep * 0.5, surfH, time).x+ var toSea = vec2f(0.0);+ var surf = vec2f(0.0);+ var surfRise = 0.0;+ // The surf's reach (waterSurf), a step wider for the two reads of its rise: further from the shore it is nothing, and takes no reads to say so.+ let surfReach = mc.u_surfLength * 4.0;+ if (zoneRead && surfH > 0.0 && mc.u_surfLength > 0.0 && shoreDist <= surfReach + surfStep && shoreDist >= -surfReach * 0.05 - surfStep) {+ let 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);+ toSea = toSeaRaw * smoothstep(0.55, 0.9, length(toSeaRaw));+ surf = waterSurf(surfDist, shoreDist, surfH, time);+ 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).+ }+ // The ripples at this pixel: their height on four sides gives the slope they add, and the foam is what they left.let ripUv = (wp - mc.u_rippleOrigin) / max(mc.u_rippleSize, 1e-4);- let ripC = textureSample(u_rippleMap, u_rippleMap_s, ripUv);- let ripCell = max(mc.u_rippleSize * mc.u_rippleTexel, 1e-5);- let ripL = textureSample(u_rippleMap, u_rippleMap_s, ripUv - vec2f(mc.u_rippleTexel, 0.0)).r;- let ripR = textureSample(u_rippleMap, u_rippleMap_s, ripUv + vec2f(mc.u_rippleTexel, 0.0)).r;- let ripD = textureSample(u_rippleMap, u_rippleMap_s, ripUv - vec2f(0.0, mc.u_rippleTexel)).r;- let ripU = textureSample(u_rippleMap, u_rippleMap_s, ripUv + vec2f(0.0, mc.u_rippleTexel)).r;let ripIn = mc.u_rippleOn > 0.5 && mc.u_waveSpace > 0.5 && all(ripUv >= vec2f(0.0)) && all(ripUv <= vec2f(1.0));var ripSlope = vec2f(0.0);var ripFoam = 0.0;- let ripEdge = min(ripUv, vec2f(1.0) - ripUv);- let ripFade = smoothstep(0.0, 0.15, min(ripEdge.x, ripEdge.y));- if (ripIn) { ripSlope = vec2f(ripR - ripL, ripU - ripD) * mc.u_rippleRange / ripCell * ripFade; ripFoam = ripC.g * ripFade; }- // How much foam the foam texture holds here (1 where none was given), read in uniform control flow with the ripples.- let foamCover = textureSample(u_foamMap, u_foamMap_s, (wp + mc.u_foamFlow * time) / max(mc.u_foamTile, 1e-4)).r;+ if (ripIn) {+ let ripCell = max(mc.u_rippleSize * mc.u_rippleTexel, 1e-5);+ let ripL = textureSampleLevel(u_rippleMap, u_rippleMap_s, ripUv - vec2f(mc.u_rippleTexel, 0.0), 0.0).r;+ let ripR = textureSampleLevel(u_rippleMap, u_rippleMap_s, ripUv + vec2f(mc.u_rippleTexel, 0.0), 0.0).r;+ let ripD = textureSampleLevel(u_rippleMap, u_rippleMap_s, ripUv - vec2f(0.0, mc.u_rippleTexel), 0.0).r;+ let ripU = textureSampleLevel(u_rippleMap, u_rippleMap_s, ripUv + vec2f(0.0, mc.u_rippleTexel), 0.0).r;+ let ripEdge = min(ripUv, vec2f(1.0) - ripUv);+ let ripFade = smoothstep(0.0, 0.15, min(ripEdge.x, ripEdge.y));+ ripSlope = vec2f(ripR - ripL, ripU - ripD) * mc.u_rippleRange / ripCell * ripFade;+ ripFoam = textureSampleLevel(u_rippleMap, u_rippleMap_s, ripUv, 0.0).g * ripFade;+ }+ // Where the foam texture is read, and how fast that moves across the screen: taken here because the read itself waits until there is foam.+ let foamUv = (wp + mc.u_foamFlow * time) / max(mc.u_foamTile, 1e-4);+ let foamDx = dpdx(foamUv);+ let foamDy = dpdy(foamUv);var surface = vec3f(0.0);if (dot(flow, flow) > 1e-6) {// A current: two copies of the surface carried downstream a cycle at a time, each fading in as the other fades out.@@ -1215,10 +1271,14 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> vecif (sun.dir.w > 0.5 && cosUp > 0.05) {let seabed = P + bentWave * column;let depthBelow = max(dot(P - seabed, Ngeo), 0.0);- let onSurface = seabed + sun.dir.xyz * (depthBelow / max(cosUp, 0.15));- let c = causticPattern(onSurface.xz / mc.u_causticScale, time * mc.u_causticSpeed);let reachSun = exp(-dot(mc.u_absorption.rgb, vec3f(1.0 / 3.0)) * mc.u_density * depthBelow / max(cosUp, 0.15));- behind = behind * (1.0 + mc.u_causticStrength * c * cosUp * waterSunVisibility(seabed, sun.tiles.x, sun.tiles.y) * reachSun * min(sun.color.a, 2.0) * 0.5);+ // The most the web can add here: where that is under a step of an 8-bit colour the pattern is not worked out (see the GLSL).+ let causticMost = mc.u_causticStrength * cosUp * reachSun * min(sun.color.a, 2.0) * 0.5;+ if (causticMost > 0.004) {+ let onSurface = seabed + sun.dir.xyz * (depthBelow / max(cosUp, 0.15));+ let c = causticPattern(onSurface.xz / mc.u_causticScale, time * mc.u_causticSpeed);+ behind = behind * (1.0 + causticMost * c * waterSunVisibility(seabed, sun.tiles.x, sun.tiles.y));+ }}}}@@ -1229,31 +1289,44 @@ fn waterSurface(p : vec2f, time : f32, dist : f32, amp : f32, calm : f32) -> veclet scatterColor = mix(mc.u_shallowColor.rgb, mc.u_deepColor.rgb, vec3f(1.0 - exp(-column * mc.u_density * 0.5)));let vertical = column * max(abs(viewDir.y), 0.15);- let foamScale = 1.0 / (mc.u_rippleLength * 1.2);- let breakup = waterNoise(wp * foamScale + vec2f(time * 0.07, time * 0.05)) * 0.6 + waterNoise(wp * foamScale * 3.0 - vec2f(time * 0.13, 0.0)) * 0.4;- let pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);- var shore = 0.0;- if (haveDepth && mc.u_foamWidth > 0.0) { shore = clamp((1.0 - vertical / (mc.u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0); }- if (zoneOn && mc.u_foamWidth > 0.0) {- // With the picture's depth the shallows foam by it, pixel by pixel; the baked depth then adds only the traced outline, not its texels.- var baked = min(shoreDist, shoreDepth);- if (haveDepth) { baked = shoreDist; }- shore = max(shore, clamp((1.0 - baked / (mc.u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0));- // How the shore takes its waves: against rock or a cliff they burst white; up a gentle beach they wash in a thin line only; and the- // less room the wind has to raise them (a sheltered lake), the less of either.- let pound = waterZoneSteep(wp);- let swash = 1.0 - smoothstep(0.0, surfStep * 1.5, shoreDist);- shore = shore * mix(swash * 0.6, 1.0, pound) * mix(0.3, 1.0, zone.w);+ var baked = min(shoreDist, shoreDepth);+ if (haveDepth) { baked = shoreDist; }+ // Most of a sea has none of the foam below, and the noise that breaks it up need not be worked out to find that (see the GLSL).+ var surfFoam = 0.0;+ var foam = 0.0;+ let crestLine = 1.0 - 0.3 * mc.u_foamCrest;+ if ((mc.u_foamWidth > 0.0 && ((haveDepth && vertical < mc.u_foamWidth) || (zoneOn && baked < mc.u_foamWidth))) || (mc.u_foamCrest > 0.0 && waves.crest > crestLine) || ripFoam > 0.0 || surf.y > 0.0) {+ let foamScale = 1.0 / (mc.u_rippleLength * 1.2);+ let breakup = waterNoise(wp * foamScale + vec2f(time * 0.07, time * 0.05)) * 0.6 + waterNoise(wp * foamScale * 3.0 - vec2f(time * 0.13, 0.0)) * 0.4;+ let pulse = 0.65 + 0.35 * sin(time * 0.9 + breakup * 6.0);+ var shore = 0.0;+ if (haveDepth && mc.u_foamWidth > 0.0) { shore = clamp((1.0 - vertical / (mc.u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0); }+ if (zoneOn && mc.u_foamWidth > 0.0) {+ // With the picture's depth the shallows foam by it, pixel by pixel; the baked depth then adds only the traced outline, not its texels.+ shore = max(shore, clamp((1.0 - baked / (mc.u_foamWidth * pulse)) * 1.25 - breakup * 1.15, 0.0, 1.0));+ if (shore > 0.0) {+ // How the shore takes its waves: against rock or a cliff they burst white; up a gentle beach they wash in a thin line only; and the+ // less room the wind has to raise them (a sheltered lake), the less of either.+ let pound = waterZoneSteep(wp);+ let swash = 1.0 - smoothstep(0.0, surfStep * 1.5, shoreDist);+ shore = shore * mix(swash * 0.6, 1.0, pound) * mix(0.3, 1.0, zone.w);+ }+ }+ var onCrest = 0.0;+ if (mc.u_foamCrest > 0.0) { onCrest = smoothstep(crestLine, 1.0, waves.crest) * smoothstep(0.35, 0.75, breakup); }+ // A breaker whitens as much on a beach as the waves are big, but bursts whitest on rock.+ if (surf.y > 0.0) {+ var steepHere = 1.0;+ if (zoneOn) { steepHere = waterZoneSteep(wp); }+ surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4) * mix(0.2, 1.0, steepHere);+ }+ foam = clamp(max(max(max(shore, onCrest * mc.u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 0.0, 1.0);+ }+ // The texture as coverage (see the GLSL): c = 1 leaves the foam as it was, and no foam stays none whatever c is.+ if (foam > 0.0) {+ let foamCover = textureSampleGrad(u_foamMap, u_foamMap_s, foamUv, foamDx, foamDy).r;+ foam = clamp((foam - (1.0 - foamCover)) / max(foamCover, 1e-3), 0.0, 1.0);}- 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); }- // A breaker whitens as much on a beach as the waves are big, but bursts whitest on rock.- var steepHere = 1.0;- if (zoneOn) { steepHere = waterZoneSteep(wp); }- let surfFoam = surf.y * smoothstep(0.15, 0.6, breakup + surf.y * 0.4) * mix(0.2, 1.0, steepHere);- var foam = clamp(max(max(max(shore, onCrest * mc.u_foamCrest), ripFoam * (0.55 + 0.45 * breakup)), surfFoam), 0.0, 1.0);- // The texture as coverage (see the GLSL): c = 1 leaves the foam as it was.- foam = clamp((foam - (1.0 - foamCover)) / max(foamCover, 1e-3), 0.0, 1.0);if (below) { foam = foam * 0.2; }var ext = surfaceExtNone(N);diff --git a/sdk/tests/water.test.ts b/sdk/tests/water.test.tsindex 81b1b4a92..3f957a032 100644--- a/sdk/tests/water.test.ts+++ b/sdk/tests/water.test.ts@@ -75,6 +75,16 @@ describe('the waves', () => {expect(source.split('fn waterBend(').length - 1).toBe(2);});+ it('has its waves written into the shader as the numbers the set gives, in both languages', () => {+ const source = JSON.stringify(WATER_SHADER_TEMPLATE);+ 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})`;+ expect(source.split(call).length - 1, call).toBe(2);+ });+ });+it('has a slope that is the derivative of its height', () => {const e = 1e-4;for (const [x, z, t] of [[0, 0, 0], [5.5, -3.1, 2.4], [-12, 9, 7.7]] as const) {diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 84df84b70..f45c33398 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -878,6 +878,12 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeRcontinue;}+ if (directive == "lighting") {+ // `#pragma lighting direct`: this surface is lit by the lights of the block and hard shadows only (see ES_LIGHT_DIRECT).+ if (trim(argument) == "direct") result.lightingDirect = true;+ continue;+ }+if (directive == "switch") {// Material-controlled compile-time toggle: `#pragma switch NAME [default(on|off)]`.usize swPos = 0;@@ -1557,6 +1563,7 @@ fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,// the tangent of the angle it subtends where its w is 1 everywhere.let hasEye = length(vec3f(m[0].w, m[1].w, m[2].w)) > 0.5;let src = select(source.y, source.x, hasEye);+#ifndef ES_LIGHT_DIRECT// Hair: layers of strand cards a few millimetres apart are not a wall. The light left after a depth of them falls off with that depth, from the// nearest card (what the map holds) to this one, the way a deep shadow map reads it. A blocker within a couple of texels toward the light is// this card's own surface and does not count.@@ -1576,6 +1583,7 @@ fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,if (hasEye) { spanHair = lcp.w - lcp.w * (Ah - proj.z) / max(Ah - zbh, 1e-6); }return mix(1.0, exp(-g_hairShadow * max(spanHair, 0.0)), hitsHair * 0.125);}+#endif// A source with no size throws one edge: a tent over the 3x3 texels around the// point, weighted by where it falls among them. Equal weights step at every// texel and the map's grid shows along the edge; a 2x2 still stair-steps it.@@ -1594,6 +1602,7 @@ fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,}return lit;}+#ifndef ES_LIGHT_DIRECT// What blocks this fragment, over the whole disc an edge can reach across — and// against a depth that forgives that reach, since a tap r texels away lands r// texels along the surface and a one-texel bias would call the slope a blocker.@@ -1671,6 +1680,7 @@ fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,soft += shadowTap(at0 + off * lc.u_shadowParams.y, lo, hi, wide);}return soft * (1.0 / 32.0);+#endif}return 1.0;#endif@@ -1802,8 +1812,8 @@ fn envBRDFApprox(NdotV : f32, roughness : f32) -> vec2f {let py5 = (9.0 * ty * py4 - 4.0 * py3) / 5.0;let py6 = (11.0 * ty * py5 - 5.0 * py4) / 6.0;let g = 1.0 / (clamp(NdotV, 0.02, 1.0) + 0.1);- let sumMetal = 0.7771111 * px0 * py0 - 0.2780760 * px0 * py1 - 0.0654304 * px0 * py2 - 0.0705640 * px0 * py3 + 0.0859185 * px0 * py4 + 0.0016314 * px0 * py5 - 0.0014479 * px0 * py6 + 0.0048182 * px1 * py0 - 0.1346961 * px1 * py1 - 0.1342442 * px1 * py2 + 0.1115811 * px1 * py3 - 0.0497620 * px1 * py4 - 0.0098451 * px1 * py5 - 0.0004214 * px1 * py6 + 0.0004797 * px2 * py0 + 0.0654544 * px2 * py1 + 0.0215100 * px2 * py2 - 0.0948616 * px2 * py3 + 0.0774489 * px2 * py4 + 0.0139819 * px2 * py5 - 0.0151021 * px2 * py6 + 0.0022918 * px3 * py0 - 0.0244567 * px3 * py1 + 0.0056279 * px3 * py2 + 0.0393924 * px3 * py3 - 0.0613759 * px3 * py4 + 0.0099383 * px3 * py5 + 0.0092971 * px3 * py6 - 0.0025728 * px4 * py0 + 0.0085869 * px4 * py1 - 0.0069877 * px4 * py2 - 0.0115072 * px4 * py3 + 0.0327063 * px4 * py4 - 0.0167796 * px4 * py5 + 0.0019107 * px4 * py6 + 0.0018089 * px5 * py0 - 0.0031015 * px5 * py1 + 0.0047701 * px5 * py2 + 0.0018675 * px5 * py3 - 0.0134691 * px5 * py4 + 0.0139776 * px5 * py5 - 0.0087024 * px5 * py6 - 0.0008609 * px6 * py0 + 0.0010956 * px6 * py1 - 0.0024048 * px6 * py2 + 0.0005262 * px6 * py3 + 0.0035639 * px6 * py4 - 0.0080487 * px6 * py5 + 0.0080563 * px6 * py6 + 0.0220605 * py0 * g + 0.0049886 * py1 * g - 0.0108884 * py2 * g + 0.0359254 * py3 * g - 0.0336876 * py4 * g;- let sumDielectric = 0.1105178 * px0 * py0 - 0.1470108 * px0 * py1 + 0.0706290 * px0 * py2 - 0.0048613 * px0 * py3 - 0.0190413 * px0 * py4 + 0.0038142 * px0 * py5 - 0.0002643 * px0 * py6 - 0.1400053 * px1 * py0 + 0.2220226 * px1 * py1 - 0.1204309 * px1 * py2 + 0.0033027 * px1 * py3 + 0.0348652 * px1 * py4 - 0.0115348 * px1 * py5 + 0.0015711 * px1 * py6 + 0.0993738 * px2 * py0 - 0.1696809 * px2 * py1 + 0.1055418 * px2 * py2 - 0.0166890 * px2 * py3 - 0.0245166 * px2 * py4 + 0.0153020 * px2 * py5 - 0.0048468 * px2 * py6 - 0.0363361 * px3 * py0 + 0.0724203 * px3 * py1 - 0.0631513 * px3 * py2 + 0.0261354 * px3 * py3 + 0.0041759 * px3 * py4 - 0.0092203 * px3 * py5 + 0.0054510 * px3 * py6 + 0.0046882 * px4 * py0 - 0.0144579 * px4 * py1 + 0.0238812 * px4 * py2 - 0.0200861 * px4 * py3 + 0.0078934 * px4 * py4 - 0.0001779 * px4 * py5 - 0.0024009 * px4 * py6 + 0.0013258 * px5 * py0 - 0.0006506 * px5 * py1 - 0.0049831 * px5 * py2 + 0.0084229 * px5 * py3 - 0.0075026 * px5 * py4 + 0.0046720 * px5 * py5 - 0.0007627 * px5 * py6 - 0.0005364 * px6 * py0 + 0.0008141 * px6 * py1 + 0.0002790 * px6 * py2 - 0.0016584 * px6 * py3 + 0.0027280 * px6 * py4 - 0.0028646 * px6 * py5 + 0.0010557 * px6 * py6 - 0.0075790 * py0 * g + 0.0243928 * py1 * g - 0.0212081 * py2 * g + 0.0063496 * py3 * g + 0.0036408 * py4 * g;+ let sumMetal = (0.7771111 - 0.2780760 * py1 - 0.0654304 * py2 - 0.0705640 * py3 + 0.0859185 * py4 + 0.0016314 * py5 - 0.0014479 * py6) + px1 * (0.0048182 - 0.1346961 * py1 - 0.1342442 * py2 + 0.1115811 * py3 - 0.0497620 * py4 - 0.0098451 * py5 - 0.0004214 * py6) + px2 * (0.0004797 + 0.0654544 * py1 + 0.0215100 * py2 - 0.0948616 * py3 + 0.0774489 * py4 + 0.0139819 * py5 - 0.0151021 * py6) + px3 * (0.0022918 - 0.0244567 * py1 + 0.0056279 * py2 + 0.0393924 * py3 - 0.0613759 * py4 + 0.0099383 * py5 + 0.0092971 * py6) + px4 * (-0.0025728 + 0.0085869 * py1 - 0.0069877 * py2 - 0.0115072 * py3 + 0.0327063 * py4 - 0.0167796 * py5 + 0.0019107 * py6) + px5 * (0.0018089 - 0.0031015 * py1 + 0.0047701 * py2 + 0.0018675 * py3 - 0.0134691 * py4 + 0.0139776 * py5 - 0.0087024 * py6) + px6 * (-0.0008609 + 0.0010956 * py1 - 0.0024048 * py2 + 0.0005262 * py3 + 0.0035639 * py4 - 0.0080487 * py5 + 0.0080563 * py6) + g * (0.0220605 + 0.0049886 * py1 - 0.0108884 * py2 + 0.0359254 * py3 - 0.0336876 * py4);+ let sumDielectric = (0.1105178 - 0.1470108 * py1 + 0.0706290 * py2 - 0.0048613 * py3 - 0.0190413 * py4 + 0.0038142 * py5 - 0.0002643 * py6) + px1 * (-0.1400053 + 0.2220226 * py1 - 0.1204309 * py2 + 0.0033027 * py3 + 0.0348652 * py4 - 0.0115348 * py5 + 0.0015711 * py6) + px2 * (0.0993738 - 0.1696809 * py1 + 0.1055418 * py2 - 0.0166890 * py3 - 0.0245166 * py4 + 0.0153020 * py5 - 0.0048468 * py6) + px3 * (-0.0363361 + 0.0724203 * py1 - 0.0631513 * py2 + 0.0261354 * py3 + 0.0041759 * py4 - 0.0092203 * py5 + 0.0054510 * py6) + px4 * (0.0046882 - 0.0144579 * py1 + 0.0238812 * py2 - 0.0200861 * py3 + 0.0078934 * py4 - 0.0001779 * py5 - 0.0024009 * py6) + px5 * (0.0013258 - 0.0006506 * py1 - 0.0049831 * py2 + 0.0084229 * py3 - 0.0075026 * py4 + 0.0046720 * py5 - 0.0007627 * py6) + px6 * (-0.0005364 + 0.0008141 * py1 + 0.0002790 * py2 - 0.0016584 * py3 + 0.0027280 * py4 - 0.0028646 * py5 + 0.0010557 * py6) + g * (-0.0075790 + 0.0243928 * py1 - 0.0212081 * py2 + 0.0063496 * py3 + 0.0036408 * py4);let scale = (sumMetal - sumDielectric) / 0.96;return vec2f(scale, sumMetal - scale);}@@ -1831,7 +1841,17 @@ fn ambientFacing(dir : vec3f) -> vec3f {return lc.u_ambient.rgb + lc.u_ambientGround.rgb * (0.5 - 0.5 * dir.y);}fn envIrradiance(Nw : vec3f) -> vec3f {- let sh = shIrradiance(lc.u_envIrradiance, envDirection(Nw));+ // Read in place, not passed: an array handed to a function is copied, all nine, for every pixel.+ let N = envDirection(Nw);+ let sh = lc.u_envIrradiance[0].rgb * 0.282095+ + lc.u_envIrradiance[1].rgb * (0.488603 * N.y)+ + lc.u_envIrradiance[2].rgb * (0.488603 * N.z)+ + lc.u_envIrradiance[3].rgb * (0.488603 * N.x)+ + lc.u_envIrradiance[4].rgb * (1.092548 * N.x * N.y)+ + lc.u_envIrradiance[5].rgb * (1.092548 * N.y * N.z)+ + lc.u_envIrradiance[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))+ + lc.u_envIrradiance[7].rgb * (1.092548 * N.x * N.z)+ + lc.u_envIrradiance[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));return ambientFacing(Nw) + max(sh, vec3f(0.0)) * lc.u_envTint.rgb;}// The GLSL twin's indirectIrradiance: a volume replaces the environment, because a@@ -2027,13 +2047,16 @@ fn applyLightingSurface(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f,var lit = indirectIrradiance(N) * ao;var gloss = vec3f(0.0);var extra = vec3f(0.0);- for (var i = 0; i < 16; i++) {+ // As many as are lit: read for a slot nobody uses, a light's six vectors cost more on a phone than the one light shaded.+ let lightCount = i32(lc.u_ambient.a);+ for (var i = 0; i < lightCount; i++) {let term = shadeLight(lc.u_lights[i].posDir, lc.u_lights[i].color, lc.u_lights[i].spot, lc.u_lights[i].shadow,lc.u_lights[i].shadowMap, lc.u_lights[i].falloff, N, V, worldPos, a, F0, NdotV, specular, roughness, ext, true);lit += term.lit;gloss += term.gloss;extra += term.extra;}+#ifndef ES_LIGHT_DIRECT// The lights past the sixteen: this pixel's tile is found from where the fragment lands through the camera it was drawn by// (normalized device coordinates, the same on every backend), and only the lights whose bit is set in its mask are shaded.let tiledCount = i32(lc.tileInfo.x);@@ -2060,6 +2083,7 @@ fn applyLightingSurface(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f,}}}+#endiflet ab = envBRDFApprox(NdotV, roughness);// The light a rough microfacet surface loses to bounces between its facets, which single-scattering GGX leaves out (a metal at roughness// 0.9 came out at half of Blender's brightness): Fdez-Aguera's term for the environment, and the same ratio on the lamps' highlight. What@@ -2153,12 +2177,14 @@ fn shadeLight(pd : vec4f, col : vec4f, sp : vec4f, sh : vec4f, sm : vec4f, fo :L = towardLight(toL, N);atten *= spotCone(sp, sh, toL, dist);}+#ifndef ES_LIGHT_DIRECTif (col.a > 0.0 && atten > 0.0) {atten *= shapeFactor2D(fo.w, worldPos.xy);}if (castShadow && col.a > 0.0 && atten > 0.0) {atten *= mix(1.0, shadowFactor2D(sm.w, worldPos.xy), fo.z);}+#endif// See the GLSL twin: a light the tiles carry has no shadow map, and says so.if (shadow3D && sm.y % 8.0 > 0.0 && atten > 0.0) {atten *= mix(1.0,@@ -2519,6 +2545,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// ES_LINEAR world with no per-call-site wiring. It must be set before the// renderer compiles shaders; flipping it later requires a reload.std::vector<std::string> features = featuresIn;+ if (parsed.lightingDirect) features.push_back("ES_LIGHT_DIRECT");if (s_linearColor&& std::find(features.begin(), features.end(), "ES_LINEAR") == features.end()) {features.push_back("ES_LINEAR");@@ -2907,6 +2934,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// the tangent of the angle it subtends where its w is 1 everywhere." bool hasEye = length(vec3(m[0][3], m[1][3], m[2][3])) > 0.5;\n"" highp float src = hasEye ? source.x : source.y;\n"+ "#ifndef ES_LIGHT_DIRECT\n"// Hair: the light left after a depth of strand layers falls off with that depth, from the nearest card (what the map holds) to this one.// A blocker within a couple of texels toward the light is this card's own surface and does not count." if (g_hairShadow > 0.0) {\n"@@ -2925,6 +2953,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" if (hasEye) spanHair = lc.w - lc.w * (Ah - proj.z) / max(Ah - zbh, 1e-6);\n"" return mix(1.0, exp(-g_hairShadow * max(spanHair, 0.0)), hitsHair * 0.125);\n"" }\n"+ "#endif\n"// A source with no size throws one edge: a tent over the 3x3 texels around the// point, weighted by where it falls among them. Equal weights step at every// texel and the map's grid shows along the edge; a 2x2 still stair-steps it.@@ -2944,6 +2973,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" }\n"" return lit;\n"" }\n"+ "#ifndef ES_LIGHT_DIRECT\n"// What blocks this fragment, over the whole disc an edge can reach across —// against a depth that forgives that reach, since a tap r texels out lands r// texels along the surface and a one-texel bias would call the slope one.@@ -3029,6 +3059,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" }\n"" return soft * (1.0 / 32.0);\n"+ "#endif\n"" }\n"" return 1.0;\n""#endif\n"@@ -3161,8 +3192,8 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" highp float py5 = (9.0 * ty * py4 - 4.0 * py3) / 5.0;\n"" highp float py6 = (11.0 * ty * py5 - 5.0 * py4) / 6.0;\n"" highp float g = 1.0 / (clamp(NdotV, 0.02, 1.0) + 0.1);\n"- " highp float sumMetal = 0.7771111 * px0 * py0 - 0.2780760 * px0 * py1 - 0.0654304 * px0 * py2 - 0.0705640 * px0 * py3 + 0.0859185 * px0 * py4 + 0.0016314 * px0 * py5 - 0.0014479 * px0 * py6 + 0.0048182 * px1 * py0 - 0.1346961 * px1 * py1 - 0.1342442 * px1 * py2 + 0.1115811 * px1 * py3 - 0.0497620 * px1 * py4 - 0.0098451 * px1 * py5 - 0.0004214 * px1 * py6 + 0.0004797 * px2 * py0 + 0.0654544 * px2 * py1 + 0.0215100 * px2 * py2 - 0.0948616 * px2 * py3 + 0.0774489 * px2 * py4 + 0.0139819 * px2 * py5 - 0.0151021 * px2 * py6 + 0.0022918 * px3 * py0 - 0.0244567 * px3 * py1 + 0.0056279 * px3 * py2 + 0.0393924 * px3 * py3 - 0.0613759 * px3 * py4 + 0.0099383 * px3 * py5 + 0.0092971 * px3 * py6 - 0.0025728 * px4 * py0 + 0.0085869 * px4 * py1 - 0.0069877 * px4 * py2 - 0.0115072 * px4 * py3 + 0.0327063 * px4 * py4 - 0.0167796 * px4 * py5 + 0.0019107 * px4 * py6 + 0.0018089 * px5 * py0 - 0.0031015 * px5 * py1 + 0.0047701 * px5 * py2 + 0.0018675 * px5 * py3 - 0.0134691 * px5 * py4 + 0.0139776 * px5 * py5 - 0.0087024 * px5 * py6 - 0.0008609 * px6 * py0 + 0.0010956 * px6 * py1 - 0.0024048 * px6 * py2 + 0.0005262 * px6 * py3 + 0.0035639 * px6 * py4 - 0.0080487 * px6 * py5 + 0.0080563 * px6 * py6 + 0.0220605 * py0 * g + 0.0049886 * py1 * g - 0.0108884 * py2 * g + 0.0359254 * py3 * g - 0.0336876 * py4 * g;\n"- " highp float sumDielectric = 0.1105178 * px0 * py0 - 0.1470108 * px0 * py1 + 0.0706290 * px0 * py2 - 0.0048613 * px0 * py3 - 0.0190413 * px0 * py4 + 0.0038142 * px0 * py5 - 0.0002643 * px0 * py6 - 0.1400053 * px1 * py0 + 0.2220226 * px1 * py1 - 0.1204309 * px1 * py2 + 0.0033027 * px1 * py3 + 0.0348652 * px1 * py4 - 0.0115348 * px1 * py5 + 0.0015711 * px1 * py6 + 0.0993738 * px2 * py0 - 0.1696809 * px2 * py1 + 0.1055418 * px2 * py2 - 0.0166890 * px2 * py3 - 0.0245166 * px2 * py4 + 0.0153020 * px2 * py5 - 0.0048468 * px2 * py6 - 0.0363361 * px3 * py0 + 0.0724203 * px3 * py1 - 0.0631513 * px3 * py2 + 0.0261354 * px3 * py3 + 0.0041759 * px3 * py4 - 0.0092203 * px3 * py5 + 0.0054510 * px3 * py6 + 0.0046882 * px4 * py0 - 0.0144579 * px4 * py1 + 0.0238812 * px4 * py2 - 0.0200861 * px4 * py3 + 0.0078934 * px4 * py4 - 0.0001779 * px4 * py5 - 0.0024009 * px4 * py6 + 0.0013258 * px5 * py0 - 0.0006506 * px5 * py1 - 0.0049831 * px5 * py2 + 0.0084229 * px5 * py3 - 0.0075026 * px5 * py4 + 0.0046720 * px5 * py5 - 0.0007627 * px5 * py6 - 0.0005364 * px6 * py0 + 0.0008141 * px6 * py1 + 0.0002790 * px6 * py2 - 0.0016584 * px6 * py3 + 0.0027280 * px6 * py4 - 0.0028646 * px6 * py5 + 0.0010557 * px6 * py6 - 0.0075790 * py0 * g + 0.0243928 * py1 * g - 0.0212081 * py2 * g + 0.0063496 * py3 * g + 0.0036408 * py4 * g;\n"+ " highp float sumMetal = (0.7771111 - 0.2780760 * py1 - 0.0654304 * py2 - 0.0705640 * py3 + 0.0859185 * py4 + 0.0016314 * py5 - 0.0014479 * py6) + px1 * (0.0048182 - 0.1346961 * py1 - 0.1342442 * py2 + 0.1115811 * py3 - 0.0497620 * py4 - 0.0098451 * py5 - 0.0004214 * py6) + px2 * (0.0004797 + 0.0654544 * py1 + 0.0215100 * py2 - 0.0948616 * py3 + 0.0774489 * py4 + 0.0139819 * py5 - 0.0151021 * py6) + px3 * (0.0022918 - 0.0244567 * py1 + 0.0056279 * py2 + 0.0393924 * py3 - 0.0613759 * py4 + 0.0099383 * py5 + 0.0092971 * py6) + px4 * (-0.0025728 + 0.0085869 * py1 - 0.0069877 * py2 - 0.0115072 * py3 + 0.0327063 * py4 - 0.0167796 * py5 + 0.0019107 * py6) + px5 * (0.0018089 - 0.0031015 * py1 + 0.0047701 * py2 + 0.0018675 * py3 - 0.0134691 * py4 + 0.0139776 * py5 - 0.0087024 * py6) + px6 * (-0.0008609 + 0.0010956 * py1 - 0.0024048 * py2 + 0.0005262 * py3 + 0.0035639 * py4 - 0.0080487 * py5 + 0.0080563 * py6) + g * (0.0220605 + 0.0049886 * py1 - 0.0108884 * py2 + 0.0359254 * py3 - 0.0336876 * py4);\n"+ " highp float sumDielectric = (0.1105178 - 0.1470108 * py1 + 0.0706290 * py2 - 0.0048613 * py3 - 0.0190413 * py4 + 0.0038142 * py5 - 0.0002643 * py6) + px1 * (-0.1400053 + 0.2220226 * py1 - 0.1204309 * py2 + 0.0033027 * py3 + 0.0348652 * py4 - 0.0115348 * py5 + 0.0015711 * py6) + px2 * (0.0993738 - 0.1696809 * py1 + 0.1055418 * py2 - 0.0166890 * py3 - 0.0245166 * py4 + 0.0153020 * py5 - 0.0048468 * py6) + px3 * (-0.0363361 + 0.0724203 * py1 - 0.0631513 * py2 + 0.0261354 * py3 + 0.0041759 * py4 - 0.0092203 * py5 + 0.0054510 * py6) + px4 * (0.0046882 - 0.0144579 * py1 + 0.0238812 * py2 - 0.0200861 * py3 + 0.0078934 * py4 - 0.0001779 * py5 - 0.0024009 * py6) + px5 * (0.0013258 - 0.0006506 * py1 - 0.0049831 * py2 + 0.0084229 * py3 - 0.0075026 * py4 + 0.0046720 * py5 - 0.0007627 * py6) + px6 * (-0.0005364 + 0.0008141 * py1 + 0.0002790 * py2 - 0.0016584 * py3 + 0.0027280 * py4 - 0.0028646 * py5 + 0.0010557 * py6) + g * (-0.0075790 + 0.0243928 * py1 - 0.0212081 * py2 + 0.0063496 * py3 + 0.0036408 * py4);\n"" highp float scale = (sumMetal - sumDielectric) / 0.96;\n"" return vec2(scale, sumMetal - scale);\n""}\n"@@ -3194,7 +3225,17 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" return u_ambient.rgb + u_ambientGround.rgb * (0.5 - 0.5 * dir.y);\n""}\n""highp vec3 envIrradiance(in highp vec3 Nw) {\n"- " highp vec3 sh = shIrradiance(u_envIrradiance, envDirection(Nw));\n"+ // Read in place, not passed: an array handed to a function is copied, all nine, for every pixel.+ " highp vec3 N = envDirection(Nw);\n"+ " highp vec3 sh = u_envIrradiance[0].rgb * 0.282095\n"+ " + u_envIrradiance[1].rgb * (0.488603 * N.y)\n"+ " + u_envIrradiance[2].rgb * (0.488603 * N.z)\n"+ " + u_envIrradiance[3].rgb * (0.488603 * N.x)\n"+ " + u_envIrradiance[4].rgb * (1.092548 * N.x * N.y)\n"+ " + u_envIrradiance[5].rgb * (1.092548 * N.y * N.z)\n"+ " + u_envIrradiance[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))\n"+ " + u_envIrradiance[7].rgb * (1.092548 * N.x * N.z)\n"+ " + u_envIrradiance[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));\n"" return ambientFacing(Nw) + max(sh, vec3(0.0)) * u_envTint.rgb;\n""}\n"// The indirect term every lit surface starts from. A volume REPLACES the@@ -3449,11 +3490,14 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" highp vec3 extra = vec3(0.0);\n"// A Light has no third coordinate, so distance stays in the plane and a// point light's height is its radius. Normal and view are the 3D part.- " for (int i = 0; i < 16; ++i) {\n"+ // As many as are lit: read for a slot nobody uses, a light's six vectors cost more on a phone than the one light shaded.+ " int lightCount = int(u_ambient.a);\n"+ " for (int i = 0; i < lightCount; ++i) {\n"" shadeLight(u_lights[i].posDir, u_lights[i].color, u_lights[i].spot, u_lights[i].shadow,\n"" u_lights[i].shadowMap, u_lights[i].falloff, N, V, worldPos, a, F0, NdotV,\n"" specular, roughness, ext, lit, gloss, extra, true);\n"" }\n"+ "#ifndef ES_LIGHT_DIRECT\n"// The lights past the sixteen: this pixel's tile is found from where the fragment lands through the camera it was drawn by// (normalized device coordinates, the same on every backend), and only the lights whose bit is set in its mask are shaded." int tiledCount = int(u_tileInfo.x);\n"@@ -3479,6 +3523,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// The environment, which for this engine is the ambient term: the same// radiance from every direction. A metal has no diffuse, so without a// reflection of it a metal is black wherever no light happens to point.+ "#endif\n"" highp vec2 ab = envBRDFApprox(NdotV, roughness);\n"// Multiple scattering, and the diffuse under the specular: see the WGSL twin." highp float Ess = ab.x + ab.y;\n"@@ -3561,12 +3606,14 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" }\n"// Only pay for the mask read when the light actually reaches this fragment (skips// the zeroed/inactive slots and unlit fragments).+ "#ifndef ES_LIGHT_DIRECT\n"" if (col.a > 0.0 && atten > 0.0) {\n"" atten *= shapeFactor2D(fo.w, worldPos.xy);\n"" }\n"" if (castShadow && col.a > 0.0 && atten > 0.0) {\n"" atten *= mix(1.0, shadowFactor2D(sm.w, worldPos.xy), fo.z);\n"" }\n"+ "#endif\n"// The tiles this light rendered into, which are its own: a fragment// tested against every map in the atlas would be darkened by geometry// seen from somewhere no light reaching it is standing.diff --git a/src/esengine/resource/ShaderParser.hpp b/src/esengine/resource/ShaderParser.hppindex 4f6233e37..ed136eba9 100644--- a/src/esengine/resource/ShaderParser.hpp+++ b/src/esengine/resource/ShaderParser.hpp@@ -148,6 +148,9 @@ struct ParsedShader {std::unordered_map<ShaderStage, std::string> stages; ///< Stage source codestd::unordered_map<std::string, std::string> variants; ///< Platform variantsstd::vector<std::string> features; ///< Declared #pragma feature keywords (compile-time variants)+ /// `#pragma lighting direct`: compiled with ES_LIGHT_DIRECT. Lit by the sixteen lights of the block and hard-edged shadows only, without what most scenes never+ /// reach and every pixel pays for regardless (on a phone, a third of a water's frame): the tiled lights, the 2D light masks, the soft and hair shadows.+ bool lightingDirect = false;std::vector<ShaderSwitch> switches; ///< Material-controlled #pragma switch toggles (name + default)std::vector<ShaderProperty> properties; ///< Exposed material params (#pragma param / properties block)std::string domain = "Unlit"; ///< #pragma domain (Unlit/Lit/PostProcess/UI)diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cppindex 00b1409af..e87d1196b 100644--- a/tests/renderer/test_shader_variant.cpp+++ b/tests/renderer/test_shader_variant.cpp@@ -45,6 +45,22 @@ void main() {#pragma end)";+// `#pragma lighting direct`: the lit header compiled without what the surface declared it does not need.+static const char* DIRECT_LIT = R"(#pragma shader "DirectLit"+#pragma version 300 es+#pragma domain Lit+#pragma lighting direct++#pragma fragment+out vec4 fragColor;+void main() { fragColor = vec4(1.0); }+#pragma end++#pragma fragment wgsl+@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1.0); }+#pragma end+)";+// Fragment-only authoring: `#pragma vertex` is optional for 2D domains.static const char* FRAG_ONLY_UNLIT = R"(#pragma shader "FragOnly"#pragma version 300 es@@ -775,6 +791,36 @@ static void testShadowGraft() {"the stock depth shader's call sits under ES_MATERIAL_VERTEX");}+static void testLightingDirect() {+ std::printf("\n-- #pragma lighting direct --\n");+ std::string plain(DIRECT_LIT);+ const std::string pragma = "#pragma lighting direct\n";+ plain.erase(plain.find(pragma), pragma.size());+ const ParsedShader direct = ShaderParser::parse(DIRECT_LIT);+ const ParsedShader full = ShaderParser::parse(plain);+ CHECK(direct.valid && direct.lightingDirect, "the directive is read");+ CHECK(full.valid && !full.lightingDirect, "a lit shader that does not ask keeps everything");+ const std::vector<std::string> mesh{"MESH", "MESH_NORMALS", "ES_RECEIVE_SHADOW", "ES_SURFACE_3D"};+ // GLSL keeps its conditionals for the driver's preprocessor, so there the define is what can be seen.+ const std::string glslOn = ShaderParser::assembleStage(direct, ShaderStage::Fragment, "", mesh, ShaderTargetLanguage::GLSL_ES300);+ const std::string glslOff = ShaderParser::assembleStage(full, ShaderStage::Fragment, "", mesh, ShaderTargetLanguage::GLSL_ES300);+ CHECK(glslOn.find("#define ES_LIGHT_DIRECT") != std::string::npos, "GLSL is compiled with the define");+ CHECK(glslOff.find("#define ES_LIGHT_DIRECT") == std::string::npos, "GLSL that did not ask is not");+ for (const char* guarded : {"tiledCount", "atten *= shapeFactor2D", "atten *= mix(1.0, shadowFactor2D", "kSpiral32[i]", "reachHair"}) {+ const size_t at = glslOn.find(guarded);+ CHECK(at != std::string::npos && glslOn.rfind("#ifndef ES_LIGHT_DIRECT", at) != std::string::npos+ && glslOn.rfind("#ifndef ES_LIGHT_DIRECT", at) > glslOn.rfind("#endif", at), guarded);+ }+ // WGSL has no preprocessor: what the directive removes is gone from the text.+ const std::string on = ShaderParser::assembleStage(direct, ShaderStage::Fragment, "", mesh, ShaderTargetLanguage::WGSL);+ const std::string off = ShaderParser::assembleStage(full, ShaderStage::Fragment, "", mesh, ShaderTargetLanguage::WGSL);+ for (const char* gone : {"tiledCount", "atten *= shapeFactor2D", "atten *= mix(1.0, shadowFactor2D", "kSpiral32[i]", "reachHair"}) {+ CHECK(off.find(gone) != std::string::npos, gone);+ CHECK(on.find(gone) == std::string::npos, gone);+ }+ CHECK(on.find("shadeLight(") != std::string::npos && on.find("g_shadowHard > 0.5") != std::string::npos, "the block's lights and the hard shadow stay");+}+int main() {ParsedShader p = ShaderParser::parse(SRC);CHECK(p.valid, "shader parses");@@ -801,6 +847,7 @@ int main() {testSystemValuesTrailAttributes();testVertexHook();testShadowGraft();+ testLightingDirect();if (g_failures == 0) {std::printf("\nALL SHADER-VARIANT TESTS PASSED\n");diff --git a/tools/gen-dfg-fit.py b/tools/gen-dfg-fit.pyindex ea833eef6..67f576f53 100644--- a/tools/gen-dfg-fit.py+++ b/tools/gen-dfg-fit.py@@ -119,17 +119,19 @@ if '--code' in sys.argv:out.append('%s %s%d = (%.1f * %s * %s%d - %.1f * %s%d) / %.1f;' % (decl, var, k + 1, 2 * k + 1, t, var, k, k, var, k - 1, k + 1))return out+ def row_expr(cs):+ out = '%.7f' % cs[0]+ for q, c in enumerate(cs[1:], 1):+ out += ' + %.7f * py%d' % (c, q)+ return out.replace('+ -', '- ')+def sum_expr(c):- terms = []- k = 0- for p in range(DX):- for q in range(DY):- terms.append('%.7f * px%d * py%d' % (c[k], p, q))- k += 1- for q in range(INV):- terms.append('%.7f * py%d * g' % (c[k], q))- k += 1- return ' + '.join(terms).replace('+ -', '- ')+ # A row for each power of x, so a product of two polynomials is read once: this runs for every lit pixel, and spelled out term by+ # term it was twice the multiplications, on a phone most of what the lighting costs.+ parts = ['(%s)' % row_expr(c[:DY])]+ parts += ['px%d * (%s)' % (p, row_expr(c[p * DY:(p + 1) * DY])) for p in range(1, DX)]+ parts.append('g * (%s)' % row_expr(c[DX * DY:]))+ return ' + '.join(parts)for lang in ('wgsl', 'glsl'):decl = 'let' if lang == 'wgsl' else 'highp float'