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(render): fog follows the scene's sun and can walk the air against its shadow map
yhh2b9d6f775e23
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b2132d621..702ac0def 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,7 +20,7 @@ published separately; it ships inside the editor.- **A G-buffer, and reflections that read it.** Reflections now know how rough and how metal each surface is, from a G-buffer the frame draws on request. A post-process shader that says `#pragma gbuffer` makes the scene target carry a second RGBA8 colour attachment, written in the same pass by the scene's own shaders — octahedral normal in `r`/`g`, roughness in `b`, metalness in `a` (0 where nothing wrote) — and finds it at `u_gbuffer`. A frame whose chain has no such effect makes none and compiles no variant. The render device grew multiple colour attachments for it on both backends: WebGL2 attaches and resolves a second target and sets the draw buffers per pipeline, and WebGPU declares the second target on every pipeline of the pass (written by the ones that write it, an empty write mask for the rest), clears it to zero and resolves it with the colour. Pipelines say whether they write it (`PipelineDesc::gbuffer`), a blended draw never does, and the second output is its own shader variant (`ES_GBUFFER`), so no pass pays for what it did not ask for. The built-in Model shader — what an imported glTF material becomes — writes it from the material's roughness, metalness and normal map. `ssr` reads it: it takes the surface's own normal (normal-map detail that depth cannot see), weighs and blurs the reflection by roughness, reflects a metal at nearly full strength where a dielectric reflects 4%, skips a surface rougher than `maxRoughness` before marching the ray, and takes the Rain effect's `wetness` as a film that smooths the ground. Where nothing wrote a record, it falls back to depth and the dielectric it has always assumed. Verified in the editor on both backends: of two floors that differ only in their material's roughness, the glossy one changes ten times the pixels the rough one does. Quality levels can also leave out expensive effects now: quality levels can now skip expensive post-process effects by name. A level's `skipEffects` lists the effects it leaves out, each named by its effect type (`ssr`, `taa`, `depthOfField`, `lightShafts`, `autoExposure`, …), and an effect leaves with all of its passes however they are named; a project's own list in its quality profile replaces the level's. By default low leaves out reflections, temporal anti-aliasing, depth of field and light shafts, and medium leaves out reflections and depth of field; high leaves out nothing. These defaults come from the work each effect does per pixel, not from a weak device: the editor's new `fx-cost` check measured every effect on Bistro at 2560×1600 on a fast desktop GPU, and none added more than about 6 ms (reflections ~5, bloom ~4, the example's whole eight-effect chain ~11, the rest within the ±3 ms the run drifts by), so the levels have not been checked against the hardware they are for. Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen.- **Rain, wet ground and puddles.** A Rain post-process effect adds falling rain, wet ground, puddles and ripples. `rain` draws three layers of slanted streaks, each at its own distance so a nearer surface hides them and the sky does not; darkens the ground that faces up by `wetness`; lays ripples and splashes where drops land on a grid in the world, so they stay on the ground as the camera moves (ripples need `intensity` above 0: wet ground under no rain is still); and, by `puddles` and `puddleScale`, covers part of the flat ground with standing water that is darker and takes denser, clearer ripples. `ssr` takes the same two numbers and treats those pools as mirrors — flat, far more reflective than dry ground, and sharp — so the pools the rain darkens are the pools that reflect. The clock is `u_time * timeScale + phase`, so a capture can pin it. The rain is a screen-space layer, not particles that collide with the world, and a puddle is flat ground whatever it lies on. Verified in the editor on both backends: streaks light a dark sky and move between two moments, wet ground reads darker, standing water darker still, and puddles change the reflection.- **Auto Exposure and Depth of Field.** Auto Exposure and Depth of Field post-process effects are available. `autoExposure` measures the average log luminance of the picture (leaving out pixels darker than 2^-8, so a black backdrop does not open the exposure to its limit), turns it into the exposure that puts it at middle grey, and moves toward that over time from where the last frame left it — brighter faster than darker, per second, within `minEV` and `maxEV`, with a `bias` in stops. To keep the settled value between frames a post-process shader can now declare a `u_feedback` texture: the engine keeps that pass's last output, at the pass's own size, and binds it there, without shifting the picture the way `u_history` does. `depthOfField` blurs by distance from `focusDistance`, with a sharp slab of `focusRange`, a blur radius that grows with how far a surface is from focus up to `maxBlur`, and a gather that counts a neighbour only where its own blur reaches back, so a sharp object does not bleed into a blurred background. Verified in the editor on both backends: a dim scene brightens (mean 6.9 to 16.5) and a bright one darkens (30.7 to 20.4), a drop in light is first dark and then recovered over real time (5.2 then 15.8), and focusing close takes the squared edge energy down to 21% of the sharp frame.-- **Height Fog and Light Shafts.** Height Fog and Light Shafts post-process effects add atmosphere. `heightFog` is exponential height fog with a closed-form integral — no marching — so a valley fills and a hilltop clears, the horizon turns hazy while the zenith stays clear, and looking toward the sun the haze takes the sun's colour; sky pixels run through the same formula with a very long ray, and `skyFog` sets how much haze the sky keeps. `lightShafts` marches each pixel toward the sun's place on screen and counts how much of the way is open sky, leaving rays through whatever stands in front of the sun. The sun's direction is set on the effects (azimuth and elevation), not read from a light. Neither is a shadowed volume: fog is lit evenly. Both run on WebGL2 and WebGPU; with an output transform of None, a floor fully taken by the fog reads exactly the authored colour on both.+- **Height Fog and Light Shafts.** Height Fog and Light Shafts post-process effects add atmosphere. `heightFog` is exponential height fog with a closed-form integral — no marching — so a valley fills and a hilltop clears, the horizon turns hazy while the zenith stays clear, and looking toward the sun the haze takes the sun's colour; sky pixels run through the same formula with a very long ray, and `skyFog` sets how much haze the sky keeps. `lightShafts` marches each pixel toward the sun's place on screen and counts how much of the way is open sky, leaving rays through whatever stands in front of the sun. The sun's direction is set on the effects (azimuth and elevation), not read from a light. Neither is a shadowed volume: fog is lit evenly. Both run on WebGL2 and WebGPU; with an output transform of None, a floor fully taken by the fog reads exactly the authored colour on both. Height Fog and Light Shafts follow the scene's own sun, and Height Fog can carry the sun's shadows as volumetric light. `followSun` (on by default) takes the sun from the first directional light that shines; `volumetric` walks the air in 24 steps against the sun's shadow map, so shadows are dark fog and gaps between them beams. A post-process shader can ask for the light block and shadow atlas with `#pragma lights`.- **Screen Space Reflections.** A Screen Space Reflections post-process effect mirrors props in floors. Add `ssr` to a `PostProcessVolume`: with no G-buffer, the surface normal is rebuilt from the depth buffer, the reflected ray is marched through the world and projected back to the screen at every step, and a step landing just behind the visible surface is a hit, refined by bisection. The reflection is blended over the pixel by a Schlick Fresnel term — faint face-on, strong at a grazing angle — and blurred by how far the ray travelled, which stands in for roughness. `intensity`, `maxDistance`, `thickness` and `floorBias` are the settings; `floorBias` at 1 lets only up-facing surfaces reflect, since the chain does not know a material's roughness. What is off screen or in the sky is not reflected; the pixel is left as it was. It reads the same depth buffer as ambient occlusion, runs on WebGL2 and WebGPU alike, and its per-pixel start offset is meant to be averaged away by `taa`. Verified in the editor on a lit scene with both backends: the props appear in the floor they stand on and nothing else on screen changes.- **Temporal Anti-Aliasing.** A Temporal Anti-Aliasing post-process effect smooths edges across frames. Add `taa` to a `PostProcessVolume` and the engine shifts the scene's picture by a different sub-pixel amount each frame (eight positions, repeating), keeps the effect's last output as its history, and blends the two — reaching what multisampling cannot: shader aliasing and thin geometry. Where a pixel was last frame comes from the depth buffer and the previous camera, so a moving camera keeps its history; the history is clipped to the colours around it, so what no longer matches is dropped rather than smeared, and each camera keeps a history of its own. One `blend` setting says how much of each frame is new. Measured in the editor on a lit scene with multisampling off, in-between edge pixels went from 2% of edge pixels to 43% on WebGL2 and 44% on WebGPU, still frames held still, and a picture taken mid-slide of the camera matched the plain one to within a fraction of a level. Objects that move by themselves are not tracked — they are handled by the clip, so fast movers can look slightly soft. Temporal Anti-Aliasing now follows meshes that move by themselves, from a motion pass that draws only what moved, so a thin fast object keeps its contrast. Moving meshes are drawn a second time into a target of their own that records how far each pixel travelled (an RGBA32F target, only on devices with float render targets), and the effect follows that where it is the surface the scene shows; `Object Motion` at 0 trusts the camera alone. Skinned meshes are followed by their bones, from the palette they were last drawn with.- **Smaller meshes on disk.** Newly imported meshes are about 9% smaller on disk. A mesh whose indices all fit in 16 bits is now written with 16-bit indices (`.esmesh` version 4), half the index bytes, and read back as 32-bit so nothing downstream changes: the renderer, the lightmap and decal bakers and static batching see the same indices as before. A mesh that needs 32 bits is written exactly as before, on the version every earlier reader knows, and files written before this change still load. Measured on the Bistro meshes (1143 files, 116 MB), re-encoding saves 10.4 MB; existing `.esmesh` files are not rewritten until the model is re-imported.diff --git a/desktop b/desktopindex 1b9187b1b..c99c43169 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 1b9187b1b90ee1e20fb22bf0c2492f5876b94c34+Subproject commit c99c431698cce68db37bc2a037ca0a456f9f2e67diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdxindex b72a05574..11179eb34 100644--- a/docs/astro/src/content/docs/graphics/post-processing.mdx+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx@@ -113,14 +113,21 @@ formula makes the **horizon hazy and the zenith clear**, because a ray skimmingthe thick part and one aimed up leaves it at once. Sky pixels have no surface to measure to, so theytake the formula with a very long ray; `skyFog` says how much of that haze the sky keeps. Looking towardthe sun the haze takes `sunColor`: give it the sun's direction as `sunAzimuth` (degrees from +Z toward-+X) and `sunElevation` (degrees above the horizon) — these are settings of the effect, not read from-a `Light`, so keep them in step with the sun you placed.++X) and `sunElevation` (degrees above the horizon). With `followSun` on (the default) the effect+ignores them and takes the sun from the scene: the first directional light that shines, its direction+and its colour, so a sun that turns takes its haze with it; the two angles are what a scene with no+directional light falls back to.++`volumetric` makes the haze carry the sun's shadows. The air between the camera and each surface is walked in+24 steps against the sun's shadow map, and every step that stands in light scatters some of it toward the+eye — so a building's shadow is dark fog and the gap between two of them a beam. It needs a directional light+that casts shadows (the effect reads the same atlas the meshes receive from), and `volumeRange` says how far+from the camera the air is walked; beyond it the fog still dims but takes no shafts.`lightShafts` finds the sun's light through whatever stands in front of it, in screen space: each pixelmarches toward the sun's place on screen and counts how much of the way is open sky. It needs thesun on screen or just off it, and only what the depth buffer holds can cast a shaft. Together the two-give the haze-and-rays look of a low sun; neither is a shadowed volume — fog does not know where a-shadow map says the light is blocked, so the fog itself is lit evenly.+give the haze-and-rays look of a low sun; `lightShafts` is still screen-space; the shadowed volume is `heightFog`'s `volumetric`.Fog colours are authored as **sRGB** and converted for a linear project, the way a clear colourand a light colour are, so the colour you pick is the colour a fully fogged surface shows.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdxindex 2cf1a3b55..a682acb2b 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/post-processing.mdx@@ -90,11 +90,17 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess闭式解——不用步进——而同一个公式让**地平线朦胧、天顶清澈**:贴着地面的射线一直待在浓处,朝上的射线立刻离开。天空像素没有可测量的表面,所以它们用一条很长的射线代入公式;`skyFog` 决定天空保留多少这样的雾。朝向太阳看时雾带上 `sunColor`:用 `sunAzimuth`(从 +Z 向 +X 的角度)和 `sunElevation`(地平线以上的-角度)给出太阳方向——它们是这个效果自己的设置,不是从 `Light` 读的,所以要和你放的太阳保持一致。+角度)给出太阳方向。`followSun` 开着(默认)时效果忽略这两个角度,从场景里取太阳:第一盏有光的方向光,+它的方向和颜色,所以太阳转动,雾霾跟着转;两个角度只是场景没有方向光时的退路。++`volumetric` 让雾霾带上太阳的阴影。相机到每个表面之间的空气被分成 24 步,对着太阳的阴影贴图走一遍,+每一步站在光里的就把一部分光散射向眼睛——所以一栋楼的影子是暗的雾,两栋楼之间的缝是一道光束。它需要+一盏投射阴影的方向光(效果读的是网格接收阴影用的同一张图集),`volumeRange` 说空气从相机起走多远;+超出之后雾仍然让画面变暗,但不再有光束。`lightShafts` 在屏幕空间里找出太阳光穿过前方遮挡物的样子:每个像素朝太阳在屏幕上的位置步进,数这一路有多少是开阔天空。太阳需要在屏幕上或刚好在屏幕外,而且只有深度缓冲里有的东西才能投出光束。两者配合出-低角度太阳的"雾加光束"的样子;都不是带阴影的体积——雾不知道阴影贴图说光在哪里被挡住,所以雾本身是均匀被照亮的。+低角度太阳的"雾加光束"的样子;`lightShafts` 仍是屏幕空间的,带阴影的体积光是 `heightFog` 的 `volumetric`。雾的颜色按 **sRGB** 书写,线性项目里会被转换,和清屏色、灯光色一样,所以你选的颜色就是完全被雾吞没的表面显示的颜色。diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.tsindex cda3054cd..3c09fca2f 100644--- a/sdk/src/postprocess/effects.ts+++ b/sdk/src/postprocess/effects.ts@@ -247,13 +247,22 @@ registerEffect({{ name: 'u_baseHeight', label: 'Base Height', min: -1000, max: 5000, step: 10, defaultValue: 0 },{ name: 'u_startDistance', label: 'Start Distance', min: 0, max: 3000, step: 10, defaultValue: 0 },{ name: 'u_maxOpacity', label: 'Max Opacity', min: 0, max: 1, step: 0.01, defaultValue: 1 },- // Where the sun is, to colour the haze toward it: degrees from +Z toward +X, and above the horizon.+ // 1: the sun is the scene's own directional light — its direction and colour — and the two angles below are+ // only what a scene with no sun falls back to. 0: the angles are the sun.+ { name: 'u_followSun', label: 'Follow Scene Sun', min: 0, max: 1, step: 1, defaultValue: 1, neutralValue: 1 },+ // Where the sun is when it is not followed, to colour the haze toward it: degrees from +Z toward +X, and above the horizon.{ name: 'u_sunAzimuth', label: 'Sun Azimuth', min: 0, max: 360, step: 1, defaultValue: 40 },{ name: 'u_sunElevation', label: 'Sun Elevation', min: -10, max: 90, step: 1, defaultValue: 25 },{ name: 'u_inscatter', label: 'Sun Glow', min: 0, max: 2, step: 0.01, defaultValue: 0.6, neutralValue: 0 },{ name: 'u_sunExponent', label: 'Glow Sharpness', min: 1, max: 64, step: 1, defaultValue: 8 },// How much of the sky takes the horizon haze; 0 leaves the sky untouched.{ name: 'u_skyFog', label: 'Sky Haze', min: 0, max: 1, step: 0.01, defaultValue: 0.8, neutralValue: 0 },+ // How much of the sun's light through the haze comes from walking the air against the shadow map, so a+ // building's shadow is dark fog and the gap between two of them a beam. 0 is the glow alone; it needs a+ // directional light that casts a shadow, and costs 24 taps a pixel.+ { name: 'u_volumetric', label: 'Volumetric Light', min: 0, max: 1, step: 0.01, defaultValue: 0, neutralValue: 0 },+ // How far from the camera the air is walked: past it the fog still dims, but takes no shafts.+ { name: 'u_volumeRange', label: 'Volumetric Range', min: 100, max: 30000, step: 100, defaultValue: 3000 },],colors: [{ name: 'u_fogColor', label: 'Colour', defaultValue: { r: 0.62, g: 0.7, b: 0.8, a: 1 } },@@ -267,6 +276,7 @@ registerEffect({factory: () => postProcessEffects.createLightShafts(),uniforms: [{ name: 'u_intensity', label: 'Intensity', min: 0, max: 3, step: 0.01, defaultValue: 0.6, neutralValue: 0 },+ { name: 'u_followSun', label: 'Follow Scene Sun', min: 0, max: 1, step: 1, defaultValue: 1, neutralValue: 1 },{ name: 'u_sunAzimuth', label: 'Sun Azimuth', min: 0, max: 360, step: 1, defaultValue: 40 },{ name: 'u_sunElevation', label: 'Sun Elevation', min: -10, max: 90, step: 1, defaultValue: 25 },// Per step of the march: lower fades the shafts sooner along their length.diff --git a/sdk/src/postprocess/postProcessEffects.ts b/sdk/src/postprocess/postProcessEffects.tsindex 710d15c2d..315da7aad 100644--- a/sdk/src/postprocess/postProcessEffects.ts+++ b/sdk/src/postprocess/postProcessEffects.ts@@ -1481,6 +1481,10 @@ fn depthAt(texel : vec2i, size : vec2i) -> f32 {#pragma param u_inscatter float default(0.6) range(0,2)#pragma param u_sunExponent float default(8) range(1,64)#pragma param u_skyFog float default(0.8) range(0,1)+#pragma param u_followSun float default(1) range(0,1)+#pragma param u_volumetric float default(0) range(0,1)+#pragma param u_volumeRange float default(3000) range(100,30000)+#pragma lights#pragma fragmentprecision highp float;@@ -1491,6 +1495,16 @@ uniform highp sampler2D u_sceneDepth;out vec4 fragColor;const float FAR_RAY = 100000.0;+const int VOLUME_STEPS = 24;++float ign(vec2 p) {+ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));+}+/// How much of a ray's light a particle scatters toward the viewer: forward, the way fog glows around the sun.+float phaseHG(float cosine) {+ const float g = 0.55;+ return (1.0 - g * g) / pow(max(1.0 + g * g - 2.0 * g * cosine, 1e-3), 1.5) * 0.25;+}/// What the exponential density integrates to along a ray: the eye's density, the length,/// and the term for how fast the ray leaves the fog. Written so a level ray (no climb)@@ -1521,9 +1535,15 @@ void main() {float tau = opticalDepth(entry.y + dir.y * u_startDistance, dir.y, effective);float amount = (1.0 - exp(-tau)) * u_maxOpacity * (sky ? u_skyFog : 1.0);+ // The sun is the scene's own directional light unless the effect is told to ignore it: where it stands and+ // what colour it is come from the light block, so a sun that moves takes its haze with it.+ vec4 lightDir, lightColor;+ ivec2 tiles;+ findSun(lightDir, lightColor, tiles);+ bool follow = u_followSun > 0.5 && lightDir.w > 0.5;float az = radians(u_sunAzimuth);float el = radians(u_sunElevation);- vec3 sun = vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az));+ vec3 sun = follow ? lightDir.xyz : vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az));float glow = pow(max(dot(dir, sun), 0.0), u_sunExponent);vec3 fog = u_fogColor.rgb;vec3 sunTint = u_sunColor.rgb;@@ -1531,13 +1551,46 @@ void main() {fog = srgbToLinear(fog);sunTint = srgbToLinear(sunTint);#endif- vec3 colour = mix(fog, sunTint, clamp(glow * u_inscatter, 0.0, 1.0));- fragColor = vec4(mix(src.rgb, colour, clamp(amount, 0.0, 1.0)), src.a);+ // The light's own colour is already in the pipeline's space; only its hue is wanted, not its strength.+ if (follow) sunTint = lightColor.rgb / max(max(lightColor.r, lightColor.g), max(lightColor.b, 1e-3));+ float shaped = u_volumetric > 0.0 ? glow * (1.0 - u_volumetric) : glow;+ vec3 colour = mix(fog, sunTint, clamp(shaped * u_inscatter, 0.0, 1.0));+ vec3 result = mix(src.rgb, colour, clamp(amount, 0.0, 1.0));++ // The sun's light through the haze, where the shadow map says it gets through: the air between the camera and+ // the surface is walked in steps, and each one that stands in light adds what it scatters toward the eye.+ if (u_volumetric > 0.0 && follow) {+ float range = min(len, u_volumeRange);+ float span = max(range - u_startDistance, 0.0);+ float ds = span / float(VOLUME_STEPS);+ float jitter = ign(gl_FragCoord.xy);+ float transmit = 1.0;+ float lit = 0.0;+ for (int i = 0; i < VOLUME_STEPS; ++i) {+ float t = u_startDistance + (float(i) + jitter) * ds;+ vec3 p = entry + dir * t;+ float dens = u_density * exp(clamp(-u_heightFalloff * (p.y - u_baseHeight), -60.0, 60.0));+ lit += transmit * dens * ds * sunVisibility(p, tiles.x, tiles.y);+ transmit *= exp(-dens * ds);+ }+ float strength = clamp(lightColor.a, 0.0, 8.0) * 0.5;+ result += sunTint * lit * phaseHG(dot(dir, sun)) * u_inscatter * u_volumetric * strength * (sky ? u_skyFog : 1.0);+ }+ fragColor = vec4(result, src.a);}#pragma end#pragma fragment wgslconst FAR_RAY : f32 = 100000.0;+const VOLUME_STEPS : i32 = 24;++fn ign(p : vec2f) -> f32 {+ return fract(52.9829189 * fract(dot(p, vec2f(0.06711056, 0.00583715))));+}+fn phaseHG(cosine : f32) -> f32 {+ let g = 0.55;+ return (1.0 - g * g) / pow(max(1.0 + g * g - 2.0 * g * cosine, 1e-3), 1.5) * 0.25;+}fn opticalDepth(eyeY : f32, dirY : f32, len : f32) -> f32 {let k = mc.u_heightFalloff;@@ -1568,18 +1621,47 @@ fn opticalDepth(eyeY : f32, dirY : f32, len : f32) -> f32 {var amount = (1.0 - exp(-tau)) * mc.u_maxOpacity;if (sky) { amount = amount * mc.u_skyFog; }+ // See the GLSL twin: the scene's own sun unless told not to follow it.+ let found = findSun();+ let follow = mc.u_followSun > 0.5 && found.dir.w > 0.5;let az = radians(mc.u_sunAzimuth);let el = radians(mc.u_sunElevation);- let sun = vec3f(cos(el) * sin(az), sin(el), cos(el) * cos(az));- let glow = pow(max(dot(dir, sun), 0.0), mc.u_sunExponent);+ var sun = vec3f(cos(el) * sin(az), sin(el), cos(el) * cos(az));+ if (follow) { sun = found.dir.xyz; }+ var shaped = dot(dir, sun);+ let glow = pow(max(shaped, 0.0), mc.u_sunExponent);var fog = mc.u_fogColor.rgb;var sunTint = mc.u_sunColor.rgb;#ifdef ES_LINEARfog = srgbToLinear(fog);sunTint = srgbToLinear(sunTint);#endif- let colour = mix(fog, sunTint, clamp(glow * mc.u_inscatter, 0.0, 1.0));- return vec4f(mix(src.rgb, colour, clamp(amount, 0.0, 1.0)), src.a);+ if (follow) { sunTint = found.color.rgb / max(max(found.color.r, found.color.g), max(found.color.b, 1e-3)); }+ var glowShare = glow;+ if (mc.u_volumetric > 0.0) { glowShare = glow * (1.0 - mc.u_volumetric); }+ let colour = mix(fog, sunTint, clamp(glowShare * mc.u_inscatter, 0.0, 1.0));+ var result = mix(src.rgb, colour, clamp(amount, 0.0, 1.0));++ if (mc.u_volumetric > 0.0 && follow) {+ let range = min(len, mc.u_volumeRange);+ let span = max(range - mc.u_startDistance, 0.0);+ let ds = span / f32(VOLUME_STEPS);+ let jitter = ign(v.pos.xy);+ var transmit = 1.0;+ var lit = 0.0;+ for (var i : i32 = 0; i < VOLUME_STEPS; i = i + 1) {+ let t = mc.u_startDistance + (f32(i) + jitter) * ds;+ let p = entry + dir * t;+ let dens = mc.u_density * exp(clamp(-mc.u_heightFalloff * (p.y - mc.u_baseHeight), -60.0, 60.0));+ lit = lit + transmit * dens * ds * sunVisibility(p, found.tiles.x, found.tiles.y);+ transmit = transmit * exp(-dens * ds);+ }+ let strength = clamp(found.color.a, 0.0, 8.0) * 0.5;+ var skyShare = 1.0;+ if (sky) { skyShare = mc.u_skyFog; }+ result = result + sunTint * lit * phaseHG(dot(dir, sun)) * mc.u_inscatter * mc.u_volumetric * strength * skyShare;+ }+ return vec4f(result, src.a);}#pragma end`;@@ -1607,6 +1689,8 @@ fn opticalDepth(eyeY : f32, dirY : f32, len : f32) -> f32 {#pragma param u_sunElevation float default(25) range(-10,90)#pragma param u_decay float default(0.96) range(0.8,1)#pragma param u_reach float default(0.6) range(0.1,1)+#pragma param u_followSun float default(1) range(0,1)+#pragma lights#pragma fragmentprecision highp float;@@ -1624,9 +1708,13 @@ float ign(vec2 p) {void main() {vec4 src = texture(u_texture, v_texCoord);+ vec4 lightDir, lightColor;+ ivec2 tiles;+ findSun(lightDir, lightColor, tiles);+ bool follow = u_followSun > 0.5 && lightDir.w > 0.5;float az = radians(u_sunAzimuth);float el = radians(u_sunElevation);- vec3 sun = vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az));+ vec3 sun = follow ? lightDir.xyz : vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az));vec3 eye = worldFromDepth(v_texCoord, 0.0);vec4 clip = u_projection * vec4(eye + sun * 10000.0, 1.0);// Behind the camera there is no screen position to march toward.@@ -1656,6 +1744,7 @@ void main() {#ifdef ES_LINEARtint = srgbToLinear(tint);#endif+ if (follow) tint = lightColor.rgb / max(max(lightColor.r, lightColor.g), max(lightColor.b, 1e-3));fragColor = vec4(src.rgb + tint * light * falloff * u_intensity, src.a);}#pragma end@@ -1669,9 +1758,12 @@ fn ign(p : vec2f) -> f32 {@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {let src = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);+ let found = findSun();+ let follow = mc.u_followSun > 0.5 && found.dir.w > 0.5;let az = radians(mc.u_sunAzimuth);let el = radians(mc.u_sunElevation);- let sun = vec3f(cos(el) * sin(az), sin(el), cos(el) * cos(az));+ var sun = vec3f(cos(el) * sin(az), sin(el), cos(el) * cos(az));+ if (follow) { sun = found.dir.xyz; }let eye = worldFromDepth(v.v_texCoord, 0.0);let clip = frame.projection * vec4f(eye + sun * 10000.0, 1.0);if (clip.w <= 1e-4) { return src; }@@ -1700,6 +1792,7 @@ fn ign(p : vec2f) -> f32 {#ifdef ES_LINEARtint = srgbToLinear(tint);#endif+ if (follow) { tint = found.color.rgb / max(max(found.color.r, found.color.g), max(found.color.b, 1e-3)); }return vec4f(src.rgb + tint * light * falloff * mc.u_intensity, src.a);}#pragma enddiff --git a/src/esengine/bindings/MaterialBindings.cpp b/src/esengine/bindings/MaterialBindings.cppindex 2af997aed..0415319ec 100644--- a/src/esengine/bindings/MaterialBindings.cpp+++ b/src/esengine/bindings/MaterialBindings.cpp@@ -48,6 +48,7 @@ static MaterialUniformLayout buildMaterialLayout(const resource::ParsedShader& playout.blockSize = parsed.materialBlockSize;layout.coverageParam = parsed.coverageParam;layout.usesGBuffer = parsed.usesGBuffer;+ layout.usesLights = parsed.usesLights;layout.vertexBounds = parsed.vertexBounds;layout.vertexHook = !parsed.vertexHook.empty();for (const auto& p : parsed.properties) {diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cppindex d336eee78..0c53e8108 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp@@ -290,6 +290,11 @@ bool PostProcessPipeline::passHasTexture(const PostProcessPass& pass, const charreturn false;}+bool PostProcessPipeline::passUsesLights(const PostProcessPass& pass) {+ const MaterialUniformLayout* layout = context_.materials().layoutFor(pass.shader);+ return layout && layout->usesLights;+}+bool PostProcessPipeline::passIsTemporal(const PostProcessPass& pass) {return passHasTexture(pass, "u_history");}@@ -629,6 +634,9 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContexif (shader->hasUniform("u_gbuffer")) {shader->setUniform("u_gbuffer", static_cast<i32>(kGBufferUnit));}+ if (shader->hasUniform("u_shadowMap")) {+ shader->setUniform("u_shadowMap", static_cast<i32>(SHADOW_MAP_TEXTURE_UNIT));+ }}// #pragma-param effects: params ride the reflected MaterialConstants block@@ -644,6 +652,12 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContex}// An effect that reflects the environment declares its parameters, and takes them from the// light block the scene was drawn with: how the atlas is laid out, how bright it is, how far the sky has turned.+ if (layout && layout->usesLights) {+ // The block the scene was lit with, bound again: the passes between have no claim on its slot, but a+ // chain is not the place to find out. And the atlas on the unit the Lit shaders read it from.+ context_.lights().uploadAndBind();+ if (shadow_texture_ != 0) device->bindTexture(SHADOW_MAP_TEXTURE_UNIT, TextureHandle{shadow_texture_});+ }if (layout && layout->find("u_envParams")) {const LightConstants& lights = context_.lights().data();pass.vec4Uniforms["u_envParams"] = lights.envParams;@@ -832,6 +846,9 @@ void PostProcessPipeline::runChain(std::vector<PostProcessPass>& passes, rg::Resif (velocity_active_ && velocity_resource_ != rg::kNoResource && passHasTexture(pass, "u_velocity")) {node.dependencies.push_back(velocity_resource_);}+ if (shadow_resource_ != rg::kNoResource && passUsesLights(pass)) {+ node.dependencies.push_back(shadow_resource_);+ }// The last pass feeds the blit, which copies into the output rect at the// chain's size — so it draws full-size whatever fraction it asked for.rg::TargetDesc writeDesc = (i == lastEnabled) ? blitDesc : desc;diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hppindex 4f8a56e19..5374a26ac 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp@@ -267,6 +267,17 @@ public:*/void setEnvironmentTexture(u32 glTextureId) { environment_texture_ = glTextureId; }+ /**+ * @brief The frame's shadow atlas, for an effect that asks whether a point of air is in the sun (`#pragma lights`).+ *+ * @details The atlas is a graph resource the scene pass names as a dependency; an effect that reads it names it+ * too, or the graph would hand it back to the pool before the effect ran. 0 / kNoResource = no map.+ */+ void setShadowAtlas(u32 glTextureId, rg::ResourceId resource) {+ shadow_texture_ = glTextureId;+ shadow_resource_ = resource;+ }+/*** @brief Starts a frame of the temporal view @p key, and answers how far to shift it.*@@ -548,10 +559,13 @@ private:std::unordered_map<u64, TemporalState> temporal_;u64 temporalKey_ = 0;bool passIsTemporal(const PostProcessPass& pass);+ bool passUsesLights(const PostProcessPass& pass);/// Some enabled pass of the chain reads the surface record.bool passesWantGBuffer();bool scene_gbuffer_ = false;u32 environment_texture_ = 0;+ u32 shadow_texture_ = 0;+ rg::ResourceId shadow_resource_ = rg::kNoResource;/// The motion pass's target, kept across frames for its size, and whether this frame drew into it.Unique<Framebuffer> velocity_fbo_;rg::ResourceId velocity_resource_ = rg::kNoResource;diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex ded1ecb60..4ff577fe1 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -652,6 +652,7 @@ void RenderFrame::end() {if (usePostProcess) {#ifdef ES_ENABLE_POSTPROCESS+ post_process_->setShadowAtlas(shadow_texture_id_, shadow_resource_);post_process_->declareChain();#endif}diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex d546ec9f0..50e0be80f 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -94,6 +94,8 @@ struct MaterialUniformLayout {std::string coverageParam;/// The shader reads the scene's surface record (ParsedShader::usesGBuffer).bool usesGBuffer = false;+ /// The shader reads the frame's light block and shadow atlas (ParsedShader::usesLights).+ bool usesLights = false;/// What the shader's vertex hook can move a vertex by (ParsedShader::vertexBounds), and whether it/// has a hook at all — culling grows a mesh's box by the first, and the shadow pass builds a/// program of its own for the second.diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 2f237ce77..1fac5ef70 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -699,6 +699,11 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeRcontinue;}+ if (directive == "lights") {+ result.usesLights = true;+ continue;+ }+if (directive == "vertexbounds") {// How far the vertex hook may move a vertex, in the mesh's local units.result.vertexBounds = std::strtof(argument.c_str(), nullptr);@@ -1111,6 +1116,70 @@ fn pbrNeutral(color : vec3f) -> vec3f {})";+// The light block and the shadow map as a fullscreen pass sees them: the same block the Lit shaders read, the atlas on+// unit 2 where a pass has nothing else, and the two questions an effect asks of them — which light is the sun, and is+// this point of air in its light. One tap, no filtering: a fog sample is not a surface.+const char* kPostLightHeaderWGSL = R"(struct Light { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f, shadowMap : vec4f, falloff : vec4f };+struct LightConstants {+ u_ambient : vec4f,+ u_lights : array<Light, 16>,+ u_mask2DRect : vec4f,+ u_shadowMatrix : array<mat4x4f, 16>,+ u_shadowTile : array<vec4f, 16>,+ u_shadowParams : vec4f,+ u_envIrradiance : array<vec4f, 9>,+ u_envParams : vec4f,+ u_envTint : vec4f,+ u_reflParams : vec4f,+ u_reflBox : array<vec4f, 30>,+};+@group(0) @binding(2) var<uniform> lc : LightConstants;+fn unpackDepth(c : vec3f) -> f32 {+ return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));+}+// The first directional light that shines: xyz = where it stands in the sky, w = 1 (0 = none),+// color = its colour and strength, tiles = x first atlas tile, y how many.+struct Sun { dir : vec4f, color : vec4f, tiles : vec2i };+fn findSun() -> Sun {+ var s : Sun;+ s.dir = vec4f(0.0);+ s.color = vec4f(0.0);+ s.tiles = vec2i(0, 0);+ for (var i = 0; i < 16; i++) {+ let l = lc.u_lights[i];+ if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {+ s.dir = vec4f(-normalize(vec3f(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);+ s.color = l.color;+ s.tiles = vec2i(i32(l.shadowMap.x), i32(l.shadowMap.y));+ return s;+ }+ }+ return s;+}+fn sunVisibility(worldPos : vec3f, first : i32, count : i32) -> f32 {+ if (lc.u_shadowParams.x < 0.5 || count <= 0) { return 1.0; }+ for (var k = 0; k < 16; k++) {+ if (k >= count) { break; }+ let t = first + k;+ let m = lc.u_shadowMatrix[t];+ let c = m * vec4f(worldPos, 1.0);+ if (c.w <= 0.0) { continue; }+ let proj = c.xyz / c.w;+ let uv = proj.xy * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) { continue; }+ let rect = lc.u_shadowTile[t];+ // The tile and the square inside it are turned over on this backend, as in the Lit header.+ let base = vec2f(rect.x, 1.0 - rect.y - rect.z);+ let at = base + vec2f(uv.x, 1.0 - uv.y) * rect.z;+ let lo = base + lc.u_shadowParams.y * 0.5;+ let hi = base + rect.z - lc.u_shadowParams.y * 0.5;+ let d = unpackDepth(textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).rgb);+ return select(1.0, 0.0, d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025);+ }+ return 1.0;+}+)";+const char* kLitHeaderWGSL = R"(struct Light { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f, shadowMap : vec4f, falloff : vec4f };struct LightConstants {u_ambient : vec4f,@@ -1770,6 +1839,7 @@ ShaderParser::AssembledStage assembleWGSLStage(const ParsedShader& parsed,if (stage == ShaderStage::Fragment) {inject(wgslMaterialTextureDecls(parsed));if (lit) inject(kLitHeaderWGSL);+ if (parsed.domain == "PostProcess" && parsed.usesLights) inject(kPostLightHeaderWGSL);inject(kColorHelpersWGSL);}// The records, for a stage that names them — the same question, and the same@@ -2568,6 +2638,68 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& pheaderLines += countNewlines(kLitHeader);}+ // The same block for a fullscreen pass that asks for it, with the two questions an effect puts to it.+ if (stage == ShaderStage::Fragment && parsed.domain == "PostProcess" && parsed.usesLights) {+ static const char* kPostLightHeader =+ "struct Light { highp vec4 posDir; highp vec4 color; highp vec4 spot; highp vec4 shadow;"+ " highp vec4 shadowMap; highp vec4 falloff; };\n"+ "layout(std140) uniform LightConstants {\n"+ " highp vec4 u_ambient;\n"+ " Light u_lights[16];\n"+ " highp vec4 u_mask2DRect;\n"+ " highp mat4 u_shadowMatrix[16];\n"+ " highp vec4 u_shadowTile[16];\n"+ " highp vec4 u_shadowParams;\n"+ " highp vec4 u_envIrradiance[9];\n"+ " highp vec4 u_envParams;\n"+ " highp vec4 u_envTint;\n"+ " highp vec4 u_reflParams;\n"+ " highp vec4 u_reflBox[30];\n"+ "};\n"+ "uniform highp sampler2D u_shadowMap;\n"+ "highp float unpackDepth(in highp vec3 c) {\n"+ " return dot(c, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n"+ "}\n"+ // The first directional light that shines: dir.xyz = where it stands in the sky, dir.w = 1 (0 = none).+ "void findSun(out highp vec4 dir, out highp vec4 color, out ivec2 tiles) {\n"+ " dir = vec4(0.0);\n"+ " color = vec4(0.0);\n"+ " tiles = ivec2(0);\n"+ " for (int i = 0; i < 16; ++i) {\n"+ " Light l = u_lights[i];\n"+ " if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {\n"+ " dir = vec4(-normalize(vec3(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);\n"+ " color = l.color;\n"+ " tiles = ivec2(int(l.shadowMap.x), int(l.shadowMap.y));\n"+ " return;\n"+ " }\n"+ " }\n"+ "}\n"+ // One tap, no filtering: a sample of air is not a surface.+ "highp float sunVisibility(in highp vec3 worldPos, in int first, in int count) {\n"+ " if (u_shadowParams.x < 0.5 || count <= 0) return 1.0;\n"+ " for (int k = 0; k < 16; ++k) {\n"+ " if (k >= count) break;\n"+ " int t = first + k;\n"+ " highp mat4 m = u_shadowMatrix[t];\n"+ " highp vec4 c = m * vec4(worldPos, 1.0);\n"+ " if (c.w <= 0.0) continue;\n"+ " highp vec3 proj = c.xyz / c.w;\n"+ " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"+ " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) continue;\n"+ " highp vec4 rect = u_shadowTile[t];\n"+ " highp vec2 at = rect.xy + uv * rect.z;\n"+ " highp vec2 lo = rect.xy + u_shadowParams.y * 0.5;\n"+ " highp vec2 hi = rect.xy + rect.z - u_shadowParams.y * 0.5;\n"+ " highp float d = unpackDepth(texture(u_shadowMap, clamp(at, lo, hi)).rgb);\n"+ " return d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025 ? 0.0 : 1.0;\n"+ " }\n"+ " return 1.0;\n"+ "}\n";+ assembled << kPostLightHeader;+ headerLines += countNewlines(kPostLightHeader);+ }+if (!platform.empty()) {auto variantIt = parsed.variants.find(platform);if (variantIt != parsed.variants.end()) {diff --git a/src/esengine/resource/ShaderParser.hpp b/src/esengine/resource/ShaderParser.hppindex 114eba68a..75481ea41 100644--- a/src/esengine/resource/ShaderParser.hpp+++ b/src/esengine/resource/ShaderParser.hpp@@ -155,6 +155,10 @@ struct ParsedShader {/// `#pragma gbuffer`: a post-process shader reads the scene's surface record (normal, roughness,/// metalness) at unit kGBufferUnit, so the frame must draw one for it.bool usesGBuffer = false;+ /// `#pragma lights`: a post-process shader reads the frame's light block — which light is the sun, where it+ /// stands, and (through `sunVisibility`) whether the shadow map says a point of air is lit — so the pipeline+ /// binds the block and the shadow atlas for it.+ bool usesLights = false;/// `#pragma vertexoffset`: the body of `esMaterialVertex(inout local, inout localNormal, uv)`,/// run on a resident mesh's local-space vertex before it is posed and placed. It is the/// material's own, so the canonical mesh vertex stage calls it and a material without onediff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex a09df8625..4937fa18c 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2491,6 +2491,8 @@ export const NOTED = {{"note":"Temporal Anti-Aliasing now follows meshes that move by themselves, from a motion pass that draws only what moved, so a thin fast object keeps its contrast."},"feat(render): the motion pass follows skinned meshes by the palette their bones were last drawn with":{"note":"Skinned meshes are followed by their bones, from the palette they were last drawn with."},+ "feat(render): fog follows the scene's sun and can walk the air against its shadow map":+ {"note":"Height Fog and Light Shafts follow the scene's own sun, and Height Fog can carry the sun's shadows as volumetric light."},"feat(render): reflections no longer guess a surface, plain meshes record themselves, and what the ray never finds is the sky":{"note":"Screen-space reflections leave a surface that recorded nothing alone, plain meshes now record a rough dielectric, and a puddle reflects the sky and what lies off screen."},};