Skip to content

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

feat(render): reflections no longer guess a surface, plain meshes record themselves, and what the ray never finds is the sky

yhh6eccf9a326b0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 942d90490..5644fe4ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@ published separately; it ships inside the editor.
### Added
- **Quality levels are edited in Settings.** Settings → Project → Rendering edits each quality level, including which effects it runs. **Editing level** picks Low, Medium or High and the groups below — Rendering (render scale, minimum scale, MSAA), Shadows, Reflections and particles, Post-processing — show and change that level, so a level is read the way Unity's Quality page reads: a level, then its settings by subsystem. Post-processing lists every effect the engine has, ticked where the level runs it; an unticked one is skipped at that level wherever a camera's volume asks for it, with all of its passes. Device rules — the model, GPU, memory and core conditions Auto chooses a level by — are a table, shown when the mode is Auto, that says so on a row with no condition instead of dropping it while it is typed. Only what you change is saved to `project.esproject`, as a difference to that level, so an engine default that improves later still reaches a project that never touched it; a row's "changed" mark and reset follow the default of the level it is showing. The old per-level shadow distance rows are the Shadows group's Distance now. The effects a level leaves out had been matched by the prefix of a pass's name, which found none of Auto Exposure's passes; they are now matched by effect type. A new Quality Levels page in the performance docs describes it.
-- **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.
+- **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.
diff --git a/desktop b/desktop
index 32ad74459..32eda9eb2 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 32ad7445902c57140fd8b39b7e1bc1e5d89a484f
+Subproject commit 32eda9eb27ce8e285507bee8c2753d5a47bade0e
diff --git a/docs/astro/src/content/docs/graphics/post-processing.mdx b/docs/astro/src/content/docs/graphics/post-processing.mdx
index 4b8089dd3..785dd4e67 100644
--- a/docs/astro/src/content/docs/graphics/post-processing.mdx
+++ b/docs/astro/src/content/docs/graphics/post-processing.mdx
@@ -28,7 +28,7 @@ several can stack in one frame at no extra target cost beyond the passes.
| `autoExposure` | Eye adaptation: exposure follows how bright the picture is | `bias`, `speedUp`, `speedDown`, `minEV`, `maxEV` |
| `depthOfField` | Blur by distance from a focus | `focusDistance`, `focusRange`, `aperture`, `maxBlur` |
| `rain` | Falling rain, wet ground, puddles, ripples and splashes | `intensity`, `wetness`, `wind`, `speed`, `puddles`, `puddleScale` |
-| `ssr` | Screen-space reflections: props mirrored in the floor they stand on | `intensity`, `maxDistance`, `thickness`, `floorBias` |
+| `ssr` | Screen-space reflections: props mirrored in the floor they stand on | `intensity`, `maxDistance`, `thickness`, `floorBias`, `skyReflection` |
| `taa` | Temporal anti-aliasing: edges smoothed over several frames | `blend` |
| `lensDistortion` | Barrel / pincushion warp | `strength`, `zoom` |
| `pixelate` | Block quantization | `pixelSize` |
@@ -91,13 +91,14 @@ rotated per pixel, so it leaves a fine grain that `taa` averages away.
Some effects have to know what a surface IS, not only how it looks. An effect whose shader says `#pragma gbuffer` makes the
frame draw a second colour attachment beside the scene's, in the same pass and from the same shaders: **octahedral normal in
-`r` and `g`, roughness in `b`, metalness in `a`** (`a` is 0 where nothing wrote, and `0.25 + 0.75 × metalness`
+`r` and `g`, roughness in `b`, metalness in `a`** (`a` is 0 where nothing wrote, and `0.75 + 0.25 × metalness`, so an edge that multisampling averaged with an unwritten pixel (at most 0.5) is told from a surface
where something did), 8 bits a channel. The effect finds it at `u_gbuffer` (GLSL) or `t6` (WGSL, read with `textureLoad`).
It costs one extra RGBA8 target and one extra write per pixel, and only while an enabled effect asks: a frame with no such
effect has no attachment and compiles no variant. What writes it today is the built-in **Model** shader — what an imported
-glTF material becomes — which is roughness, metalness and normal map as the material says. A mesh drawn without a material, a sprite, a
-blended surface and a custom shader leave it at 0, and an effect must treat that as "unknown" and fall back, as `ssr` does.
+glTF material becomes, with roughness, metalness and normal map as the material says — and the engine's plain lit mesh, which records
+what it is: a rough dielectric. A sprite, a blended surface, an unlit mesh and a custom shader leave it at 0, and an effect must
+treat that as "unknown" and leave the pixel alone, as `ssr` does.
A shader of your own can write it: it is compiled with `ES_GBUFFER` defined when the pass has the attachment, and then declares
a second output (`layout(location = 1) out vec4`, or a struct return in WGSL) and writes the same encoding.
@@ -127,8 +128,7 @@ and a light colour are, so the colour you pick is the colour a fully fogged surf
### Screen-space reflections
`ssr` reflects what is on screen in the surfaces that face up: a wet street, a polished
-floor, a lake's edge. There is no G-buffer, so it works from what the chain already has — the
-surface normal is rebuilt from the depth buffer, the reflected ray is marched through the world
+floor, a lake's edge. The reflected ray is marched through the world
and projected back at every step, and a step that lands just behind what the depth buffer shows
is a hit. What it finds is blended over the pixel by a Schlick Fresnel term: faint face-on,
strong at a grazing angle, so the floor shines toward the horizon. A farther hit is blurred more,
@@ -139,10 +139,11 @@ surface's own normal (a normal map's detail, which depth cannot see), its roughn
reflects dimly and blurred, and one rougher than `maxRoughness` is skipped before the ray is marched, which is most of the
cost; a metal reflects nearly all it receives where a dielectric reflects 4% face-on. `wetness` makes ground
smoother (a film of water fills the pores), so it reflects as it gets wet, and puddles are mirrors. Where nothing wrote
-a record — a mesh with no material, a sprite — the depth normal stands, the surface is taken for a middling dielectric and
-`floorBias` decides what may reflect: at 1 only up-facing surfaces do, at 0 every surface by its Fresnel term alone.
-It cannot show what is off screen, behind another object or in the sky — there it leaves the pixel as it was, so
-it sits on top of the environment's own specular rather than replacing it. `maxDistance` is a
+a record — a sprite, a blended or unlit surface, a custom shader — nothing is guessed: the pixel is left as it was. `floorBias`
+(0 by default) can narrow what reflects further: at 1 only up-facing surfaces do.
+Where the ray leaves the picture or goes on to the sky, the surface still reflects the **environment** the frame's meshes
+reflect, at the sharpness its roughness gives; `skyReflection` says how much (0 turns it off). So a puddle shows the sky and
+what lies beyond the edge of the picture, not only the props on screen. `maxDistance` is a
world length; the step count is fixed, so a longer reach is a coarser march, and the per-pixel
start offset that hides the banding is what `taa` averages away — use them together.
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.mdx
index 2c948ad08..fe91aa4c4 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
@@ -27,7 +27,7 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
| `autoExposure` | 眼睛适应:曝光跟随画面亮度 | `bias`、`speedUp`、`speedDown`、`minEV`、`maxEV` |
| `depthOfField` | 按到焦点的距离模糊 | `focusDistance`、`focusRange`、`aperture`、`maxBlur` |
| `rain` | 下雨、潮湿的地面、水坑、涟漪与水花 | `intensity`、`wetness`、`wind`、`speed`、`puddles`、`puddleScale` |
-| `ssr` | 屏幕空间反射:道具映在它们所站的地面上 | `intensity`、`maxDistance`、`thickness`、`floorBias` |
+| `ssr` | 屏幕空间反射:道具映在它们所站的地面上 | `intensity`、`maxDistance`、`thickness`、`floorBias`、`skyReflection` |
| `taa` | 时间性抗锯齿:边缘跨多帧平滑 | `blend` |
| `lensDistortion` | 桶形 / 枕形畸变 | `strength`、`zoom` |
| `pixelate` | 块状量化 | `pixelSize` |
@@ -75,11 +75,11 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
有些效果必须知道表面**是什么**,而不只是它看起来怎样。着色器里写了 `#pragma gbuffer` 的效果会让这一帧在场景的颜色旁多画一个颜色附件,
同一个 pass、同样的着色器:**八面体法线在 `r`、`g`,粗糙度在 `b`,金属度在 `a`**(没写的地方 `a` 为 0,写了的地方是
-`0.25 + 0.75 × 金属度`),每通道 8 位。效果在 `u_gbuffer`(GLSL)或 `t6`(WGSL,用 `textureLoad` 读)处找到它。
+`0.75 + 0.25 × 金属度`,所以被多重采样与未写入像素平均过的边缘(最多 0.5)能和真正的表面区分开),每通道 8 位。效果在 `u_gbuffer`(GLSL)或 `t6`(WGSL,用 `textureLoad` 读)处找到它。
它多花一个 RGBA8 目标和每像素一次额外写入,而且只在有已启用的效果要它时才有:没有这种效果的帧没有附件,也不编译变体。
-目前写它的是内置的 **Model** 着色器——导入的 glTF 材质变成的就是它——粗糙度、金属度和法线贴图都按材质所说。没有材质的网格、精灵、
-混合表面和自定义着色器都留 0,效果必须把它当"未知"并回退,`ssr` 就是这样做的。你自己的着色器也可以写它:当 pass 有这个附件时,
+目前写它的是内置的 **Model** 着色器——导入的 glTF 材质变成的就是它,粗糙度、金属度和法线贴图都按材质所说——以及引擎自带的普通受光网格,它如实记录自己是什么:粗糙的电介质。
+精灵、混合表面、不受光网格和自定义着色器都留 0,效果必须把它当"未知"并保持像素不变,`ssr` 就是这样做的。你自己的着色器也可以写它:当 pass 有这个附件时,
编译会定义 `ES_GBUFFER`,然后声明第二个输出(`layout(location = 1) out vec4`,WGSL 里是返回结构体)并按同样的编码写入。
在 WebGL2 和 WebGPU 上,附件都与场景一起多重采样、一起解析。混合绘制从不写它——与背后那个平均过的法线谁也不是——场景自己的背景把它清成 0。
@@ -101,16 +101,14 @@ Estella 通过 ping-pong 帧缓冲运行全屏后处理。加一个 `PostProcess
### 屏幕空间反射
-`ssr` 把屏幕上已有的东西反射到朝上的表面里:湿街道、抛光地板、湖岸。没有 G-buffer,所以只用链路
-里已有的东西——法线由深度缓冲重建,反射射线在世界里步进、每一步投影回屏幕,落在深度缓冲所示表面
+`ssr` 把屏幕上已有的东西反射到朝上的表面里:湿街道、抛光地板、湖岸。反射射线在世界里步进、每一步投影回屏幕,落在深度缓冲所示表面
刚好后面的一步算命中。找到的颜色按 Schlick 菲涅尔项混到像素上:正对时很弱,掠射时很强,所以地面
越靠近地平线越亮。命中越远越模糊,这代替了粗糙度。
表面是什么来自 [G-buffer](#g-buffer):场景写了记录的地方,反射用表面自己的法线(法线贴图的细节,深度看不到)、粗糙度和金属度。
粗糙的表面反射暗而模糊,比 `maxRoughness` 更粗糙的表面在步进射线之前就被跳过,这是大头开销;金属几乎全部反射
-所得的光,而电介质正对时只反射 4%。`wetness` 让地面变光滑(水膜填满了孔隙),所以越湿越反光,水坑是镜子。没有写记录的地方——没有材质的网格、
-精灵——用深度法线,表面按中等电介质对待,由 `floorBias` 决定谁可以反射:为 1 时只有朝上的表面反射,为 0 时每个表面仅按菲涅尔项反射。
-它看不到屏幕外、被别的物体挡住的或天空里的东西——那里像素保持原样,所以它叠在环境自身的高光之上而不是取代它。`maxDistance` 是世界长度;步数固定,所以距离越长
+所得的光,而电介质正对时只反射 4%。`wetness` 让地面变光滑(水膜填满了孔隙),所以越湿越反光,水坑是镜子。没有写记录的地方——精灵、混合或不受光表面、自定义着色器——不做猜测:像素保持原样。`floorBias`(默认 0)可以进一步收窄谁反射:为 1 时只有朝上的表面反射。
+射线离开画面或射向天空的地方,表面仍然反射网格所反射的**环境**,清晰度由粗糙度决定;`skyReflection` 控制多少(0 关闭)。所以水坑映出天空和画面边缘之外的东西,而不只是屏幕上的道具。`maxDistance` 是世界长度;步数固定,所以距离越长
步进越粗,而用来藏起条带的逐像素起始偏移要靠 `taa` 平均掉——两者配合使用。
### 时间性抗锯齿
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 6aa745565..cacf0ad70 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -383,9 +383,9 @@ registerEffect({
{ name: 'u_maxDistance', label: 'Max Distance', min: 10, max: 3000, step: 10, defaultValue: 400 },
// How far behind a visible surface a ray may pass and still count as having hit it.
{ name: 'u_thickness', label: 'Thickness', min: 1, max: 200, step: 1, defaultValue: 12 },
- // 1 = only surfaces that face up reflect (wet ground, polished floors); 0 = every surface
- // reflects by its Fresnel term alone.
- { name: 'u_floorBias', label: 'Floor Bias', min: 0, max: 1, step: 0.01, defaultValue: 1 },
+ // 1 = only surfaces that face up reflect (wet ground, polished floors, and not the walls beside them);
+ // 0 = any surface smooth enough to show a reflection does.
+ { name: 'u_floorBias', label: 'Floor Bias', min: 0, max: 1, step: 0.01, defaultValue: 0 },
// Standing water: flat, and a mirror. Give it the same two numbers as the Rain effect's puddles
// and the pools it darkens are the pools that reflect.
{ name: 'u_puddles', label: 'Puddles', min: 0, max: 1, step: 0.01, defaultValue: 0, neutralValue: 0 },
@@ -394,6 +394,9 @@ registerEffect({
{ name: 'u_maxRoughness', label: 'Max Roughness', min: 0.05, max: 1, step: 0.01, defaultValue: 0.75 },
// How wet the ground is: wet is smoother, so it reflects. Give it the Rain effect's wetness.
{ name: 'u_wetness', label: 'Wetness', min: 0, max: 1, step: 0.01, defaultValue: 0, neutralValue: 0 },
+ // Where the ray finds nothing on screen, how much of the environment's reflection takes its place: the sky
+ // in a puddle, and what is past the edge of the picture.
+ { name: 'u_skyReflection', label: 'Sky Reflection', min: 0, max: 1, step: 0.01, defaultValue: 1, neutralValue: 0 },
],
});
diff --git a/sdk/src/postprocess/postProcessEffects.ts b/sdk/src/postprocess/postProcessEffects.ts
index cb3cf02a4..3d1f6ba15 100644
--- a/sdk/src/postprocess/postProcessEffects.ts
+++ b/sdk/src/postprocess/postProcessEffects.ts
@@ -114,7 +114,8 @@ fn puddleMask(xz : vec2f, coverage : f32, scale : f32) -> f32 {
/**
* Reading the scene's surface record, in both languages: what each pixel IS, as the scene's own shaders
* wrote it beside the colour — octahedral normal in rg, roughness in b, metalness in a (a is 0 where nothing
- * wrote, and 0.25 + 0.75 * metalness where something did). An effect that wants it says `#pragma gbuffer`,
+ * wrote, and 0.75 + 0.25 * metalness where something did, so that an edge multisampling averaged with an
+ * unwritten pixel — at most 0.5 — is told from a surface). An effect that wants it says `#pragma gbuffer`,
* which is what makes the frame draw one, and finds it at `u_gbuffer`.
*/
const GBUFFER_GLSL = `
@@ -122,14 +123,14 @@ struct Surface { vec3 normal; float roughness; float metallic; bool known; };
Surface readSurface(ivec2 t) {
vec4 g = texelFetch(u_gbuffer, t, 0);
Surface s;
- s.known = g.a > 0.01;
+ s.known = g.a > 0.7;
vec2 f = g.rg * 2.0 - 1.0;
vec3 n = vec3(f.x, f.y, 1.0 - abs(f.x) - abs(f.y));
float k = clamp(-n.z, 0.0, 1.0);
n.xy += vec2(n.x >= 0.0 ? -k : k, n.y >= 0.0 ? -k : k);
s.normal = normalize(n);
s.roughness = g.b;
- s.metallic = clamp((g.a - 0.25) / 0.75, 0.0, 1.0);
+ s.metallic = clamp((g.a - 0.75) / 0.25, 0.0, 1.0);
return s;
}`;
@@ -142,13 +143,95 @@ fn readSurface(t : vec2i) -> Surface {
let k = clamp(-n.z, 0.0, 1.0);
n = vec3f(n.x + select(k, -k, n.x >= 0.0), n.y + select(k, -k, n.y >= 0.0), n.z);
var s : Surface;
- s.known = g.a > 0.01;
+ s.known = g.a > 0.7;
s.normal = normalize(n);
s.roughness = g.b;
- s.metallic = clamp((g.a - 0.25) / 0.75, 0.0, 1.0);
+ s.metallic = clamp((g.a - 0.75) / 0.25, 0.0, 1.0);
return s;
}`;
+/**
+ * The frame's environment, sampled from an effect, in both languages: the same prefiltered octahedral atlas the
+ * meshes reflect, read at the sky's own column. This is the engine's `envSampleMip` and `envDirection` as
+ * the mesh shaders spell them (ShaderParser.cpp) — the atlas layout is the one fact they share, so a change
+ * to it is a change here too. The numbers it needs come in as params the pipeline fills from the frame's light
+ * block each frame (\`u_envParams\`: x = has a map, y = range, z = highest mip, w = face size; \`u_envTint\`:
+ * the sky's turn in alpha; \`u_reflParams\`: x = columns in the atlas).
+ */
+const ENV_GLSL = `
+vec3 envDirection(vec3 d) {
+ float a = -u_envTint.a;
+ float s = sin(a);
+ float c = cos(a);
+ return vec3(c * d.x + s * d.z, d.y, -s * d.x + c * d.z);
+}
+vec2 envOctahedral(vec3 d) {
+ vec2 p = d.xz / max(abs(d.x) + abs(d.y) + abs(d.z), 1e-6);
+ if (d.y < 0.0) {
+ p = (1.0 - abs(p.yx)) * vec2(p.x >= 0.0 ? 1.0 : -1.0, p.y >= 0.0 ? 1.0 : -1.0);
+ }
+ return p * 0.5 + 0.5;
+}
+vec3 envSkyMip(vec3 R, float mip) {
+ float face = u_envParams.w;
+ float size = face * exp2(-mip);
+ float yOff = 2.0 * face * (1.0 - exp2(-mip)) + 2.0 * mip;
+ float col = face + 2.0;
+ float atlasW = col * u_reflParams.x;
+ float atlasH = 2.0 * face * (1.0 - exp2(-(u_envParams.z + 1.0))) + 2.0 * (u_envParams.z + 1.0);
+ vec2 uv = envOctahedral(envDirection(R));
+ vec2 lo = vec2(0.5, yOff + 0.5);
+ vec2 hi = vec2(size + 1.5, yOff + size + 1.5);
+ vec2 px = clamp(vec2(1.0 + uv.x * size, yOff + 1.0 + uv.y * size), lo, hi);
+ vec4 t = textureLod(u_environment, px / vec2(atlasW, atlasH), 0.0);
+ return t.rgb * t.rgb * (t.a * t.a * u_envParams.y);
+}
+/// The sky's reflection along a direction at a roughness: two mips of the atlas blended, and tinted by the ambient
+/// light that owns the environment — what the mesh shaders add to the flat ambient term for a reflection.
+vec3 envSky(vec3 R, float roughness) {
+ float lod = clamp(roughness, 0.0, 1.0) * u_envParams.z;
+ float lo = floor(lod);
+ vec3 a = envSkyMip(R, lo);
+ vec3 b = envSkyMip(R, min(lo + 1.0, u_envParams.z));
+ return mix(a, b, lod - lo) * u_envTint.rgb;
+}`;
+
+const ENV_WGSL = `
+fn envDirection(d : vec3f) -> vec3f {
+ let a = -mc.u_envTint.a;
+ let s = sin(a);
+ let c = cos(a);
+ return vec3f(c * d.x + s * d.z, d.y, -s * d.x + c * d.z);
+}
+fn envOctahedral(d : vec3f) -> vec2f {
+ var p = d.xz / max(abs(d.x) + abs(d.y) + abs(d.z), 1e-6);
+ if (d.y < 0.0) {
+ p = (1.0 - abs(vec2f(p.y, p.x))) * vec2f(select(-1.0, 1.0, p.x >= 0.0), select(-1.0, 1.0, p.y >= 0.0));
+ }
+ return p * 0.5 + 0.5;
+}
+fn envSkyMip(R : vec3f, mip : f32) -> vec3f {
+ let face = mc.u_envParams.w;
+ let size = face * exp2(-mip);
+ let yOff = 2.0 * face * (1.0 - exp2(-mip)) + 2.0 * mip;
+ let col = face + 2.0;
+ let atlasW = col * mc.u_reflParams.x;
+ let atlasH = 2.0 * face * (1.0 - exp2(-(mc.u_envParams.z + 1.0))) + 2.0 * (mc.u_envParams.z + 1.0);
+ let uv = envOctahedral(envDirection(R));
+ let lo = vec2f(0.5, yOff + 0.5);
+ let hi = vec2f(size + 1.5, yOff + size + 1.5);
+ let px = clamp(vec2f(1.0 + uv.x * size, yOff + 1.0 + uv.y * size), lo, hi);
+ let t = textureSampleLevel(u_environment, u_environment_s, px / vec2f(atlasW, atlasH), 0.0);
+ return t.rgb * t.rgb * (t.a * t.a * mc.u_envParams.y);
+}
+fn envSky(R : vec3f, roughness : f32) -> vec3f {
+ let lod = clamp(roughness, 0.0, 1.0) * mc.u_envParams.z;
+ let lo = floor(lod);
+ let a = envSkyMip(R, lo);
+ let b = envSkyMip(R, min(lo + 1.0, mc.u_envParams.z));
+ return mix(a, b, lod - lo) * mc.u_envTint.rgb;
+}`;
+
export const postProcessEffects = {
createLutGrade(): ShaderHandle {
// True LUT color grading: a 2D-packed 32^3 LUT (1024x32 — 32 slices of
@@ -405,11 +488,16 @@ fn project(P : vec3f) -> vec3f {
#pragma param u_intensity float default(1) range(0,2)
#pragma param u_maxDistance float default(400) range(10,3000)
#pragma param u_thickness float default(12) range(1,200)
-#pragma param u_floorBias float default(1) range(0,1)
+#pragma param u_floorBias float default(0) range(0,1)
#pragma param u_puddles float default(0) range(0,1)
#pragma param u_puddleScale float default(350) range(40,2000)
#pragma param u_maxRoughness float default(0.75) range(0.05,1)
#pragma param u_wetness float default(0) range(0,1)
+#pragma param u_skyReflection float default(1) range(0,1)
+#pragma param u_envParams color default(0,0,0,0)
+#pragma param u_envTint color default(0,0,0,0)
+#pragma param u_reflParams color default(1,0,0,0)
+#pragma param u_environment texture default(black)
#pragma gbuffer
#pragma fragment
@@ -424,6 +512,7 @@ out vec4 fragColor;
${SSAO_GLSL}
${PUDDLE_GLSL}
${GBUFFER_GLSL}
+${ENV_GLSL}
${GLSL}
void main() {
@@ -450,19 +539,15 @@ void main() {
vec3 V = viewDirection(P);
if (dot(N, V) < 0.0) N = -N;
- // What the surface is, where the scene wrote it: its own normal (a normal map's detail, which depth
- // cannot see), how rough it is and whether it is metal. Where nothing wrote — a sprite, a draw
- // with a shader that has no record to give — the depth normal stands, and the surface is taken
- // for a middling dielectric, which is what reflecting it by Fresnel alone has always assumed.
+ // What the surface is, as the scene wrote it: its own normal (a normal map's detail, which depth
+ // cannot see), how rough it is and whether it is metal. Where nothing wrote — a sprite, a draw whose
+ // shader has no record to give — nothing is known of it, and a reflection of a guess is worse than none.
Surface sf = readSurface(c);
- float rough = 0.5;
- float metal = 0.0;
- if (sf.known) {
- N = sf.normal;
- if (dot(N, V) < 0.0) N = -N;
- rough = sf.roughness;
- metal = sf.metallic;
- }
+ if (!sf.known) { fragColor = scene; return; }
+ N = sf.normal;
+ if (dot(N, V) < 0.0) N = -N;
+ float rough = sf.roughness;
+ float metal = sf.metallic;
// Standing water is flat and mirror-like whatever the ground under it is: its normal is
// straight up, and a still surface reflects far more than the 4% a dry one does.
@@ -476,7 +561,7 @@ void main() {
rough = mix(rough, rough * 0.35, u_wetness * flatUp);
rough = mix(rough, 0.04, puddle);
// Too rough to show anything: skipped before the march, which is the whole cost.
- if (sf.known && rough > u_maxRoughness) { fragColor = scene; return; }
+ if (rough > u_maxRoughness) { fragColor = scene; return; }
// Fresnel at this angle, Schlick from the surface's own reflectance face-on: a dielectric's 4%, a
// metal's near-all. The floor mask keeps a surface nobody described from shining on every wall.
@@ -485,8 +570,9 @@ void main() {
float fresnel = f0 + (1.0 - f0) * pow(1.0 - cosT, 5.0);
fresnel = mix(fresnel, max(fresnel, 0.55), puddle);
// A rough surface's reflection is spread over the lobe and dimmer for it.
- float gloss = sf.known ? (1.0 - rough) * (1.0 - rough) : 1.0;
- float up = sf.known ? 1.0 : mix(1.0, smoothstep(0.55, 0.9, N.y), u_floorBias);
+ float gloss = (1.0 - rough) * (1.0 - rough);
+ // Optionally only what faces up reflects: a wet street and not the walls beside it.
+ float up = mix(1.0, smoothstep(0.55, 0.9, N.y), u_floorBias);
float weight = fresnel * up * gloss * u_intensity;
if (weight < 0.002) { fragColor = scene; return; }
@@ -544,7 +630,15 @@ void main() {
}
prevP = Q;
}
- fragColor = vec4(mix(scene.rgb, hitColor, clamp(weight * hit, 0.0, 1.0)), scene.a);
+ vec3 result = mix(scene.rgb, hitColor, clamp(weight * hit, 0.0, 1.0));
+ // Where the ray found nothing on screen — it left the picture, or went on to the sky — the surface still
+ // reflects what is there: the environment, at the sharpness its roughness gives. Without it a mirror
+ // (a puddle) would show the sky only where the scene had already painted a blurred copy of it.
+ if (u_envParams.x > 0.5 && u_skyReflection > 0.0) {
+ vec3 sky = envSky(R, rough);
+ result = mix(result, sky, clamp(weight * (1.0 - hit) * u_skyReflection, 0.0, 1.0));
+ }
+ fragColor = vec4(result, scene.a);
}
#pragma end
@@ -552,6 +646,7 @@ void main() {
${SSAO_WGSL}
${PUDDLE_WGSL}
${GBUFFER_WGSL}
+${ENV_WGSL}
${WGSL}
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
@@ -577,14 +672,11 @@ ${WGSL}
if (dot(N, V) < 0.0) { N = -N; }
let sf = readSurface(c);
- var rough = 0.5;
- var metal = 0.0;
- if (sf.known) {
- N = sf.normal;
- if (dot(N, V) < 0.0) { N = -N; }
- rough = sf.roughness;
- metal = sf.metallic;
- }
+ if (!sf.known) { return scene; }
+ N = sf.normal;
+ if (dot(N, V) < 0.0) { N = -N; }
+ var rough = sf.roughness;
+ let metal = sf.metallic;
let flatUp = smoothstep(0.86, 0.95, N.y);
var puddle = 0.0;
@@ -594,16 +686,14 @@ ${WGSL}
}
rough = mix(rough, rough * 0.35, mc.u_wetness * flatUp);
rough = mix(rough, 0.04, puddle);
- if (sf.known && rough > mc.u_maxRoughness) { return scene; }
+ if (rough > mc.u_maxRoughness) { return scene; }
let cosT = clamp(dot(N, V), 0.0, 1.0);
let f0 = mix(0.04, 0.9, metal);
var fresnel = f0 + (1.0 - f0) * pow(1.0 - cosT, 5.0);
fresnel = mix(fresnel, max(fresnel, 0.55), puddle);
- var gloss = 1.0;
- if (sf.known) { gloss = (1.0 - rough) * (1.0 - rough); }
- var up = 1.0;
- if (!sf.known) { up = mix(1.0, smoothstep(0.55, 0.9, N.y), mc.u_floorBias); }
+ let gloss = (1.0 - rough) * (1.0 - rough);
+ let up = mix(1.0, smoothstep(0.55, 0.9, N.y), mc.u_floorBias);
let weight = fresnel * up * gloss * mc.u_intensity;
if (weight < 0.002) { return scene; }
@@ -655,7 +745,12 @@ ${WGSL}
}
prevP = Q;
}
- return vec4f(mix(scene.rgb, hitColor, clamp(weight * hit, 0.0, 1.0)), scene.a);
+ var result = mix(scene.rgb, hitColor, vec3f(clamp(weight * hit, 0.0, 1.0)));
+ if (mc.u_envParams.x > 0.5 && mc.u_skyReflection > 0.0) {
+ let sky = envSky(R, rough);
+ result = mix(result, sky, vec3f(clamp(weight * (1.0 - hit) * mc.u_skyReflection, 0.0, 1.0)));
+ }
+ return vec4f(result, scene.a);
}
#pragma end
`;
diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.ts
index 8debd6269..7ebbc3fbd 100644
--- a/sdk/src/render/builtinShaders.ts
+++ b/sdk/src/render/builtinShaders.ts
@@ -456,8 +456,9 @@ void main() {
u_metallic * mr.b, roughness, 1.0, ao);
fragColor = vec4(lit + u_emissive.rgb * texture(u_emissiveMap, v_texCoord).rgb, alpha);
#ifdef ES_GBUFFER
- // Alpha says something was drawn here (0 is "nothing wrote"), and carries the metalness above a floor.
- fragSurface = vec4(packNormal(normalize(N)), roughness, 0.25 + 0.75 * clamp(u_metallic * mr.b, 0.0, 1.0));
+ // Alpha says something was drawn here (0 is "nothing wrote"), and carries the metalness above 0.75: a pixel that
+ // multisampling averaged with an unwritten one falls below it, and an effect can tell such an edge from a surface.
+ fragSurface = vec4(packNormal(normalize(N)), roughness, 0.75 + 0.25 * clamp(u_metallic * mr.b, 0.0, 1.0));
#endif
}
#pragma end
@@ -539,7 +540,7 @@ fn packNormal(n : vec3f) -> vec2f {
#ifdef ES_GBUFFER
var frag : FragOut;
frag.color = vec4f(lit + emit, alpha);
- frag.surface = vec4f(packNormal(normalize(N)), roughness, 0.25 + 0.75 * clamp(mc.u_metallic * mr.b, 0.0, 1.0));
+ frag.surface = vec4f(packNormal(normalize(N)), roughness, 0.75 + 0.25 * clamp(mc.u_metallic * mr.b, 0.0, 1.0));
return frag;
#else
return vec4f(lit + emit, alpha);
diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshader
index e5b8cc3b7..8978e06e3 100644
--- a/src/esengine/data/shaders/mesh.esshader
+++ b/src/esengine/data/shaders/mesh.esshader
@@ -223,7 +223,23 @@ uniform sampler2D u_texture;
uniform sampler2D u_normalMap;
#endif
+#ifdef ES_GBUFFER
+// The frame's second attachment beside the colour: what this surface IS (normal, roughness, metalness),
+// for the post effects that need to know. This shader's surface is the plain one — a rough dielectric —
+// which is a record like any other: "nothing reflects here" is an answer, and one a reflections effect
+// would otherwise have to guess.
+layout(location = 0) out vec4 fragColor;
+layout(location = 1) out vec4 fragSurface;
+
+vec2 packNormal(vec3 n) {
+ n /= (abs(n.x) + abs(n.y) + abs(n.z));
+ vec2 sgn = vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0);
+ vec2 e = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * sgn;
+ return e * 0.5 + 0.5;
+}
+#else
out vec4 fragColor;
+#endif
void main() {
#ifdef SHADOW_DEPTH
@@ -250,6 +266,9 @@ void main() {
vec3 shaded = applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),
0.0, 1.0, 1.0, 1.0);
fragColor = vec4(shaded, base.a);
+#ifdef ES_GBUFFER
+ fragSurface = vec4(packNormal(normalize(N)), 1.0, 0.75);
+#endif
#else
#ifdef MESH_LIGHTMAP
// Unlit AND lightmapped: the bake is the whole of this surface's light, not
@@ -449,7 +468,25 @@ struct VSOut {
@location(6) @interpolate(flat) v_probeSlot : f32,
};
+#ifdef ES_GBUFFER
+// What the frame's second attachment takes, beside the colour (see the GLSL twin).
+struct FragOut {
+ @location(0) color : vec4f,
+ @location(1) surface : vec4f,
+};
+
+fn packNormal(n : vec3f) -> vec2f {
+ let a = n / (abs(n.x) + abs(n.y) + abs(n.z));
+ let sgn = vec2f(select(-1.0, 1.0, a.x >= 0.0), select(-1.0, 1.0, a.y >= 0.0));
+ var e = a.xy;
+ if (a.z < 0.0) { e = (vec2f(1.0) - abs(a.yx)) * sgn; }
+ return e * 0.5 + 0.5;
+}
+
+@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> FragOut {
+#else
@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> @location(0) vec4f {
+#endif
// WGSL has no module varying: the entry point hands the injected header the
// slot its GLSL twin reads straight off one.
g_probeSlot = v.v_probeSlot;
@@ -476,7 +513,14 @@ struct VSOut {
// says nothing must still be lit the way the same mesh out of a glTF is.
let shaded = applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),
0.0, 1.0, 1.0, 1.0);
+#ifdef ES_GBUFFER
+ var frag : FragOut;
+ frag.color = vec4f(shaded, base.a);
+ frag.surface = vec4f(packNormal(normalize(N)), 1.0, 0.75);
+ return frag;
+#else
return vec4f(shaded, base.a);
+#endif
#else
#ifdef MESH_LIGHTMAP
// Unlit AND lightmapped: the bake is the whole of this surface's light.
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cpp
index ff734dac1..62fe451c9 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp
@@ -15,6 +15,7 @@
#include "./RenderContext.hpp"
#include "../rhi/GfxDevice.hpp"
#include "../store/MaterialConstants.hpp"
+#include "../store/LightConstants.hpp"
#include "../rhi/Shader.hpp"
#include "../rhi/ShaderEmbeds.generated.hpp"
#include "../../resource/ResourceManager.hpp"
@@ -590,6 +591,15 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContex
} else if (pass.feedback) {
if (auto it = feedback_.find(pass.historyKey); it != feedback_.end()) temporal = &it->second;
}
+ // 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->find("u_envParams")) {
+ const LightConstants& lights = context_.lights().data();
+ pass.vec4Uniforms["u_envParams"] = lights.envParams;
+ pass.vec4Uniforms["u_envTint"] = lights.envTint;
+ pass.vec4Uniforms["u_reflParams"] = lights.reflParams;
+ pass.paramDirty = true;
+ }
if (temporal && pass.temporal) {
// The previous picture's camera, as columns: a world point times it is where
// that point was one frame ago. Re-sent each frame because it is each frame's.
@@ -655,6 +665,9 @@ void PostProcessPipeline::renderPass(PostProcessPass& pass, const rg::PassContex
&& temporal->history[temporal->readIndex]) {
gpu = temporal->history[temporal->readIndex]->getColorAttachment();
}
+ if (slot.name == "u_environment" && environment_texture_ != 0) {
+ gpu = TextureHandle{environment_texture_};
+ }
for (const auto& [name, glId] : pass.textureUniforms) {
if (name == slot.name && glId != 0) { gpu = TextureHandle{glId}; break; }
}
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hpp
index 32f6d4f5f..ecd34796c 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp
@@ -230,6 +230,15 @@ public:
*/
bool sceneHasGBuffer() const { return inFrame_ && scene_gbuffer_; }
+ /**
+ * @brief The frame's environment atlas, for an effect that reflects it (`u_environment`).
+ *
+ * @details Handed over by the frame that bound it for the scene: the same atlas the meshes
+ * reflect, so a reflection an effect adds where the scene's own ray found nothing is the
+ * sky the surface already shows. 0 = none this frame.
+ */
+ void setEnvironmentTexture(u32 glTextureId) { environment_texture_ = glTextureId; }
+
/**
* @brief Starts a frame of the temporal view @p key, and answers how far to shift it.
*
@@ -514,6 +523,7 @@ private:
/// Some enabled pass of the chain reads the surface record.
bool passesWantGBuffer();
bool scene_gbuffer_ = false;
+ u32 environment_texture_ = 0;
bool passHasTexture(const PostProcessPass& pass, const char* name);
/// A history made (or kept) at @p w x @p h, or null when it cannot be.
TemporalState* prepareHistory(TemporalState& state, u32 w, u32 h);
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index ff4286832..e64828aba 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -225,6 +225,8 @@ void RenderFrame::drawScene() {
// The scene only: the overlay and the shadow maps are drawn with constants of their own.
glm::vec2 jitter{0.0f};
#ifdef ES_ENABLE_POSTPROCESS
+ // The atlas the meshes reflect, for an effect that adds a reflection of its own where the scene's ray found none.
+ if (post_process_) post_process_->setEnvironmentTexture(environment_texture_id_);
if (post_process_ && post_process_->isEngaged() && post_process_->temporalActive()) {
jitter = post_process_->beginTemporalView(view_projection_, current_target_);
}
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index bc4287b69..d378027d9 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -247,10 +247,10 @@ void reportLodAuthoring(const LodLevels& levels, bool& warned) {
}
u32 meshVariant(bool normals, bool lit, bool normalMapped, bool skinned, bool depthOnly,
- bool envMapped, bool lightmapped, bool weightHeat = false) {
+ bool envMapped, bool lightmapped, bool weightHeat = false, bool gbuffer = false) {
return (normals ? 1u : 0u) | (lit ? 2u : 0u) | (normalMapped ? 4u : 0u)
| (skinned ? 8u : 0u) | (depthOnly ? 16u : 0u) | (envMapped ? 32u : 0u)
- | (lightmapped ? 64u : 0u) | (weightHeat ? 128u : 0u);
+ | (lightmapped ? 64u : 0u) | (weightHeat ? 128u : 0u) | (gbuffer ? 256u : 0u);
}
/**
@@ -299,16 +299,19 @@ struct MeshDrawKeys {
u32 normalTextureId = 0;
};
-u32 meshVariantFrom(const MeshProgramFacts& facts, bool envMapped, bool shadowDepth, bool weightHeat = false) {
+u32 meshVariantFrom(const MeshProgramFacts& facts, bool envMapped, bool shadowDepth, bool weightHeat = false,
+ bool gbuffer = false) {
// `lightmapped` survives the shadow pass, unlike the three describing
// shading: it declares two vertex attributes, and a layout may not carry one
// the program ignores. The depth fragment simply never reads the atlas.
// Weights are read off the surface of a skinned draw and nothing else's: the colour is
// the shade, so it asks for no light, no normal map and no depth pass of its own.
const bool heat = weightHeat && facts.skinned && !shadowDepth;
- return meshVariant(facts.hasNormals, facts.lit && !shadowDepth && !heat,
+ const bool lit = facts.lit && !shadowDepth && !heat;
+ // The surface record is for what takes light: an unlit surface has no normal worth recording.
+ return meshVariant(facts.hasNormals, lit,
facts.normalTextureId != 0 && !shadowDepth && !heat, facts.skinned, shadowDepth,
- envMapped, facts.lightmapped, heat);
+ envMapped, facts.lightmapped, heat, gbuffer && lit);
}
/** @brief The facts a LIVE entity answers with: its components and its mesh. */
@@ -336,7 +339,8 @@ MeshDrawKeys meshDrawFor(RenderFrameContext& ctx, ecs::Registry& registry, Entit
const MeshProgramFacts facts =
meshFactsFromEntity(ctx, registry, entity, mesh, resident, warnedBones);
return { meshVariantFrom(facts, ctx.environment_texture_id != 0
- || (!shadowDepth && ctx.frame && ctx.frame->planarTextureFor(entity) != 0), shadowDepth, weightHeat),
+ || (!shadowDepth && ctx.frame && ctx.frame->planarTextureFor(entity) != 0), shadowDepth, weightHeat,
+ ctx.gbuffer && !shadowDepth),
facts.normalTextureId };
}
} // namespace
@@ -374,6 +378,7 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, u32 variant) {
const bool normalMapped = (variant & 4u) != 0, skinned = (variant & 8u) != 0;
const bool depthOnly = (variant & 16u) != 0, envMapped = (variant & 32u) != 0;
const bool lightmapped = (variant & 64u) != 0, weightHeat = (variant & 128u) != 0;
+ const bool gbuffer = (variant & 256u) != 0;
if (mesh_compiled_[variant]) return mesh_programs_[variant];
mesh_compiled_[variant] = true;
// Counted because the cost of this function is entirely the times it does
@@ -391,6 +396,7 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, u32 variant) {
if (lightmapped) features.emplace_back("MESH_LIGHTMAP");
if (weightHeat) features.emplace_back("WEIGHT_HEAT");
if (depthOnly) features.emplace_back("SHADOW_DEPTH");
+ if (gbuffer) features.emplace_back("ES_GBUFFER");
// Resident geometry owns its texture slots, so it is the vertex source that can
// carry a shadow map and a reflection — the batch stream's are a per-vertex
// merge product, and a sampler pinned there would read someone's sprite.
@@ -428,6 +434,8 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, u32 variant) {
return shader->getProgramId();
};
mesh_programs_[variant] = compile(features);
+ // Said to the store the draw list asks, so the pipeline of a draw on this program declares the second output.
+ if (gbuffer && mesh_programs_[variant] != 0 && ctx.materials) ctx.materials->markGBufferProgram(mesh_programs_[variant]);
return mesh_programs_[variant];
}
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index 26e4ac4cd..adc8921c7 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -137,9 +137,10 @@ static constexpr u32 MORPH_TEXTURE_WIDTH = 2048;
/// mesh that does not draw at all.
static constexpr u32 MORPH_MAX_TEXELS = MORPH_TEXTURE_WIDTH * MORPH_TEXTURE_WIDTH;
/// Programs the resident-mesh shader has: one per combination of {normals, lit,
-/// normal-mapped, skinned, depth-only, env-mapped, lightmapped}. Seven bits, not
-/// one: the geometry, the draw, the frame and the pass each answer a different.
-static constexpr u32 MESH_VARIANTS = 256;
+/// normal-mapped, skinned, depth-only, env-mapped, lightmapped, weight-heat,
+/// writes-the-surface-record}. Nine bits, not one: the geometry, the draw, the frame
+/// and the pass each answer a different.
+static constexpr u32 MESH_VARIANTS = 512;
/**
* @brief What a mesh vertex channel MEANS, and the attribute location it binds to.
* @details One vocabulary for the file format, the layout and the shaders: a
diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
index 53a9835d1..68176bdde 100644
--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
@@ -593,7 +593,23 @@ uniform sampler2D u_texture;
uniform sampler2D u_normalMap;
#endif
+#ifdef ES_GBUFFER
+
+
+
+
+layout(location = 0) out vec4 fragColor;
+layout(location = 1) out vec4 fragSurface;
+
+vec2 packNormal(vec3 n) {
+ n /= (abs(n.x) + abs(n.y) + abs(n.z));
+ vec2 sgn = vec2(n.x >= 0.0 ? 1.0 : -1.0, n.y >= 0.0 ? 1.0 : -1.0);
+ vec2 e = n.z >= 0.0 ? n.xy : (1.0 - abs(n.yx)) * sgn;
+ return e * 0.5 + 0.5;
+}
+#else
out vec4 fragColor;
+#endif
void main() {
#ifdef SHADOW_DEPTH
@@ -620,6 +636,9 @@ void main() {
vec3 shaded = applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),
0.0, 1.0, 1.0, 1.0);
fragColor = vec4(shaded, base.a);
+#ifdef ES_GBUFFER
+ fragSurface = vec4(packNormal(normalize(N)), 1.0, 0.75);
+#endif
#else
#ifdef MESH_LIGHTMAP
@@ -819,7 +838,25 @@ struct VSOut {
@location(6) @interpolate(flat) v_probeSlot : f32,
};
+#ifdef ES_GBUFFER
+
+struct FragOut {
+ @location(0) color : vec4f,
+ @location(1) surface : vec4f,
+};
+
+fn packNormal(n : vec3f) -> vec2f {
+ let a = n / (abs(n.x) + abs(n.y) + abs(n.z));
+ let sgn = vec2f(select(-1.0, 1.0, a.x >= 0.0), select(-1.0, 1.0, a.y >= 0.0));
+ var e = a.xy;
+ if (a.z < 0.0) { e = (vec2f(1.0) - abs(a.yx)) * sgn; }
+ return e * 0.5 + 0.5;
+}
+
+@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> FragOut {
+#else
@fragment fn fs_main(v : VSOut, @builtin(front_facing) front : bool) -> @location(0) vec4f {
+#endif
g_probeSlot = v.v_probeSlot;
@@ -846,7 +883,14 @@ struct VSOut {
let shaded = applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),
0.0, 1.0, 1.0, 1.0);
+#ifdef ES_GBUFFER
+ var frag : FragOut;
+ frag.color = vec4f(shaded, base.a);
+ frag.surface = vec4f(packNormal(normalize(N)), 1.0, 0.75);
+ return frag;
+#else
return vec4f(shaded, base.a);
+#endif
#else
#ifdef MESH_LIGHTMAP
diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hpp
index 0705fb25f..d546ec9f0 100644
--- a/src/esengine/renderer/store/MaterialStore.hpp
+++ b/src/esengine/renderer/store/MaterialStore.hpp
@@ -199,6 +199,8 @@ public:
bool programWritesGBuffer(u32 programId) const {
return gbuffer_programs_.count(programId) != 0;
}
+ /// A program that is not a material's — the engine's own mesh shader — says it writes the record.
+ void markGBufferProgram(u32 programId) const { gbuffer_programs_.insert(programId); }
/// How far @p materialId's vertex hook can move a vertex from the mesh's own bounds, in the
/// mesh's local units; 0 for a material without one.
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 913e11219..67f087765 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2487,4 +2487,6 @@ export const NOTED = {
{"note":"Settings → Project → Rendering edits each quality level, including which effects it runs."},
"feat(render): the scene can draw a G-buffer beside its colour, and reflections read each surface's normal, roughness and metalness from it":
{"note":"Reflections now know how rough and how metal each surface is, from a G-buffer the frame draws on request."},
+ "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."},
};