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): a transmissive material refracts the opaque scene behind it
yhh1fc2949b6642
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 56cee4c80..c188db0c9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,7 @@ published separately; it ships inside the editor.### Added- **Contact shadows and screen-space bounce light.** Contact Shadows and Screen Space GI effects add small sharp shadows at contacts and one bounce of colour between surfaces, and the weather softens the sun's shadows. `contactShadows` marches a short ray toward the scene's sun in the depth buffer; `ssgi` gathers eight rays a pixel over the G-buffer's normals at half size into a float target and averages the neighbours on the same surface before laying the light, times the receiver's colour, over the picture. The Weather component raises the sun's `sourceAngle` and lowers its `shadowStrength` as the sky clouds over.+- **Refraction.** Glass and water refract: a material with transmission bends and tints the opaque scene behind it, softened by its roughness. The frame draws the scene in two halves with a copy of the picture taken between them: the materials that read it (a shader that declares `u_sceneColor`, the Model shader while its transmission is above zero) are drawn second, ray-bent through their thickness. The surface's own highlights are no longer dimmed by blending, as they were when transmission was only coverage. Only the opaque scene is refracted, and it needs a post-process chain to copy from; without one transmission falls back to the earlier coverage.- **Ground-truth ambient occlusion.** Ground-truth ambient occlusion (GTAO) is a post-process effect beside SSAO: a crease darkens by how closed it really is and a flat floor stays white, with no bias to tune. It marches the depth buffer along a few slice planes through each pixel, finds the horizon on both sides and integrates the open arc against the surface's own normal; the blur and composite are SSAO's, the low quality level leaves it out, and the ambient-occlusion switch governs both.- **A sharper upscale.** A scene drawn at a render scale below 1 is stretched back to the screen with a resampler that keeps edges steeper than a bilinear copy. The resampler is Catmull-Rom clamped to the texels around each point, so it draws no halo; a whole-number stretch is still an exact copy. Measured on a sprite edge at the low level's 0.75 scale: the edge's 10-90% width is 1.04 px against 1.15 px bilinear (0.69 px at full size).- **Motion blur, film grain and lens flare.** Motion blur, film grain and lens flare are post-process effects, and a moving mesh's motion now reaches effects on WebGPU too. Motion blur follows the camera by the depth buffer and a moving mesh by its own motion, with the shutter and a cap on the streak as its settings; it needs no temporal anti-aliasing and does not shift the picture. Film grain is mid-tone noise that crawls with the clock; lens flare throws ghosts and a halo from what is brighter than a threshold. The low quality level skips motion blur and lens flare. Also fixed: a 32-bit float texture an effect only reads texel by texel (the motion pass's) is no longer paired with a filtering sampler, which WebGPU refused — temporal anti-aliasing's object motion logged an error every frame there.diff --git a/desktop b/desktopindex 37a13e7c5..5d7ff28de 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 37a13e7c526b2651fd59a28960ccc3a7f3085e98+Subproject commit 5d7ff28de563101751c3a228614714497525caa7diff --git a/docs/astro/src/content/docs/graphics/materials.mdx b/docs/astro/src/content/docs/graphics/materials.mdxindex d2c75c15a..d5130dd50 100644--- a/docs/astro/src/content/docs/graphics/materials.mdx+++ b/docs/astro/src/content/docs/graphics/materials.mdx@@ -53,13 +53,13 @@ The **Model** shader is a metal/rough surface with layers on top. Each is off at| Translucency | `u_translucency`, `u_translucencyColor`, `u_thickness` | Light that scatters into a thin surface: the lit side wraps past the terminator, and a lamp behind shows through, tinted, less the thicker it is. Leaves, paper, wax, a lampshade, skin at the ears. || Thin film | `u_iridescence`, `u_iridescenceIor`, `u_iridescenceThickness` (nm) | The reflection changes hue with the angle: soap, oil, beetle shell, coated glass. || Index of refraction | `u_ior`, `u_specular` | How strongly a non-metal reflects head-on (1.5 is glass and most plastics; a gemstone is 2.4), and a master scale on the reflection. |-| Transmission | `u_transmission`, `u_attenuationColor` | Glass and water: the surface lets that much of what is behind show, tinted, and reflects more at grazing angles. See the limits. |+| Transmission | `u_transmission`, `u_attenuationColor`, `u_thickness`, `u_refractionStrength` | Glass and water: the surface shows what is behind it, bent by the glass (thicker bends more), tinted, and softened by its roughness; it reflects more at grazing angles. |Everything here is written by model import from the glTF extensions of the same names (`KHR_materials_clearcoat`, `_sheen`, `_anisotropy`, `_ior`, `_specular`, `_iridescence`, `_transmission`, `_volume`, `_diffuse_transmission`) — see [Models](/docs/assets/models/).**Limits.** These are cheap, real-time models, and say where they stop:-- **Transmission shows no refraction.** There is no picture of the opaque scene to bend, so a transmissive surface is drawn alpha-blended: the background behind it is undistorted, and the highlights on it are dimmed by the same blend. Pull the transmission down for a surface that must keep its highlights.+- **Transmission refracts the opaque scene only.** A material that holds `u_transmission` above zero is drawn after the rest of the scene, from a copy of the picture taken just before: the ray is bent through the surface's thickness and the copy is read where it lands. So glass does not refract other glass, and a thin shell bends the picture by a fixed amount rather than as a lens that flips it. It needs a scene the engine can copy, which means a post-process chain is running (any effect, an output transform, or a render scale below 1); without one the surface falls back to alpha-blended coverage and shows the background undistorted.- **Translucency does not blur.** There is no screen-space subsurface pass; the light that enters at one point leaves at that point.- **A layer's textures are not read.** Each layer is a constant for the whole material (the Model shader has no texture unit left for more); a glTF extension's maps are reported at import and its factors are kept.- **Sheen and thin film are fits.** Sheen's energy loss and the film's interference are analytic approximations in place of the lookup tables a production renderer bakes.diff --git a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdxindex 5f905331b..b32fb6b41 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/materials.mdx@@ -47,13 +47,13 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一| 半透(Translucency) | `u_translucency`、`u_translucencyColor`、`u_thickness` | 光散射进薄的表面:受光面越过明暗交界线向背光侧延伸,背后的灯会透出来并带上颜色,越厚越弱。树叶、纸、蜡、灯罩、耳朵边缘的皮肤。 || 薄膜干涉 | `u_iridescence`、`u_iridescenceIor`、`u_iridescenceThickness`(nm) | 反射的色相随角度变化:肥皂泡、油膜、甲虫壳、镀膜玻璃。 || 折射率 | `u_ior`、`u_specular` | 非金属正对时反射有多强(1.5 是玻璃和大多数塑料,宝石是 2.4),以及反射的总缩放。 |-| 透射(Transmission) | `u_transmission`、`u_attenuationColor` | 玻璃和水:表面让背后的东西按该比例透出来并带上颜色,掠射角处反射更强。见下方限制。 |+| 透射(Transmission) | `u_transmission`、`u_attenuationColor`、`u_thickness`、`u_refractionStrength` | 玻璃和水:表面显示它背后的东西,被玻璃折射(越厚折得越多)、带上颜色、并按粗糙度变柔;掠射角处反射更强。 |这些都由模型导入从同名的 glTF 扩展写出(`KHR_materials_clearcoat`、`_sheen`、`_anisotropy`、`_ior`、`_specular`、`_iridescence`、`_transmission`、`_volume`、`_diffuse_transmission`)——见[模型](/docs/zh-cn/assets/models/)。**限制。** 这些是便宜的实时模型,下面说清楚它们止步在哪里:-- **透射没有折射。** 没有不透明场景的画面可以拿来扭曲,所以透射表面按 alpha 混合绘制:它后面的背景不会变形,表面上的高光也会被同一次混合压暗。需要保住高光的表面请把透射调低。+- **透射只折射不透明场景。** `u_transmission` 大于 0 的材质在场景其余部分之后绘制,读取的是之前刚拍下的画面副本:光线穿过表面厚度后被折弯,在落点处读取副本。所以玻璃不会折射另一块玻璃,薄壳对画面的偏折是固定的量,而不是像透镜那样把画面翻转。它需要引擎能拷贝的场景,也就是有后处理链在运行(任意效果、输出变换,或小于 1 的渲染比例);没有时表面退回 alpha 混合覆盖,背景不会变形。- **半透不做模糊。** 没有屏幕空间次表面散射 pass;从某一点进入的光就在这一点出去。- **不读取层的贴图。** 每一层对整个材质是一个常量(Model shader 已经没有多余的纹理单元);glTF 扩展的贴图在导入时会报告,其系数会保留。- **绒面和薄膜是拟合。** 绒面的能量损失和薄膜的干涉是解析近似,代替了生产级渲染器烘焙的查找表。diff --git a/sdk/src/render/builtinShaders.ts b/sdk/src/render/builtinShaders.tsindex 4082c584c..959e0a7d3 100644--- a/sdk/src/render/builtinShaders.ts+++ b/sdk/src/render/builtinShaders.ts@@ -377,6 +377,11 @@ const MODEL = `#pragma shader "Model"#pragma param u_thickness float default(0) range(0,1) ui(slider)#pragma param u_transmission float default(0) range(0,1) ui(slider)#pragma param u_attenuationColor color default(1,1,1,1)+// The picture of the opaque scene as it stood behind this surface, which the frame takes a copy of before it draws a material+// that holds a transmission above zero (and only then: a draw that reads it is made after the copy). The white it falls back+// to has alpha 1, and a real copy has 0.5 — which is how this tells whether it has one.+#pragma param u_sceneColor texture default(white)+#pragma param u_refractionStrength float default(1) range(0,4) ui(slider)#pragma param u_iridescence float default(0) range(0,1) ui(slider)#pragma param u_iridescenceIor float default(1.3) range(1,2.5) ui(slider)#pragma param u_iridescenceThickness float default(400) range(0,1200) ui(slider)@@ -497,16 +502,38 @@ void main() {}if (u_iridescence > 0.0) ext.film = vec4(u_iridescence, max(u_iridescenceIor, 1.0), u_iridescenceThickness, 0.0);vec3 viewDir = viewDirection(P);- // Light that passes through. With no picture of what is behind to refract, the surface lets that much of it show: its- // coverage falls with the transmission, and returns at grazing angles where glass reflects instead of passing light.+ // Light that passes through: what stands behind the surface, bent by the glass and tinted by it, and less of it where the+ // surface reflects instead. The frame took a copy of the opaque scene for this draw; the ray is refracted through the+ // surface's thickness, and the copy is read where it lands, blurred by the roughness.+ vec3 seen = vec3(0.0);+ float refracted = 0.0;if (u_transmission > 0.0) {float cosV = clamp(dot(N, viewDir), 0.0, 1.0);- alpha *= 1.0 - u_transmission * (1.0 - (0.04 + 0.96 * pow(1.0 - cosV, 5.0)));- base.rgb = mix(base.rgb, base.rgb * u_attenuationColor.rgb, u_transmission);+ float fresnel = ext.misc.x + (1.0 - ext.misc.x) * pow(1.0 - cosV, 5.0);+ if (texture(u_sceneColor, vec2(0.5)).a < 0.75) {+ vec3 bent = refract(-viewDir, N, 1.0 / max(u_ior, 1.0));+ float depth = max(u_thickness, 0.15) * 60.0 * u_refractionStrength;+ vec4 landed = u_projection * vec4(P + bent * depth, 1.0);+ vec2 uv = landed.xy / max(landed.w, 1e-4) * 0.5 + 0.5;+ float spread = roughness * roughness * 0.04;+ vec3 behind = texture(u_sceneColor, clamp(uv, vec2(0.001), vec2(0.999))).rgb;+ for (int i = 0; i < 8; ++i) {+ float a = float(i) * 2.39996;+ vec2 o = vec2(cos(a), sin(a)) * (spread * sqrt((float(i) + 0.5) / 8.0));+ behind += texture(u_sceneColor, clamp(uv + o, vec2(0.001), vec2(0.999))).rgb;+ }+ seen = behind / 9.0 * u_attenuationColor.rgb * (1.0 - fresnel) * u_transmission;+ refracted = 1.0;+ } else {+ // No picture to refract (the scene is not a texture here): the surface lets that much of the scene show instead,+ // by its own coverage, which dims what it reflects with it.+ alpha *= 1.0 - u_transmission * (1.0 - fresnel);+ base.rgb = mix(base.rgb, base.rgb * u_attenuationColor.rgb, u_transmission);+ }}- vec3 lit = applyLightingSurface(base.rgb, N, P, viewDir,+ vec3 lit = applyLightingSurface(base.rgb * (1.0 - u_transmission * refracted), N, P, viewDir,u_metallic * mr.b, roughness, u_specular, ao, ext);- fragColor = vec4(lit + u_emissive.rgb * texture(u_emissiveMap, v_texCoord).rgb, alpha);+ fragColor = vec4(lit + seen + 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 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.@@ -615,22 +642,43 @@ fn packNormal(n : vec3f) -> vec2f {}if (mc.u_iridescence > 0.0) { ext.film = vec4f(mc.u_iridescence, max(mc.u_iridescenceIor, 1.0), mc.u_iridescenceThickness, 0.0); }let viewDir = viewDirection(P);+ var seen = vec3f(0.0);+ var refracted = 0.0;if (mc.u_transmission > 0.0) {let cosV = clamp(dot(N, viewDir), 0.0, 1.0);- alpha *= 1.0 - mc.u_transmission * (1.0 - (0.04 + 0.96 * pow(1.0 - cosV, 5.0)));- base = vec4f(mix(base.rgb, base.rgb * mc.u_attenuationColor.rgb, vec3f(mc.u_transmission)), base.a);+ let fresnel = ext.misc.x + (1.0 - ext.misc.x) * pow(1.0 - cosV, 5.0);+ if (textureSampleLevel(u_sceneColor, u_sceneColor_s, vec2f(0.5), 0.0).a < 0.75) {+ let bent = refract(-viewDir, N, 1.0 / max(mc.u_ior, 1.0));+ let depth = max(mc.u_thickness, 0.15) * 60.0 * mc.u_refractionStrength;+ let landed = frame.projection * vec4f(P + bent * depth, 1.0);+ let w = max(landed.w, 1e-4);+ // This device's rows run down the texture, so clip y is flipped on the way to a uv.+ let uv = vec2f(landed.x / w * 0.5 + 0.5, 0.5 - landed.y / w * 0.5);+ let spread = roughness * roughness * 0.04;+ var behind = textureSampleLevel(u_sceneColor, u_sceneColor_s, clamp(uv, vec2f(0.001), vec2f(0.999)), 0.0).rgb;+ for (var i : i32 = 0; i < 8; i = i + 1) {+ let a = f32(i) * 2.39996;+ let o = vec2f(cos(a), sin(a)) * (spread * sqrt((f32(i) + 0.5) / 8.0));+ behind = behind + textureSampleLevel(u_sceneColor, u_sceneColor_s, clamp(uv + o, vec2f(0.001), vec2f(0.999)), 0.0).rgb;+ }+ seen = behind / 9.0 * mc.u_attenuationColor.rgb * (1.0 - fresnel) * mc.u_transmission;+ refracted = 1.0;+ } else {+ alpha *= 1.0 - mc.u_transmission * (1.0 - fresnel);+ base = vec4f(mix(base.rgb, base.rgb * mc.u_attenuationColor.rgb, vec3f(mc.u_transmission)), base.a);+ }}- let lit = applyLightingSurface(base.rgb, N, P, viewDir,+ let lit = applyLightingSurface(base.rgb * (1.0 - mc.u_transmission * refracted), N, P, viewDir,mc.u_metallic * mr.b, roughness, mc.u_specular, ao, ext);let emit = mc.u_emissive.rgb* textureSampleGrad(u_emissiveMap, u_emissiveMap_s, v.v_texCoord, duvx, duvy).rgb;#ifdef ES_GBUFFERvar frag : FragOut;- frag.color = vec4f(lit + emit, alpha);+ frag.color = vec4f(lit + seen + emit, alpha);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);+ return vec4f(lit + seen + emit, alpha);#endif}#pragma enddiff --git a/sdk/tests/shader-reflect.test.ts b/sdk/tests/shader-reflect.test.tsindex 84309f02e..fb256c8c3 100644--- a/sdk/tests/shader-reflect.test.ts+++ b/sdk/tests/shader-reflect.test.ts@@ -131,6 +131,8 @@ describe('which texture params a shader reads as numbers', () => {.filter((p) => p.type === 'texture').map((p) => [p.name, p.texel ?? 'colour']);expect(Object.fromEntries(data)).toEqual({u_normalMap: 'data', u_emissiveMap: 'colour', u_occlusionMap: 'data', u_metallicRoughnessMap: 'data',+ // The picture of the scene the frame binds for refraction: never a project texture, so nothing to flag.+ u_sceneColor: 'colour',});});});diff --git a/src/esengine/data/shaders/blit.esshader b/src/esengine/data/shaders/blit.esshaderindex 18e3ee45e..5df152e0c 100644--- a/src/esengine/data/shaders/blit.esshader+++ b/src/esengine/data/shaders/blit.esshader@@ -52,6 +52,12 @@ void main() {#endif// The editor view's exposure (u_time.z, stops): zero outside the editor, where// exp2(0) = 1 leaves every pixel as it was. Before the curve, like any exposure.+#ifdef ES_COPY+ // A copy of the picture for a surface that looks through to it. Alpha 0.5 says "a real copy": the texture param a shader falls+ // back to when the frame took none is white, whose alpha is 1.+ fragColor = vec4(c.rgb, 0.5);+ return;+#endifc = vec4(c.rgb * exp2(u_time.z), c.a);#ifdef ES_TONEMAP// The output transform: scene radiance can exceed 1.0 on an HDR target,@@ -110,6 +116,9 @@ fn upscale(uv : vec2f) -> vec4f {var c = upscale(v.v_texCoord);#elsevar c = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);+#endif+#ifdef ES_COPY+ return vec4f(c.rgb, 0.5);#endifc = vec4f(c.rgb * exp2(tc.u_time.z), c.a);#ifdef ES_TONEMAPdiff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cppindex 64a544b1e..c6ae26b07 100644--- a/src/esengine/renderer/draw/DrawList.cpp+++ b/src/esengine/renderer/draw/DrawList.cpp@@ -355,9 +355,16 @@ void DrawList::stageBlocks(const PerDrawBlockSet& blocks) {}}+bool DrawList::anyUsesSceneColor(const MaterialStore& materials) const {+ for (u32 i = 0; i < merged_draw_calls_; ++i) {+ if (commands_[i].material_id != 0 && materials.usesSceneColor(commands_[i].material_id)) return true;+ }+ return false;+}+void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,MaterialStore& materials, u32 white_texture_id,- FrameCapture* capture, const PerDrawBlockSet& blocks) {+ FrameCapture* capture, const PerDrawBlockSet& blocks, Phase phase) {PipelineDesc lastDesc{};PipelineHandle lastHandle = PipelineHandle::Invalid;@@ -372,6 +379,10 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,for (u32 i = 0; i < merged_draw_calls_; ++i) {const auto& cmd = commands_[i];const StagedBlocks& staged = staged_[i];+ if (phase != Phase::All+ && (cmd.material_id != 0 && materials.usesSceneColor(cmd.material_id)) != (phase == Phase::SceneColorOnly)) {+ continue;+ }const GfxStencilMode stencil = stencilModeOf(cmd.state_flags);diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hppindex ca1439463..76f37c9cd 100644--- a/src/esengine/renderer/draw/DrawList.hpp+++ b/src/esengine/renderer/draw/DrawList.hpp@@ -55,10 +55,16 @@ public:// white_texture_id fills a Batch draw's unused sampler slots — a STABLE texture// so those slots stay pinned across draws and the bind cache dedups them// (filling with the draw's own tex re-pointed all 8 units on every tex change).+ /// Which of the list's draws an execute makes. A draw whose material reads the picture behind it (`u_sceneColor`) has to be+ /// made after a copy of that picture is taken, so the frame executes the list twice: the rest, then those.+ enum class Phase : u8 { All, WithoutSceneColor, SceneColorOnly };void execute(GfxDevice& device, TransientBufferPool& buffers,MaterialStore& materials, u32 white_texture_id = 0,FrameCapture* capture = nullptr,- const PerDrawBlockSet& blocks = {});+ const PerDrawBlockSet& blocks = {}, Phase phase = Phase::All);++ /// Whether any merged draw reads the picture behind it.+ bool anyUsesSceneColor(const MaterialStore& materials) const;/** Append one draw's bone matrices; returns where they start. Frame-scoped,* like the vertex pool: a command references an offset, not a copy. */diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cppindex aeb08e1ea..809f734d8 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp@@ -227,6 +227,10 @@ void PostProcessPipeline::shutdown() {resourceManager_.releaseShader(tonemapShader_);tonemapShader_ = resource::ShaderHandle{};}+ if (copyShader_.isValid()) {+ resourceManager_.releaseShader(copyShader_);+ copyShader_ = resource::ShaderHandle{};+ }for (auto& shader : upscaleShaders_) {if (!shader.isValid()) continue;resourceManager_.releaseShader(shader);@@ -992,6 +996,22 @@ void PostProcessPipeline::setOutputViewport(u32 x, u32 y, u32 w, u32 h) {output_vp_h_ = h;}+void PostProcessPipeline::grabScene() {+ if (!copyShader_.isValid()) {+ copyShader_ = compileBlit({"ES_COPY"});+ if (!copyShader_.isValid()) {+ ES_LOG_ERROR("PostProcessPipeline: no copy shader; a refractive surface sees nothing behind it");+ return;+ }+ }+ Shader* shader = resourceManager_.getShader(copyShader_);+ if (!shader) return;+ applyPassPipeline(*shader);+ shader->setUniform("u_texture", 0);+ shader->commitParams();+ drawScreenQuad();+}+void PostProcessPipeline::blitPass() {Shader* shader = resourceManager_.getShader(outputShader());if (!shader) return;diff --git a/src/esengine/renderer/frame/PostProcessPipeline.hpp b/src/esengine/renderer/frame/PostProcessPipeline.hppindex b3f3d8483..aa6ecf936 100644--- a/src/esengine/renderer/frame/PostProcessPipeline.hpp+++ b/src/esengine/renderer/frame/PostProcessPipeline.hpp@@ -261,6 +261,13 @@ public:*/bool cameraMotionWanted();+ /// The shape of the copy of the opaque scene a refractive surface reads: the chain's own, bilinear.+ rg::TargetDesc grabTarget() const { return chainTarget(/*withDepth=*/false); }++ /// Copies what is bound at unit 0 (the scene, as the pass before drew it) into the target being drawn. No exposure, no curve, no+ /// encode: a copy, with the alpha set to a marker (0.5) a shader can tell from the white a texture param falls back to.+ void grabScene();+/// Records this frame's camera as the view @p key's current one, and last frame's as its previous. No shift.void trackView(const glm::mat4& viewProjection, u64 key);@@ -587,6 +594,7 @@ private:resource::ShaderHandle neutralShader_;/// The same three blits (plain, neutral, ACES) with the resampling upscaler, compiled when a present first needs one.resource::ShaderHandle upscaleShaders_[3];+ resource::ShaderHandle copyShader_;std::vector<PostProcessPass> passes_;u32 width_ = 0;diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 3762bb8fb..bd2bf47b6 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -229,7 +229,7 @@ void RenderFrame::resize(u32 width, u32 height) {// The scene pass's body. The graph has bound the target and set the camera's// viewport; this is the draw and the constants it needs current.-void RenderFrame::drawScene() {+void RenderFrame::drawScene(DrawList::Phase phase) {// A temporal effect in the chain asks for the picture to be shifted by a different// sub-pixel amount each frame, so its history samples what a single frame cannot.// The scene only: the overlay and the shadow maps are drawn with constants of their own.@@ -237,7 +237,11 @@ void RenderFrame::drawScene() {#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()) {+ if (phase == DrawList::Phase::SceneColorOnly) {+ // The second half of a scene drawn in two: the same camera, shifted the same way, and a frame that must not step the+ // temporal view a second time.+ jitter = scene_jitter_;+ } else if (post_process_ && post_process_->isEngaged() && post_process_->temporalActive()) {jitter = post_process_->beginTemporalView(view_projection_, current_target_);} else if (post_process_ && post_process_->isEngaged() && post_process_->cameraMotionWanted()) {post_process_->trackView(view_projection_, current_target_);@@ -275,7 +279,7 @@ void RenderFrame::drawScene() {draw_list_.setGBufferPass(post_process_ && post_process_->sceneHasGBuffer());#endifdraw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),- &frame_capture_, context_.perDrawBlocks());+ &frame_capture_, context_.perDrawBlocks(), phase);draw_list_.setGBufferPass(false);}@@ -634,11 +638,45 @@ void RenderFrame::end() {scene.dependencies.push_back(shadow_2d_resource_);}if (planar_resource_ != rg::kNoResource) scene.dependencies.push_back(planar_resource_);- scene.execute = [this](const rg::PassContext&) {- drawScene();- if (presented_overlay_draw_) presented_overlay_draw_->flushDeferred();+ // A surface that refracts has to see what stands behind it, and what stands behind it is the opaque scene: the pass is+ // drawn in two, with a copy of the picture taken between. Only where the scene is a texture a pass can read (a chain is+ // engaged) and a draw in the list asks for the copy.+ bool glass = false;+#ifdef ES_ENABLE_POSTPROCESS+ glass = usePostProcess && draw_list_.anyUsesSceneColor(context_.materials());+#endif+ rg::PassDesc glassPass;+ rg::ResourceId grab = rg::kNoResource;+ if (glass) {+#ifdef ES_ENABLE_POSTPROCESS+ grab = graph_.createTarget(post_process_->grabTarget());+ glassPass = scene;+ glassPass.name = "scene-glass";+ glassPass.dependencies.push_back(grab);+ glassPass.execute = [this, grab](const rg::PassContext&) {+ context_.materials().setSceneColor(graph_.textureOf(grab));+ drawScene(DrawList::Phase::SceneColorOnly);+ context_.materials().setSceneColor(TextureHandle::Invalid);+ if (presented_overlay_draw_) presented_overlay_draw_->flushDeferred();+ };+#endif+ }+ scene.execute = [this, glass](const rg::PassContext&) {+ drawScene(glass ? DrawList::Phase::WithoutSceneColor : DrawList::Phase::All);+ if (!glass && presented_overlay_draw_) presented_overlay_draw_->flushDeferred();};graph_.addPass(std::move(scene));+ if (glass) {+#ifdef ES_ENABLE_POSTPROCESS+ rg::PassDesc copy;+ copy.name = "scene-grab";+ copy.reads = {scene_resource_};+ copy.write = grab;+ copy.execute = [this](const rg::PassContext&) { post_process_->grabScene(); };+ graph_.addPass(std::move(copy));+#endif+ graph_.addPass(std::move(glassPass));+ }}#ifdef ES_ENABLE_POSTPROCESSdiff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 0f12b32cf..6f6a499a8 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -791,7 +791,7 @@ private:/// Deletes them. Device loss and shutdown: the handles name nothing afterwards.void releaseShadowFrameUbos();/// The scene pass's body: the draw, and the constants it needs current.- void drawScene();+ void drawScene(DrawList::Phase phase = DrawList::Phase::All);/// Drops the atlas texture id the frame published; its target is the graph's/// to give back.void releaseFrameTargets();diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 45b0a6042..961a5826b 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -274,6 +274,8 @@ void MaterialStore::bindForDraw(u32 materialId) {if (lit != layouts_.end()) {for (const auto& slot : lit->second.textures) {TextureHandle gpu = builtinDefault(slot.defaultTexture);+ // What stood behind this draw, where the frame took a copy of it; a material that named a texture there keeps its own.+ if (sceneColor_ != TextureHandle::Invalid && slot.name == "u_sceneColor") gpu = sceneColor_;for (const auto& b : rec.textures) {if (b.unit != slot.unit) continue;// Resolved HERE rather than cached at set time. A pool lookup isdiff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex 1989cd137..d7f2a86ee 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -309,6 +309,25 @@ public:return it != materials_.end() ? &it->second : nullptr;}+ /// Whether @p materialId's shader reads the picture of what is behind it (declares `u_sceneColor`): refraction, a lens, anything+ /// that has to see the opaque scene as it stood before this draw. Such a draw is made after a copy of that picture is taken.+ bool usesSceneColor(u32 materialId) const {+ const MaterialRecord* m = find(materialId);+ const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;+ if (!layout || layout->findTexture("u_sceneColor") == nullptr) return false;+ // A shader that has a `u_transmission` (the Model shader, whose material is mostly opaque) asks for the copy only while+ // the material holds it above zero; one that has none always does.+ const MaterialParamSlot* slot = layout->find("u_transmission");+ if (!slot) return true;+ if (slot->offset + sizeof(f32) > m->uboBytes.size()) return false;+ f32 value = 0.0f;+ std::memcpy(&value, m->uboBytes.data() + slot->offset, sizeof(f32));+ return value > 0.0f;+ }+ /// The copy of the opaque scene the frame took for the draws above, or invalid when it took none. Bound to a material's+ /// `u_sceneColor` unit unless the material was given a texture of its own there.+ void setSceneColor(TextureHandle texture) { sceneColor_ = texture; }+/// Whether @p materialId's output alpha is coverage now: its shader names a/// coverage param and this material holds it above zero.bool alphaIsCoverage(u32 materialId) const {@@ -368,6 +387,7 @@ private:mutable std::unordered_map<u32, std::unordered_map<u64, resource::ShaderHandle>> mesh_programs_;/// Programs compiled with ES_GBUFFER (see programWritesGBuffer).mutable std::unordered_set<u32> gbuffer_programs_;+ TextureHandle sceneColor_ = TextureHandle::Invalid;public:/** @brief How many material program variants have been built. A prewarm countsdiff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 9c60a7ac7..19b69e794 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2493,6 +2493,8 @@ export const NOTED = {{"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): a transmissive material refracts the opaque scene behind it":+ {"note":"Glass and water refract: a material with transmission bends and tints the opaque scene behind it, softened by its roughness."},"feat(render): ground-truth ambient occlusion joins the post-process effects":{"note":"Ground-truth ambient occlusion (GTAO) is a post-process effect beside SSAO: a crease darkens by how closed it really is and a flat floor stays white, with no bias to tune."},"feat(render): a scene drawn below the screen's size is stretched back with a sharper resampler":