From bd4929653806df5d94f33afa6b8b87744a20064f Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 24 Nov 2026 19:20:46 +0900 Subject: [PATCH 1/9] feat(render3d): add composable 3D post-processing (Bloom, SSAO, DoF) --- .../2026-11-24-render3d-post-processing.md | 42 + changelog.d/render3d-post-processing-282.md | 3 + docs/en/render3d.md | 32 + docs/zh/render3d.md | 32 + packages/game/render3d/post3d.go | 3030 +++++++++++++++++ packages/game/render3d/post3d_test.go | 1040 ++++++ .../render3d/testdata/golden/post3d_bloom.png | Bin 0 -> 3110 bytes .../testdata/golden/post3d_combined.png | Bin 0 -> 6805 bytes .../render3d/testdata/golden/post3d_dof.png | Bin 0 -> 4800 bytes .../render3d/testdata/golden/post3d_ssao.png | Bin 0 -> 3124 bytes 10 files changed, 4179 insertions(+) create mode 100644 .agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md create mode 100644 changelog.d/render3d-post-processing-282.md create mode 100644 packages/game/render3d/post3d.go create mode 100644 packages/game/render3d/post3d_test.go create mode 100644 packages/game/render3d/testdata/golden/post3d_bloom.png create mode 100644 packages/game/render3d/testdata/golden/post3d_combined.png create mode 100644 packages/game/render3d/testdata/golden/post3d_dof.png create mode 100644 packages/game/render3d/testdata/golden/post3d_ssao.png diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md b/.agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md new file mode 100644 index 00000000..12a66ccd --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md @@ -0,0 +1,42 @@ +# Agent Note: 3D Post-Processing (Bloom, SSAO, Depth of Field) in render3d + +Status: implemented + +## Problem + +3D games built on `game/render3d` and NSGo's `gpu.View` need multi-pass offscreen 3D post-processing — HDR Bloom, depth-based Screen-Space Ambient Occlusion (SSAO), and Depth of Field (DoF) — running over `gpu.RenderTarget` color and depth attachments (#282, part of #279). + +The existing 2D `game/effects` package fuses Kage fragment passes into a single draw without intermediate textures or a 3D depth buffer (see [CRT scanlines note](2026-11-24-effects-crt-scanlines.md)), so it cannot sample a 3D `texture_depth_2d` attachment, preserve HDR floating-point highlights (`FormatRGBA16Float`), or run multi-pass separable blurs. Building portable 3D post-processing on NSGo v0.3.0 also carries concrete cross-backend constraints: + +- NSGo's software GPU VM omits `shaderir.Exp`, `shaderir.Exp2`, `shaderir.Log2`, and screen-space derivative builtins (`dpdx`/`dpdy`), so shaders that rely on `exp` Gaussian weights or `dpdx`/`dpdy` normal reconstruction fail or produce wrong output in headless tests. +- All `Device.WriteBuffer` calls queued within a frame execute before any render passes in that frame, so sharing one uniform buffer across horizontal and vertical blur passes overwrites the horizontal direction before it runs. +- WebGPU and GLES 3.0 require non-filtering (`FilterNearest`) samplers for non-comparison `texture_depth_2d` reads and require `textureSampleLevel` inside non-uniform control flow (loops or early-exit branches). +- WebGL 2 / OpenGL ES 3.0 (`nsgotest.NoGPUCompute`) lack compute shaders, so every pass must run as fragment render passes. + +## Decision + +`packages/game/render3d/post3d.go` adds standalone passes (`BloomPass`, `SSAOPass`, `DepthOfFieldPass`) and a composable `PostStack3D` manager with validated configs (`BloomConfig`, `SSAOConfig`, `DepthOfFieldConfig`, wrapping invalid inputs in `ErrInvalidPostProcess`): + +- **Dedicated offscreen render targets and fixed stage order**: `PostStack3D` owns an offscreen color+depth scene target (`FormatRGBA16Float` + `FormatDepth32Float` by default, configurable to `FormatRGBA8Unorm` / `FormatDepth24Plus`) and two ping-pong color targets. Enabled passes run in order **SSAO -> Depth of Field -> Bloom** so ambient occlusion darkens crevices before optical blur and highlights bloom afterward. Each pass holds separate intermediate (`ColorFormat`) and output (`OutputFormat`) composite pipelines so the final enabled pass writes directly to the swapchain or destination texture without an extra copy pass. +- **Portable fragment-only WGSL**: All passes use a shared 3-vertex retained fullscreen triangle buffer (`z = 0.0`, avoiding far-plane `z = 1.0` clipping and empty-VAO WebGL 2 quirks), explicit `textureSampleLevel`, `FilterNearest` depth samplers, precomputed 9-tap separable Gaussian weights (Bloom), algebraic bilateral depth weights `1 / (1 + (dz / thresh)^2)` (SSAO blur), and edge-preserving 4-neighbor depth-difference normal reconstruction with a deterministic 4×4 stratified rotation pattern (SSAO). Zero `exp`/`exp2`/`log2`, `dpdx`/`dpdy`, or compute shaders are used. +- **Per-stage uniform buffers and bind-group caching**: Each sub-pass (`extract`, `horizBlur`, `vertBlur`, `composite`, `ssao`, `ssaoBlur`, `coc`, `bokeh`) owns its own uniform buffer so multi-pass submissions in one `gpu.Frame` or `gpu.Encoder` never clobber earlier passes' uniforms. External input bind groups are cached by texture handle and closed on change, `Resize`, or `Close` to avoid steady-state leaks. +- **Device-parameterized methods (`PostPassRecorder`)**: Following [textures and samplers](2026-11-24-render3d-textures-and-samplers.md), passes never cache `*gpu.Device`; `Apply`, `ComputeAO`, and `Resize` accept `dev *gpu.Device` explicitly and a `PostPassRecorder` interface satisfied by both `*gpu.Frame` and `*gpu.Encoder`, allowing `Retained: true` resources to survive device loss and restoration cleanly. + +## Alternatives considered + +### Compute-shader Bloom, SSAO, and DoF + +Running separable blur, SSAO, and CoC gather in compute shaders with shared workgroup memory reduces texture bandwidth on desktop/modern mobile GPUs. Rejected because NSGo targets WebGL 2 and OpenGL ES 3.0 (`nsgotest.NoGPUCompute`), where compute pipelines and storage textures return `gpu.ErrUnsupported`. Fragment passes over `gpu.RenderTarget` work identically across Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software device. + +### Reconstructing SSAO normals with `dpdx`/`dpdy` + +Using `normalize(cross(dpdx(viewPos), dpdy(viewPos)))` avoids four neighboring depth texture fetches per pixel. Rejected because NSGo's software GPU VM does not evaluate 2×2 fragment quads or implement `Dfdx`/`Dfdy`, and raw `dpdx`/`dpdy` produces silhouette-edge normal artifacts across depth discontinuities whereas minimum-delta 4-neighbor depth differencing is edge-preserving and deterministic everywhere. + +### Extending `game/effects` with 3D post-processing + +Placing 3D Bloom, SSAO, and DoF in `game/effects` would group all screen-space effects under one package. Rejected because `game/effects` is coupled to Kage single-pass fusion over 2D `core.ImageSource` layers without `gpu.Device`, `gpu.RenderTarget`, `texture_depth_2d`, or `scene3d.Camera` projection matrices; keeping 3D post-processing in `game/render3d` aligns with `CameraBuffer`, `GPUMesh`, and `GPUTexture`. + +## Consequences + +- **Benefits**: Games get composable or standalone HDR Bloom, depth-reconstructed SSAO (with inspectable `AOTexture()` and bilateral blur), and depth-aware disc bokeh Depth of Field running on every NSGo backend including `NoGPUCompute`, with `Resize`, `Retained` device-loss restoration, zero steady-state bind-group leaks, and deterministic golden reference tests (`post3d_bloom.png`, `post3d_ssao.png`, `post3d_dof.png`, `post3d_combined.png`). +- **Costs**: `PostStack3D` allocates offscreen scene, ping-pong, and per-pass render targets up front (even for passes initially disabled, so toggling via `SetSSAO`/`SetDepthOfField`/`SetBloom` allocates nothing at runtime); callers needing only one effect can instantiate `BloomPass`, `SSAOPass`, or `DepthOfFieldPass` standalone to avoid unused target memory. SSAO bilateral blur runs as a 2D neighborhood loop (capped at `BlurRadius <= 4`) rather than a separable pass, trading slightly more software-VM test time for stronger diagonal edge preservation. diff --git a/changelog.d/render3d-post-processing-282.md b/changelog.d/render3d-post-processing-282.md new file mode 100644 index 00000000..2c7b7a16 --- /dev/null +++ b/changelog.d/render3d-post-processing-282.md @@ -0,0 +1,3 @@ +### Added + +- `game/render3d`: composable 3D post-processing via offscreen `gpu.RenderTarget` passes (`PostStack3D`, `BloomPass`, `SSAOPass`, `DepthOfFieldPass`) supporting HDR bright-extract + separable Gaussian Bloom, depth-reconstructed SSAO with bilateral blur, and depth-aware disc bokeh Depth of Field across full and compute-free (`WebGL 2` / `GLES 3.0`) NSGo GPU profiles (#282). diff --git a/docs/en/render3d.md b/docs/en/render3d.md index eea8fe54..c3bfe981 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -1138,3 +1138,35 @@ for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { - **Filtering and bias**: `LocalShadowFilterHard` (one nearest comparison tap) or `LocalShadowFilterPCF3x3` (nine linear taps), with a constant `DepthBias` and a world-space `NormalBias`. - **Bind group 3**: `LocalShadowGroup` is `ShadowGroup` (3), the group the directional shadow, fog, IBL and skinning also use, so a lit PBR pipeline takes one of them (`LitPBRPipelineOptions.SpotShadowLayout` or `PointShadowLayout`). A custom shader that needs both, or group 3 for something else, places the bindings with `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` and scales its lights with `shade_pbr_visibility(…, directional0_vis, point0_vis, spot0_vis)` from `LightWGSL`. - **Device loss and CPU references**: with `Retained: true` the depth target, sampler, buffers, bind groups and depth pipeline come back after a device loss. `EvaluateSpotShadow`, `EvaluatePointShadow` and `PointShadowSelectFace` mirror the WGSL, and `ShadePointVisibility` with a `LightVisibility` reproduces the lit pixel; the tests compare them with the GPU and with the golden renders `render3d/testdata/golden/local_shadow_spot.png` and `local_shadow_point.png` (`UPDATE_GOLDEN=1` rewrites them). + +## 3D post-processing (`PostStack3D`, `BloomPass`, `SSAOPass`, `DepthOfFieldPass`) + +`PostStack3D` composes screen-space ambient occlusion (`SSAOPass`), depth-aware disc bokeh Depth of Field (`DepthOfFieldPass`), and HDR Bloom (`BloomPass`) over an offscreen 3D color+depth `gpu.RenderTarget` (`FormatRGBA16Float` + `FormatDepth32Float` by default) and writes the final image to the swapchain or a chosen destination texture: + +```go +stack, err := render3d.NewPostStack3D(cx, dev, render3d.PostStack3DOptions{ + Width: uint32(w), + Height: uint32(h), + OutputFormat: dev.SurfaceFormat(), + Retained: true, + EnableSSAO: true, + SSAO: render3d.SSAOConfigFromCamera(cam), + EnableDoF: true, + DoF: render3d.DepthOfFieldConfigFromCamera(cam, 5.0, 2.0, 5.0), + EnableBloom: true, + Bloom: render3d.DefaultBloomConfig(), +}) + +// In OnFrame: +pass := stack.BeginScenePass(frame, core.RGB(0x0c1018)) +// ... draw 3D meshes into stack.SceneTarget() ... +pass.End() +_ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> Depth of Field -> Bloom -> swapchain +frame.Submit() +``` + +- **Composable order and standalone passes**: `PostStack3D` runs enabled stages in fixed order — **SSAO -> Depth of Field -> Bloom** — routing intermediate results through ping-pong offscreen targets and writing the final stage directly in `OutputFormat` (or blitting cleanly when all stages are disabled). Each pass (`SSAOPass`, `DepthOfFieldPass`, `BloomPass`) can also be constructed and applied standalone against any caller-owned `gpu.Texture` color and depth attachments via `PostPassRecorder` (satisfied by both `*gpu.Frame` and `*gpu.Encoder`). +- **SSAO (`SSAOConfig`, `SSAOPass`)**: reconstructs view-space positions and edge-preserving normals from the 3D depth buffer, evaluates a deterministic 4–16-sample hemisphere kernel with stratified 4×4 tangent rotation, applies an optional depth-aware bilateral blur (`BlurRadius`, `DepthThreshold`), and multiplies ambient occlusion into the scene color (`AOTexture` exposes the AO map for inspection). +- **Depth of Field (`DepthOfFieldConfig`, `DepthOfFieldPass`)**: linearizes perspective or orthographic `[0, 1]` depth to compute a signed Circle of Confusion around `FocusDistance` ± `FocusRange`, then gathers an 18-tap two-ring disc bokeh blur that prevents blurred background pixels from bleeding across sharp in-focus silhouettes. +- **Bloom (`BloomConfig`, `BloomPass`)**: extracts bright LDR or HDR (`> 1.0`) pixels with a quadratic `Threshold` / `SoftKnee` curve, runs `BlurPasses` separable 9-tap Gaussian horizontal and vertical passes (optionally at half resolution via `HalfRes`), and composites the glow additively with `Intensity`. +- **Portability, lifecycle, and reference renders**: every pass uses fragment-only portable WGSL with explicit `textureSampleLevel` and algebraic/precomputed weights (no compute shaders or `exp`/`log2` instructions), running on both full and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0) profiles, supporting `Resize(dev, w, h)` and `Retained` device-loss recovery. Golden reference renders (`render3d/testdata/golden/post3d_bloom.png`, `post3d_ssao.png`, `post3d_dof.png`, and `post3d_combined.png`) verify each pass and the combined stack; `UPDATE_GOLDEN=1` rewrites them. diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 00a4c97a..4ca22855 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -1138,3 +1138,35 @@ for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { - **滤波与偏移**:`LocalShadowFilterHard`(一次最近邻比较采样)或 `LocalShadowFilterPCF3x3`(九次线性采样),配合常量 `DepthBias` 与世界空间 `NormalBias`。 - **第 3 绑定组**:`LocalShadowGroup` 即 `ShadowGroup`(3),方向光阴影、雾、IBL 与蒙皮也使用该组,因此一条带光照的 PBR 管线只能选用其中之一(`LitPBRPipelineOptions.SpotShadowLayout` 或 `PointShadowLayout`)。需要同时使用两种阴影、或第 3 组另有用途的自定义着色器,可用 `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` 放置绑定,并用 `LightWGSL` 中的 `shade_pbr_visibility(…, directional0_vis, point0_vis, spot0_vis)` 缩放各光源。 - **设备丢失与 CPU 参考实现**:设置 `Retained: true` 后,深度目标、采样器、缓冲、绑定组与深度管线会在设备丢失后恢复。`EvaluateSpotShadow`、`EvaluatePointShadow` 与 `PointShadowSelectFace` 与 WGSL 一一对应,`ShadePointVisibility` 配合 `LightVisibility` 可复现带光照的像素;测试将它们与 GPU 结果以及参考渲染图 `render3d/testdata/golden/local_shadow_spot.png` 和 `local_shadow_point.png`(`UPDATE_GOLDEN=1` 可重写)进行比较。 + +## 3D 后处理(`PostStack3D`、`BloomPass`、`SSAOPass`、`DepthOfFieldPass`) + +`PostStack3D` 通过离屏 3D 颜色+深度 `gpu.RenderTarget`(默认为 `FormatRGBA16Float` + `FormatDepth32Float`)组合屏幕空间环境光遮蔽(`SSAOPass`)、深度感知圆盘散景景深(`DepthOfFieldPass`)和 HDR 泛光(`BloomPass`),并将最终结果写入交换链或指定的目标纹理: + +```go +stack, err := render3d.NewPostStack3D(cx, dev, render3d.PostStack3DOptions{ + Width: uint32(w), + Height: uint32(h), + OutputFormat: dev.SurfaceFormat(), + Retained: true, + EnableSSAO: true, + SSAO: render3d.SSAOConfigFromCamera(cam), + EnableDoF: true, + DoF: render3d.DepthOfFieldConfigFromCamera(cam, 5.0, 2.0, 5.0), + EnableBloom: true, + Bloom: render3d.DefaultBloomConfig(), +}) + +// 在 OnFrame 中: +pass := stack.BeginScenePass(frame, core.RGB(0x0c1018)) +// ... 将 3D 网格绘制到 stack.SceneTarget() ... +pass.End() +_ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> 景深 -> Bloom -> 交换链 +frame.Submit() +``` + +- **可组合管线与独立通道**:`PostStack3D` 按固定顺序执行已启用的阶段——**SSAO → 景深 → Bloom**——中间结果在乒乓离屏渲染目标之间流转,最后一个阶段直接以 `OutputFormat` 输出(全部关闭时执行干净直通复制)。每个通道(`SSAOPass`、`DepthOfFieldPass`、`BloomPass`)也可独立创建,并通过 `PostPassRecorder`(`*gpu.Frame` 与 `*gpu.Encoder` 均已实现)作用于调用方自建的 `gpu.Texture` 颜色与深度附件。 +- **SSAO(`SSAOConfig`、`SSAOPass`)**:从 3D 深度缓冲重建视空间位置与保边法线,使用带 4×4 分层切线旋转的确定性 4–16 采样半球核计算遮蔽,支持可选的深度感知双边模糊(`BlurRadius`、`DepthThreshold`),并将环境光遮蔽乘入场景颜色(可通过 `AOTexture` 获取 AO 纹理)。 +- **景深(`DepthOfFieldConfig`、`DepthOfFieldPass`)**:支持透视与正交 `[0, 1]` 深度线性化,围绕 `FocusDistance` ± `FocusRange` 计算带符号弥散圆(CoC),并通过 18 采样双环圆盘散景模糊平滑虚化近景与远景,同时阻止背景模糊色溢入清晰的焦内轮廓。 +- **泛光(`BloomConfig`、`BloomPass`)**:用二次软拐点阈值曲线(`Threshold`、`SoftKnee`)提取 LDR 或 HDR(`> 1.0`)高亮像素,执行 `BlurPasses` 轮可分离 9 采样高斯横纵模糊(可通过 `HalfRes` 启用半分辨率以获得更宽柔和光晕),再以 `Intensity` 加法混合回场景。 +- **跨后端兼容性、生命周期与参考渲染**:所有通道均使用纯片元可移植 WGSL、显式 `textureSampleLevel` 以及代数/预计算权重(不依赖计算着色器,也不使用 `exp`/`log2` 指令),同时兼容完整能力与 `nsgotest.NoGPUCompute`(WebGL 2 / OpenGL ES 3.0)配置,并支持 `Resize(dev, w, h)` 与 `Retained` 设备丢失恢复。黄金参考图(`render3d/testdata/golden/post3d_bloom.png`、`post3d_ssao.png`、`post3d_dof.png` 与 `post3d_combined.png`)用于验证各个独立通道与组合栈;设置 `UPDATE_GOLDEN=1` 可重写参考图。 diff --git a/packages/game/render3d/post3d.go b/packages/game/render3d/post3d.go new file mode 100644 index 00000000..b954741e --- /dev/null +++ b/packages/game/render3d/post3d.go @@ -0,0 +1,3030 @@ +package render3d + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + "sync" + + "github.com/nsgo-dev/game/packages/game/math3d" + "github.com/nsgo-dev/game/packages/game/scene3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" +) + +// ErrInvalidPostProcess is wrapped by every validation error returned by 3D +// post-processing configurations and constructors ([BloomConfig.Validate], +// [SSAOConfig.Validate], [DepthOfFieldConfig.Validate], [NewBloomPass], +// [NewSSAOPass], [NewDepthOfFieldPass], and [NewPostStack3D]). +var ErrInvalidPostProcess = errors.New("render3d: invalid post-processing configuration") + +// PostPassRecorder is the minimal render-pass recording surface shared by +// [*gpu.Frame] (inside [gpu.View]'s OnFrame) and [*gpu.Encoder] (for headless +// or custom command encoding). +type PostPassRecorder interface { + BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass +} + +// Compile-time assertions that both *gpu.Frame and *gpu.Encoder implement PostPassRecorder. +var ( + _ PostPassRecorder = (*gpu.Frame)(nil) + _ PostPassRecorder = (*gpu.Encoder)(nil) +) + +const ( + postMaxBloomBlurPasses = 8 + postMaxSSAOSamples = 16 + postMinSSAOSamples = 4 + postMaxSSAOBlurRadius = 4 + postDoFTapCount = 18 + + postBloomExtractUniformSize = 16 + postBloomBlurUniformSize = 16 + postBloomCompositeUniformSize = 16 + postSSAOUniformSize = 64 + 64 + 16 + 16 + postMaxSSAOSamples*16 // 416 bytes + postSSAOBlurUniformSize = 64 + 16 // 80 bytes + postDoFCoCUniformSize = 32 + postDoFBokehUniformSize = 16 + postDoFTapCount*16 // 304 bytes +) + +// Shared fullscreen triangle vertex stage prepended to every post-processing WGSL module. +// Z is 0.0 (never 1.0) so fullscreen triangles never clip at the far depth plane. +const postFullscreenVertexWGSL = ` +struct PostVertexIn { + @location(0) pos: vec2, + @location(1) uv: vec2, +} + +struct PostVertexOut { + @builtin(position) pos: vec4, + @location(0) uv: vec2, +} + +@vertex +fn vs_post(in: PostVertexIn) -> PostVertexOut { + var out: PostVertexOut; + out.pos = vec4(in.pos, 0.0, 1.0); + out.uv = in.uv; + return out; +} +` + +const postBlitWGSL = postFullscreenVertexWGSL + ` +@group(0) @binding(0) var src_tex: texture_2d; +@group(0) @binding(1) var src_samp: sampler; + +@fragment +fn fs_blit(in: PostVertexOut) -> @location(0) vec4 { + return textureSampleLevel(src_tex, src_samp, in.uv, 0.0); +} +` + +const postBloomExtractWGSL = postFullscreenVertexWGSL + ` +struct BloomExtractUniform { + params: vec4, // x=threshold, y=soft_knee, z=0, w=0 +} + +@group(0) @binding(0) var u: BloomExtractUniform; +@group(0) @binding(1) var src_tex: texture_2d; +@group(0) @binding(2) var src_samp: sampler; + +@fragment +fn fs_bloom_extract(in: PostVertexOut) -> @location(0) vec4 { + let c = textureSampleLevel(src_tex, src_samp, in.uv, 0.0); + let threshold = u.params.x; + let soft_knee = u.params.y; + let br = max(c.r, max(c.g, c.b)); + let knee = threshold * soft_knee; + var contrib: f32 = 0.0; + if (knee > 0.0001) { + let soft = clamp(br - threshold + knee, 0.0, 2.0 * knee); + let soft_c = (soft * soft) / (4.0 * knee); + contrib = max(soft_c, br - threshold) / max(br, 0.0001); + } else if (br > threshold) { + contrib = (br - threshold) / max(br, 0.0001); + } + let bright = c.rgb * max(contrib, 0.0); + return vec4(bright, 1.0); +} +` + +// 9-tap separable Gaussian blur with precomputed weights (sum = 1.0, no exp/exp2 calls). +const postBloomBlurWGSL = postFullscreenVertexWGSL + ` +struct BloomBlurUniform { + step_dir: vec4, // x=dx, y=dy, z=0, w=0 +} + +@group(0) @binding(0) var u: BloomBlurUniform; +@group(0) @binding(1) var src_tex: texture_2d; +@group(0) @binding(2) var src_samp: sampler; + +@fragment +fn fs_bloom_blur(in: PostVertexOut) -> @location(0) vec4 { + let d = u.step_dir.xy; + var sum = textureSampleLevel(src_tex, src_samp, in.uv, 0.0).rgb * 0.22702703; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv + d * 1.0, 0.0).rgb * 0.19459459; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv - d * 1.0, 0.0).rgb * 0.19459459; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv + d * 2.0, 0.0).rgb * 0.12162162; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv - d * 2.0, 0.0).rgb * 0.12162162; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv + d * 3.0, 0.0).rgb * 0.05405405; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv - d * 3.0, 0.0).rgb * 0.05405405; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv + d * 4.0, 0.0).rgb * 0.01621622; + sum = sum + textureSampleLevel(src_tex, src_samp, in.uv - d * 4.0, 0.0).rgb * 0.01621622; + return vec4(sum, 1.0); +} +` + +const postBloomCompositeWGSL = postFullscreenVertexWGSL + ` +struct BloomCompositeUniform { + params: vec4, // x=intensity, y=0, z=0, w=0 +} + +@group(0) @binding(0) var u: BloomCompositeUniform; +@group(0) @binding(1) var scene_tex: texture_2d; +@group(0) @binding(2) var bloom_tex: texture_2d; +@group(0) @binding(3) var samp: sampler; + +@fragment +fn fs_bloom_composite(in: PostVertexOut) -> @location(0) vec4 { + let base = textureSampleLevel(scene_tex, samp, in.uv, 0.0); + let glow = textureSampleLevel(bloom_tex, samp, in.uv, 0.0).rgb; + return vec4(base.rgb + glow * u.params.x, base.a); +} +` + +const postSSAOWGSL = postFullscreenVertexWGSL + ` +struct SSAOUniform { + proj: mat4x4, + inv_proj: mat4x4, + params: vec4, // x=radius, y=bias, z=intensity, w=power + screen: vec4, // x=1/w, y=1/h, z=sample_count, w=0 + kernel: array, 16>, +} + +@group(0) @binding(0) var u: SSAOUniform; +@group(0) @binding(1) var depth_tex: texture_depth_2d; +@group(0) @binding(2) var depth_samp: sampler; + +fn ssao_view_pos(uv: vec2, d: f32) -> vec3 { + let ndc = vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0); + let vh = u.inv_proj * ndc; + return vh.xyz / vh.w; +} + +@fragment +fn fs_ssao(in: PostVertexOut) -> @location(0) vec4 { + let dC = textureSampleLevel(depth_tex, depth_samp, in.uv, 0); + if (dC >= 0.9999) { + return vec4(1.0, 1.0, 1.0, 1.0); + } + let intensity = u.params.z; + if (intensity <= 0.0) { + return vec4(1.0, 1.0, 1.0, 1.0); + } + + let tx = u.screen.x; + let ty = u.screen.y; + let pC = ssao_view_pos(in.uv, dC); + + let uvR = vec2(min(in.uv.x + tx, 1.0), in.uv.y); + let uvL = vec2(max(in.uv.x - tx, 0.0), in.uv.y); + let uvU = vec2(in.uv.x, max(in.uv.y - ty, 0.0)); + let uvD = vec2(in.uv.x, min(in.uv.y + ty, 1.0)); + + let pR = ssao_view_pos(uvR, textureSampleLevel(depth_tex, depth_samp, uvR, 0)); + let pL = ssao_view_pos(uvL, textureSampleLevel(depth_tex, depth_samp, uvL, 0)); + let pU = ssao_view_pos(uvU, textureSampleLevel(depth_tex, depth_samp, uvU, 0)); + let pD = ssao_view_pos(uvD, textureSampleLevel(depth_tex, depth_samp, uvD, 0)); + + var dx = pR - pC; + if (abs(pC.z - pL.z) < abs(pR.z - pC.z)) { + dx = pC - pL; + } + var dy = pU - pC; + if (abs(pC.z - pD.z) < abs(pU.z - pC.z)) { + dy = pC - pD; + } + let cross_n = cross(dx, dy); + var n = vec3(0.0, 0.0, 1.0); + if (dot(cross_n, cross_n) > 1e-12) { + n = normalize(cross_n); + } + + // Deterministic 4x4 stratified rotation angle in [0, 2*pi). + let ix = floor(in.pos.x); + let iy = floor(in.pos.y); + let cx = ix - floor(ix * 0.25) * 4.0; + let cy = iy - floor(iy * 0.25) * 4.0; + let cell = cy * 4.0 + cx; + let ridx = cell * 7.0 - floor(cell * 7.0 * 0.0625) * 16.0; + let ang = ridx * 0.39269908; + var rvec = vec3(cos(ang), sin(ang), 0.0); + if (abs(dot(rvec, n)) > 0.95) { + rvec = vec3(0.0, 0.0, 1.0); + if (abs(dot(rvec, n)) > 0.95) { + rvec = vec3(1.0, 0.0, 0.0); + } + } + let tangent = normalize(rvec - n * dot(rvec, n)); + let bitangent = cross(n, tangent); + + let radius = u.params.x; + let bias = u.params.y; + let power = u.params.w; + let count = i32(u.screen.z + 0.5); + + var occlusion: f32 = 0.0; + for (var i: i32 = 0; i < 16; i = i + 1) { + if (i >= count) { + break; + } + let k = u.kernel[i].xyz; + let offset = tangent * k.x + bitangent * k.y + n * k.z; + let spos = pC + offset * radius; + + let clip = u.proj * vec4(spos, 1.0); + if (clip.w <= 0.0001) { + continue; + } + let ndc = clip.xyz / clip.w; + let suv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + if (suv.x < 0.0 || suv.x > 1.0 || suv.y < 0.0 || suv.y > 1.0) { + continue; + } + let occ_d = textureSampleLevel(depth_tex, depth_samp, suv, 0); + if (occ_d >= 0.9999) { + continue; + } + let occ_pos = ssao_view_pos(suv, occ_d); + let dz = abs(pC.z - occ_pos.z); + let range_check = 1.0 - smoothstep(radius * 0.5, radius * 1.5, dz); + if (occ_pos.z >= spos.z + bias) { + occlusion = occlusion + range_check; + } + } + + let raw_ao = 1.0 - clamp((occlusion / max(u.screen.z, 1.0)) * intensity, 0.0, 1.0); + var ao = 1.0; + if (raw_ao < 0.9999) { + ao = pow(max(raw_ao, 0.0001), power); + } + return vec4(ao, ao, ao, 1.0); +} +` + +const postSSAOBlurWGSL = postFullscreenVertexWGSL + ` +struct SSAOBlurUniform { + inv_proj: mat4x4, + params: vec4, // x=1/w, y=1/h, z=blur_radius, w=depth_threshold +} + +@group(0) @binding(0) var u: SSAOBlurUniform; +@group(0) @binding(1) var ao_tex: texture_2d; +@group(0) @binding(2) var depth_tex: texture_depth_2d; +@group(0) @binding(3) var samp: sampler; + +fn blur_view_z(uv: vec2, d: f32) -> f32 { + let ndc = vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0); + let vh = u.inv_proj * ndc; + return vh.z / vh.w; +} + +@fragment +fn fs_ssao_blur(in: PostVertexOut) -> @location(0) vec4 { + let center_ao = textureSampleLevel(ao_tex, samp, in.uv, 0.0).r; + let r = i32(u.params.z + 0.5); + if (r <= 0) { + return vec4(center_ao, center_ao, center_ao, 1.0); + } + let center_d = textureSampleLevel(depth_tex, samp, in.uv, 0); + if (center_d >= 0.9999) { + return vec4(1.0, 1.0, 1.0, 1.0); + } + let center_z = blur_view_z(in.uv, center_d); + let thresh = max(u.params.w, 0.0001); + let inv_r2 = 1.0 / f32(r * r + 1); + + var acc: f32 = 0.0; + var wsum: f32 = 0.0; + for (var dy: i32 = -r; dy <= r; dy = dy + 1) { + for (var dx: i32 = -r; dx <= r; dx = dx + 1) { + let suv = clamp(in.uv + vec2(f32(dx) * u.params.x, f32(dy) * u.params.y), vec2(0.0), vec2(1.0)); + let sd = textureSampleLevel(depth_tex, samp, suv, 0); + if (sd >= 0.9999) { + continue; + } + let sz = blur_view_z(suv, sd); + let dz = abs(center_z - sz) / thresh; + let depth_w = 1.0 / (1.0 + dz * dz); + let dist2 = f32(dx * dx + dy * dy); + let spatial_w = 1.0 / (1.0 + dist2 * inv_r2); + let w = depth_w * spatial_w; + let sao = textureSampleLevel(ao_tex, samp, suv, 0.0).r; + acc = acc + sao * w; + wsum = wsum + w; + } + } + let out_ao = acc / max(wsum, 0.0001); + return vec4(out_ao, out_ao, out_ao, 1.0); +} +` + +const postSSAOCompositeWGSL = postFullscreenVertexWGSL + ` +@group(0) @binding(0) var scene_tex: texture_2d; +@group(0) @binding(1) var ao_tex: texture_2d; +@group(0) @binding(2) var samp: sampler; + +@fragment +fn fs_ssao_composite(in: PostVertexOut) -> @location(0) vec4 { + let scene = textureSampleLevel(scene_tex, samp, in.uv, 0.0); + let ao = textureSampleLevel(ao_tex, samp, in.uv, 0.0).r; + return vec4(scene.rgb * ao, scene.a); +} +` + +const postDoFCoCWGSL = postFullscreenVertexWGSL + ` +struct DoFCoCUniform { + params: vec4, // x=focus_distance, y=focus_range, z=near, w=far + flags: vec4, // x=ortho (0 or 1), y=0, z=0, w=0 +} + +@group(0) @binding(0) var u: DoFCoCUniform; +@group(0) @binding(1) var scene_tex: texture_2d; +@group(0) @binding(2) var depth_tex: texture_depth_2d; +@group(0) @binding(3) var color_samp: sampler; +@group(0) @binding(4) var depth_samp: sampler; + +@fragment +fn fs_dof_coc(in: PostVertexOut) -> @location(0) vec4 { + let scene = textureSampleLevel(scene_tex, color_samp, in.uv, 0.0); + let d = textureSampleLevel(depth_tex, depth_samp, in.uv, 0); + let near = u.params.z; + let far = u.params.w; + var lin_d: f32 = far; + if (u.flags.x > 0.5) { + lin_d = near + d * (far - near); + } else { + lin_d = (near * far) / max(far - d * (far - near), 0.0001); + } + let signed_coc = clamp((lin_d - u.params.x) / max(u.params.y, 0.0001), -1.0, 1.0); + let enc_coc = signed_coc * 0.5 + 0.5; + return vec4(scene.rgb, enc_coc); +} +` + +const postDoFBokehWGSL = postFullscreenVertexWGSL + ` +struct DoFBokehUniform { + params: vec4, // x=1/w, y=1/h, z=max_blur_radius, w=0 + taps: array, 18>, // x=dx, y=dy, z=ring_radius, w=0 +} + +@group(0) @binding(0) var u: DoFBokehUniform; +@group(0) @binding(1) var scene_tex: texture_2d; +@group(0) @binding(2) var coc_tex: texture_2d; +@group(0) @binding(3) var samp: sampler; + +@fragment +fn fs_dof_bokeh(in: PostVertexOut) -> @location(0) vec4 { + let base = textureSampleLevel(scene_tex, samp, in.uv, 0.0); + let max_radius = u.params.z; + if (max_radius <= 0.0001) { + return base; + } + let center_coc_sample = textureSampleLevel(coc_tex, samp, in.uv, 0.0); + let center_signed = center_coc_sample.a * 2.0 - 1.0; + let center_coc = abs(center_signed); + let texel = u.params.xy; + + var acc_rgb = base.rgb; + var acc_w: f32 = 1.0; + + for (var i: i32 = 0; i < 18; i = i + 1) { + let tap_info = u.taps[i]; + let r = tap_info.z; + let suv = clamp(in.uv + tap_info.xy * max_radius * texel, vec2(0.0), vec2(1.0)); + let tap = textureSampleLevel(coc_tex, samp, suv, 0.0); + let tap_signed = tap.a * 2.0 - 1.0; + let tap_coc = abs(tap_signed); + var eff_coc: f32 = min(tap_coc, center_coc); + if (tap_signed < 0.0) { + eff_coc = tap_coc; + } + let w = smoothstep(r - 0.25, r + 0.1, eff_coc); + acc_rgb = acc_rgb + tap.rgb * w; + acc_w = acc_w + w; + } + + return vec4(acc_rgb / acc_w, base.a); +} +` + +type postShaderCache struct { + once sync.Once + err error + blit *gpu.ShaderModule + bloomExtract *gpu.ShaderModule + bloomBlur *gpu.ShaderModule + bloomComposite *gpu.ShaderModule + ssao *gpu.ShaderModule + ssaoBlur *gpu.ShaderModule + ssaoComposite *gpu.ShaderModule + dofCoC *gpu.ShaderModule + dofBokeh *gpu.ShaderModule +} + +var postShaders postShaderCache + +func getPostShaders() (*postShaderCache, error) { + postShaders.once.Do(func() { + compile := func(label, src string) *gpu.ShaderModule { + if postShaders.err != nil { + return nil + } + m, err := gpu.CompileShader(gpu.ShaderDesc{Label: label, Source: src}) + if err != nil { + postShaders.err = fmt.Errorf("render3d: compile %s shader: %w", label, err) + return nil + } + return m + } + postShaders.blit = compile("render3d.post.blit", postBlitWGSL) + postShaders.bloomExtract = compile("render3d.post.bloom.extract", postBloomExtractWGSL) + postShaders.bloomBlur = compile("render3d.post.bloom.blur", postBloomBlurWGSL) + postShaders.bloomComposite = compile("render3d.post.bloom.composite", postBloomCompositeWGSL) + postShaders.ssao = compile("render3d.post.ssao", postSSAOWGSL) + postShaders.ssaoBlur = compile("render3d.post.ssao.blur", postSSAOBlurWGSL) + postShaders.ssaoComposite = compile("render3d.post.ssao.composite", postSSAOCompositeWGSL) + postShaders.dofCoC = compile("render3d.post.dof.coc", postDoFCoCWGSL) + postShaders.dofBokeh = compile("render3d.post.dof.bokeh", postDoFBokehWGSL) + }) + if postShaders.err != nil { + return nil, postShaders.err + } + return &postShaders, nil +} + +func postFullscreenVertexLayout() gpu.VertexBufferLayout { + return gpu.VertexBufferLayout{ + Stride: 4 * 4, + Attributes: []gpu.VertexAttribute{ + {Location: 0, Offset: 0, Format: gpu.VertexFloat32x2}, + {Location: 1, Offset: 2 * 4, Format: gpu.VertexFloat32x2}, + }, + } +} + +func createPostFullscreenVB(cx *core.Scope, dev *gpu.Device, retained bool) (*gpu.Buffer, error) { + verts := [12]float32{ + -1, -1, 0, 1, + 3, -1, 2, 1, + -1, 3, 0, -1, + } + var data [48]byte + for i, f := range verts { + binary.LittleEndian.PutUint32(data[i*4:], math.Float32bits(f)) + } + return dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: "render3d.post.fullscreen", + Size: uint64(len(data)), + Usage: gpu.UsageVertex, + Data: data[:], + Retained: retained, + }) +} + +func createPostPipeline( + cx *core.Scope, + dev *gpu.Device, + label string, + mod *gpu.ShaderModule, + fragEntry string, + layout *gpu.BindGroupLayout, + targetFormat gpu.TextureFormat, +) (*gpu.Pipeline, error) { + return dev.CreatePipeline(cx, gpu.PipelineDesc{ + Label: label, + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_post"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: fragEntry}, + Layouts: []*gpu.BindGroupLayout{layout}, + VertexBuffers: []gpu.VertexBufferLayout{postFullscreenVertexLayout()}, + Primitive: gpu.PrimitiveState{Topology: gpu.TopologyTriangleList, CullMode: gpu.CullNone}, + Targets: []gpu.ColorTargetState{{Format: targetFormat, WriteMask: gpu.ColorWriteAll}}, + }) +} + +func drawPostFullscreen(rec PostPassRecorder, label string, dst *gpu.Texture, pipe *gpu.Pipeline, bg *gpu.BindGroup, vb *gpu.Buffer) { + pass := rec.BeginRenderPass(gpu.RenderPassDesc{ + Label: label, + ColorAttachments: []gpu.ColorAttachment{{ + Texture: dst, + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + }}, + }) + pass.SetPipeline(pipe) + pass.SetBindGroup(0, bg) + pass.SetVertexBuffer(0, vb, 0) + pass.Draw(3, 0) + pass.End() +} + +func postPutFloat32(dst []byte, off int, v float32) { + binary.LittleEndian.PutUint32(dst[off:], math.Float32bits(v)) +} + +func postPutMat4(dst []byte, off int, m math3d.Mat4) { + for i, f := range m { + binary.LittleEndian.PutUint32(dst[off+i*4:], math.Float32bits(f)) + } +} + +func postResolveColorFormat(f gpu.TextureFormat) (gpu.TextureFormat, error) { + if f == gpu.FormatUndefined { + return gpu.FormatRGBA16Float, nil + } + if f.IsDepthStencil() || f.IsCompressed() { + return gpu.FormatUndefined, fmt.Errorf("%w: unsupported color target format %s", ErrInvalidPostProcess, f) + } + return f, nil +} + +func postResolveOutputFormat(dev *gpu.Device, f gpu.TextureFormat) (gpu.TextureFormat, error) { + if f == gpu.FormatUndefined { + if dev != nil && dev.SurfaceFormat() != gpu.FormatUndefined { + return dev.SurfaceFormat(), nil + } + return gpu.FormatRGBA8Unorm, nil + } + if f.IsDepthStencil() || f.IsCompressed() { + return gpu.FormatUndefined, fmt.Errorf("%w: unsupported output format %s", ErrInvalidPostProcess, f) + } + return f, nil +} + +func postResolveDepthFormat(f gpu.TextureFormat) (gpu.TextureFormat, error) { + if f == gpu.FormatUndefined { + return gpu.FormatDepth32Float, nil + } + if !f.IsDepth() { + return gpu.FormatUndefined, fmt.Errorf("%w: depth format %s has no depth aspect", ErrInvalidPostProcess, f) + } + return f, nil +} + +func postValidateSize(w, h uint32) error { + if w == 0 || h == 0 { + return fmt.Errorf("%w: dimensions %dx%d must be positive", ErrInvalidPostProcess, w, h) + } + return nil +} + +func postCloseAll(closers ...interface{ Close() error }) error { + var first error + for _, c := range closers { + if c == nil { + continue + } + // Guard against typed nil pointers stored in the interface. + switch v := c.(type) { + case *gpu.Buffer: + if v == nil { + continue + } + case *gpu.Sampler: + if v == nil { + continue + } + case *gpu.RenderTarget: + if v == nil { + continue + } + case *gpu.BindGroupLayout: + if v == nil { + continue + } + case *gpu.BindGroup: + if v == nil { + continue + } + case *gpu.Pipeline: + if v == nil { + continue + } + case *BloomPass: + if v == nil { + continue + } + case *SSAOPass: + if v == nil { + continue + } + case *DepthOfFieldPass: + if v == nil { + continue + } + } + if err := c.Close(); err != nil && first == nil { + first = err + } + } + return first +} + +// ============================================================================ +// Bloom +// ============================================================================ + +// BloomConfig tunes the 3D bloom post-processing pass. +type BloomConfig struct { + // Threshold is the minimum max-channel brightness that contributes to bloom (>= 0). + // Values above 1.0 target HDR emissive pixels in floating-point color targets. + Threshold float32 + // SoftKnee controls the smooth transition width around Threshold in [0, 1]. + // 0 produces a hard cutoff; 0.5 produces a gradual shoulder. + SoftKnee float32 + // Intensity scales the blurred glow added onto the scene color (>= 0). + // 0 leaves the scene unchanged. + Intensity float32 + // Radius scales the separable Gaussian blur tap stride in texels (>= 0). + Radius float32 + // BlurPasses is the number of horizontal+vertical separable Gaussian iterations in [1, 8]. + // 0 defaults to 2. + BlurPasses int + // HalfRes runs bright extraction and Gaussian blur at half resolution (max(1, w/2) x max(1, h/2)) + // for wider soft halos at a quarter of the pixel cost. + HalfRes bool +} + +// DefaultBloomConfig returns balanced defaults for 3D bloom. +func DefaultBloomConfig() BloomConfig { + return BloomConfig{ + Threshold: 0.8, + SoftKnee: 0.5, + Intensity: 0.6, + Radius: 1.5, + BlurPasses: 2, + HalfRes: true, + } +} + +// Validate checks that every field of c is finite and within its valid range. +// Every error wraps [ErrInvalidPostProcess]. +func (c BloomConfig) Validate() error { + if !finite(c.Threshold) || c.Threshold < 0 { + return fmt.Errorf("%w: bloom Threshold %v must be finite and >= 0", ErrInvalidPostProcess, c.Threshold) + } + if !finite(c.SoftKnee) || c.SoftKnee < 0 || c.SoftKnee > 1 { + return fmt.Errorf("%w: bloom SoftKnee %v must be finite and in [0, 1]", ErrInvalidPostProcess, c.SoftKnee) + } + if !finite(c.Intensity) || c.Intensity < 0 { + return fmt.Errorf("%w: bloom Intensity %v must be finite and >= 0", ErrInvalidPostProcess, c.Intensity) + } + if !finite(c.Radius) || c.Radius < 0 { + return fmt.Errorf("%w: bloom Radius %v must be finite and >= 0", ErrInvalidPostProcess, c.Radius) + } + if c.BlurPasses < 0 || c.BlurPasses > postMaxBloomBlurPasses { + return fmt.Errorf("%w: bloom BlurPasses %d must be in [0, %d]", ErrInvalidPostProcess, c.BlurPasses, postMaxBloomBlurPasses) + } + return nil +} + +func (c BloomConfig) normalized() BloomConfig { + if c.BlurPasses == 0 { + c.BlurPasses = 2 + } + return c +} + +// BloomPassOptions configures [NewBloomPass]. +type BloomPassOptions struct { + Label string + Width uint32 + Height uint32 + ColorFormat gpu.TextureFormat // internal blur target format; defaults to FormatRGBA16Float + OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm + Retained bool + Config BloomConfig +} + +// BloomPass executes bright-pixel extraction, separable 9-tap Gaussian blur +// across offscreen ping-pong render targets, and additive composition onto a +// destination target or swapchain. +type BloomPass struct { + cx *core.Scope + label string + width uint32 + height uint32 + blurW uint32 + blurH uint32 + colorFormat gpu.TextureFormat + outputFormat gpu.TextureFormat + retained bool + cfg BloomConfig + + vb *gpu.Buffer + linearSamp *gpu.Sampler + extractBuf *gpu.Buffer + horizBlurBuf *gpu.Buffer + vertBlurBuf *gpu.Buffer + compBuf *gpu.Buffer + + singleLayout *gpu.BindGroupLayout // uniform + 1 tex + 1 samp + compLayout *gpu.BindGroupLayout // uniform + 2 tex + 1 samp + + extractPipe *gpu.Pipeline + blurPipe *gpu.Pipeline + compPipe *gpu.Pipeline + compOutPipe *gpu.Pipeline // nil when outputFormat == colorFormat + + pingRT *gpu.RenderTarget + pongRT *gpu.RenderTarget + + horizBlurBG *gpu.BindGroup // reads pingRT + vertBlurBG *gpu.BindGroup // reads pongRT + + cachedExtractTex *gpu.Texture + cachedExtractBG *gpu.BindGroup + cachedCompTex *gpu.Texture + cachedCompBG *gpu.BindGroup + + closed bool +} + +// NewBloomPass creates a scope-owned [BloomPass] on dev. +func NewBloomPass(cx *core.Scope, dev *gpu.Device, opts BloomPassOptions) (*BloomPass, error) { + if err := postValidateSize(opts.Width, opts.Height); err != nil { + return nil, err + } + if err := opts.Config.Validate(); err != nil { + return nil, err + } + colorFmt, err := postResolveColorFormat(opts.ColorFormat) + if err != nil { + return nil, err + } + outFmt, err := postResolveOutputFormat(dev, opts.OutputFormat) + if err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + shaders, err := getPostShaders() + if err != nil { + return nil, err + } + + label := opts.Label + if label == "" { + label = "render3d.bloom" + } + + p := &BloomPass{ + cx: cx, + label: label, + width: opts.Width, + height: opts.Height, + colorFormat: colorFmt, + outputFormat: outFmt, + retained: opts.Retained, + cfg: opts.Config.normalized(), + } + + if p.vb, err = createPostFullscreenVB(cx, dev, opts.Retained); err != nil { + _ = p.Close() + return nil, err + } + if p.linearSamp, err = dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".linear", + MinFilter: gpu.FilterLinear, + MagFilter: gpu.FilterLinear, + MipmapFilter: gpu.FilterLinear, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + mkUniform := func(name string, size uint64) (*gpu.Buffer, error) { + return dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + "." + name, + Size: size, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: opts.Retained, + }) + } + if p.extractBuf, err = mkUniform("extract.u", postBloomExtractUniformSize); err != nil { + _ = p.Close() + return nil, err + } + if p.horizBlurBuf, err = mkUniform("blur.h.u", postBloomBlurUniformSize); err != nil { + _ = p.Close() + return nil, err + } + if p.vertBlurBuf, err = mkUniform("blur.v.u", postBloomBlurUniformSize); err != nil { + _ = p.Close() + return nil, err + } + if p.compBuf, err = mkUniform("comp.u", postBloomCompositeUniformSize); err != nil { + _ = p.Close() + return nil, err + } + + if err := p.buildPipelines(dev, shaders); err != nil { + _ = p.Close() + return nil, err + } + if err := p.allocTargets(dev); err != nil { + _ = p.Close() + return nil, err + } + return p, nil +} + +func (p *BloomPass) buildPipelines(dev *gpu.Device, shaders *postShaderCache) error { + singleLayout, err := dev.CreateBindGroupLayoutDesc(p.cx, gpu.BindGroupLayoutDesc{ + Label: p.label + ".single", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + return err + } + compLayout, err := dev.CreateBindGroupLayoutDesc(p.cx, gpu.BindGroupLayoutDesc{ + Label: p.label + ".comp", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + _ = singleLayout.Close() + return err + } + extractPipe, err := createPostPipeline(p.cx, dev, p.label+".extract", shaders.bloomExtract, "fs_bloom_extract", singleLayout, p.colorFormat) + if err != nil { + _ = postCloseAll(singleLayout, compLayout) + return err + } + blurPipe, err := createPostPipeline(p.cx, dev, p.label+".blur", shaders.bloomBlur, "fs_bloom_blur", singleLayout, p.colorFormat) + if err != nil { + _ = postCloseAll(extractPipe, singleLayout, compLayout) + return err + } + compPipe, err := createPostPipeline(p.cx, dev, p.label+".comp", shaders.bloomComposite, "fs_bloom_composite", compLayout, p.colorFormat) + if err != nil { + _ = postCloseAll(extractPipe, blurPipe, singleLayout, compLayout) + return err + } + var compOutPipe *gpu.Pipeline + if p.outputFormat != p.colorFormat { + compOutPipe, err = createPostPipeline(p.cx, dev, p.label+".comp.out", shaders.bloomComposite, "fs_bloom_composite", compLayout, p.outputFormat) + if err != nil { + _ = postCloseAll(extractPipe, blurPipe, compPipe, singleLayout, compLayout) + return err + } + } + _ = postCloseAll(p.cachedExtractBG, p.cachedCompBG, p.horizBlurBG, p.vertBlurBG, + p.extractPipe, p.blurPipe, p.compPipe, p.compOutPipe, p.singleLayout, p.compLayout) + p.singleLayout = singleLayout + p.compLayout = compLayout + p.extractPipe = extractPipe + p.blurPipe = blurPipe + p.compPipe = compPipe + p.compOutPipe = compOutPipe + p.horizBlurBG = nil + p.vertBlurBG = nil + p.cachedExtractTex = nil + p.cachedExtractBG = nil + p.cachedCompTex = nil + p.cachedCompBG = nil + return nil +} + +func (p *BloomPass) rebuildBlurBindGroups(dev *gpu.Device) error { + hBG, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".blur.h", + Layout: p.singleLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.horizBlurBuf, Size: postBloomBlurUniformSize}, + {Binding: 1, Texture: p.pingRT.Color}, + {Binding: 2, Sampler: p.linearSamp}, + }, + }) + if err != nil { + return err + } + vBG, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".blur.v", + Layout: p.singleLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.vertBlurBuf, Size: postBloomBlurUniformSize}, + {Binding: 1, Texture: p.pongRT.Color}, + {Binding: 2, Sampler: p.linearSamp}, + }, + }) + if err != nil { + _ = hBG.Close() + return err + } + _ = postCloseAll(p.horizBlurBG, p.vertBlurBG) + p.horizBlurBG = hBG + p.vertBlurBG = vBG + return nil +} + +func (p *BloomPass) allocTargets(dev *gpu.Device) error { + bw, bh := p.width, p.height + if p.cfg.HalfRes { + bw = max(1, bw/2) + bh = max(1, bh/2) + } + p.blurW, p.blurH = bw, bh + + ping, err := dev.CreateRenderTarget(p.cx, gpu.RenderTargetDesc{ + Label: p.label + ".ping", + Width: bw, + Height: bh, + ColorFormat: p.colorFormat, + Retained: p.retained, + }) + if err != nil { + return err + } + pong, err := dev.CreateRenderTarget(p.cx, gpu.RenderTargetDesc{ + Label: p.label + ".pong", + Width: bw, + Height: bh, + ColorFormat: p.colorFormat, + Retained: p.retained, + }) + if err != nil { + _ = ping.Close() + return err + } + _ = postCloseAll(p.horizBlurBG, p.vertBlurBG, p.cachedCompBG, p.pingRT, p.pongRT) + p.pingRT = ping + p.pongRT = pong + p.horizBlurBG = nil + p.vertBlurBG = nil + p.cachedCompTex = nil + p.cachedCompBG = nil + return p.rebuildBlurBindGroups(dev) +} + +// Config returns the pass's current normalized [BloomConfig]. +func (p *BloomPass) Config() BloomConfig { + if p == nil { + return BloomConfig{} + } + return p.cfg +} + +// SetConfig validates and updates the bloom parameters. Changing [BloomConfig.HalfRes] +// takes effect on the next [BloomPass.Resize] or [BloomPass.Apply]. +func (p *BloomPass) SetConfig(cfg BloomConfig) error { + if p == nil || p.closed { + return fmt.Errorf("%w: bloom pass is not valid", ErrInvalidPostProcess) + } + if err := cfg.Validate(); err != nil { + return err + } + p.cfg = cfg.normalized() + return nil +} + +// Width returns the configured scene width in pixels. +func (p *BloomPass) Width() uint32 { + if p == nil { + return 0 + } + return p.width +} + +// Height returns the configured scene height in pixels. +func (p *BloomPass) Height() uint32 { + if p == nil { + return 0 + } + return p.height +} + +// Valid reports whether the pass is open and its GPU resources are live. +func (p *BloomPass) Valid() bool { + return p != nil && !p.closed && + p.vb.Valid() && p.pingRT.Valid() && p.pongRT.Valid() && + p.extractPipe.Valid() && p.blurPipe.Valid() && p.compPipe.Valid() && + (p.compOutPipe == nil || p.compOutPipe.Valid()) +} + +func (p *BloomPass) ensureLive(dev *gpu.Device) error { + if p == nil || p.closed { + return fmt.Errorf("%w: bloom pass is not valid", ErrInvalidPostProcess) + } + if p.Valid() && p.horizBlurBG.Valid() && p.vertBlurBG.Valid() { + return nil + } + if !p.retained || !p.vb.Valid() || !p.pingRT.Valid() || !p.pongRT.Valid() { + return fmt.Errorf("%w: bloom pass is not valid", ErrInvalidPostProcess) + } + shaders, err := getPostShaders() + if err != nil { + return err + } + if err := p.buildPipelines(dev, shaders); err != nil { + return err + } + return p.rebuildBlurBindGroups(dev) +} + +// Resize recreates the pass's offscreen blur render targets for a new scene size. +func (p *BloomPass) Resize(dev *gpu.Device, width, height uint32) error { + if p == nil || p.closed { + return fmt.Errorf("%w: bloom pass is not valid", ErrInvalidPostProcess) + } + if err := postValidateSize(width, height); err != nil { + return err + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + wantBW, wantBH := width, height + if p.cfg.HalfRes { + wantBW = max(1, width/2) + wantBH = max(1, height/2) + } + if p.width == width && p.height == height && p.blurW == wantBW && p.blurH == wantBH && p.Valid() { + return nil + } + if !p.singleLayout.Valid() && p.retained { + shaders, err := getPostShaders() + if err != nil { + return err + } + if err := p.buildPipelines(dev, shaders); err != nil { + return err + } + } + p.width, p.height = width, height + return p.allocTargets(dev) +} + +// Apply runs bright extraction, separable blur, and additive composite from srcColor +// into dstColor (nil writes to the swapchain using OutputFormat). +func (p *BloomPass) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, dstColor *gpu.Texture) error { + return p.applyWithOutput(dev, rec, srcColor, dstColor, dstColor == nil) +} + +func (p *BloomPass) applyWithOutput(dev *gpu.Device, rec PostPassRecorder, srcColor, dstColor *gpu.Texture, useOutputFormat bool) error { + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if err := p.ensureLive(dev); err != nil { + return err + } + if rec == nil { + return fmt.Errorf("%w: nil render pass recorder", ErrInvalidPostProcess) + } + if srcColor == nil || !srcColor.Valid() { + return fmt.Errorf("%w: invalid source color texture", ErrInvalidPostProcess) + } + if dstColor != nil && !dstColor.Valid() { + return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) + } + // Ensure half-res/full-res internal targets match current config. + wantBW, wantBH := p.width, p.height + if p.cfg.HalfRes { + wantBW = max(1, p.width/2) + wantBH = max(1, p.height/2) + } + if p.blurW != wantBW || p.blurH != wantBH { + if err := p.allocTargets(dev); err != nil { + return err + } + } + + // Upload uniforms (each pass reads its own dedicated uniform buffer). + var extractData [postBloomExtractUniformSize]byte + postPutFloat32(extractData[:], 0, p.cfg.Threshold) + postPutFloat32(extractData[:], 4, p.cfg.SoftKnee) + dev.WriteBuffer(p.extractBuf, 0, extractData[:]) + + stepX := p.cfg.Radius / float32(p.blurW) + stepY := p.cfg.Radius / float32(p.blurH) + var hData [postBloomBlurUniformSize]byte + postPutFloat32(hData[:], 0, stepX) + postPutFloat32(hData[:], 4, 0) + dev.WriteBuffer(p.horizBlurBuf, 0, hData[:]) + + var vData [postBloomBlurUniformSize]byte + postPutFloat32(vData[:], 0, 0) + postPutFloat32(vData[:], 4, stepY) + dev.WriteBuffer(p.vertBlurBuf, 0, vData[:]) + + var compData [postBloomCompositeUniformSize]byte + postPutFloat32(compData[:], 0, p.cfg.Intensity) + dev.WriteBuffer(p.compBuf, 0, compData[:]) + + if p.cachedExtractTex != srcColor || !p.cachedExtractBG.Valid() { + bg, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".extract.bg", + Layout: p.singleLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.extractBuf, Size: postBloomExtractUniformSize}, + {Binding: 1, Texture: srcColor}, + {Binding: 2, Sampler: p.linearSamp}, + }, + }) + if err != nil { + return err + } + _ = postCloseAll(p.cachedExtractBG) + p.cachedExtractTex = srcColor + p.cachedExtractBG = bg + } + if p.cachedCompTex != srcColor || !p.cachedCompBG.Valid() { + bg, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".comp.bg", + Layout: p.compLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.compBuf, Size: postBloomCompositeUniformSize}, + {Binding: 1, Texture: srcColor}, + {Binding: 2, Texture: p.pingRT.Color}, + {Binding: 3, Sampler: p.linearSamp}, + }, + }) + if err != nil { + return err + } + _ = postCloseAll(p.cachedCompBG) + p.cachedCompTex = srcColor + p.cachedCompBG = bg + } + + // 1. Bright extract -> pingRT. + drawPostFullscreen(rec, p.label+".extract", p.pingRT.Color, p.extractPipe, p.cachedExtractBG, p.vb) + + // 2. Separable Gaussian blur iterations: pingRT -> pongRT -> pingRT. + if p.cfg.Intensity > 0 && p.cfg.Radius > 0 { + for range p.cfg.BlurPasses { + drawPostFullscreen(rec, p.label+".blur.h", p.pongRT.Color, p.blurPipe, p.horizBlurBG, p.vb) + drawPostFullscreen(rec, p.label+".blur.v", p.pingRT.Color, p.blurPipe, p.vertBlurBG, p.vb) + } + } + + // 3. Additive composite -> dstColor (or swapchain). + pipe := p.compPipe + if useOutputFormat && p.compOutPipe != nil { + pipe = p.compOutPipe + } + drawPostFullscreen(rec, p.label+".composite", dstColor, pipe, p.cachedCompBG, p.vb) + return nil +} + +// Close releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once. +func (p *BloomPass) Close() error { + if p == nil || p.closed { + return nil + } + p.closed = true + p.cachedExtractTex = nil + p.cachedCompTex = nil + return postCloseAll( + p.cachedExtractBG, p.cachedCompBG, p.horizBlurBG, p.vertBlurBG, + p.pingRT, p.pongRT, + p.extractPipe, p.blurPipe, p.compPipe, p.compOutPipe, + p.singleLayout, p.compLayout, + p.extractBuf, p.horizBlurBuf, p.vertBlurBuf, p.compBuf, + p.linearSamp, p.vb, + ) +} + +// ============================================================================ +// SSAO +// ============================================================================ + +// SSAOConfig tunes screen-space ambient occlusion from a 3D depth buffer. +type SSAOConfig struct { + // Radius is the view-space sampling hemisphere radius in world units (> 0). Default: 0.6. + Radius float32 + // Bias offsets depth comparisons in view-space units to suppress self-occlusion acne (>= 0). Default: 0.025. + Bias float32 + // Intensity scales the occlusion darkening strength in [0, 4]. 0 leaves the scene unchanged. Default: 1.2. + Intensity float32 + // Power raises ambient visibility (ao^Power) to tune crevice contrast (> 0). Default: 1.5. + Power float32 + // SampleCount is the number of deterministic hemisphere kernel samples in [4, 16]. 0 defaults to 12. + SampleCount int + // BlurRadius is the depth-aware bilateral blur half-width in texels in [0, 4]. 0 disables blur. + BlurRadius int + // DepthThreshold is the view-space depth tolerance for bilateral blur edge preservation (> 0). Default: 0.2. + DepthThreshold float32 + // Near and Far are fallback perspective clip planes used only when ProjMatrix is zero. + Near float32 + Far float32 + // ProjMatrix is the camera's [0, 1] NDC depth projection matrix (e.g. cam.ProjMatrix()). + ProjMatrix math3d.Mat4 + // InvProjMatrix optionally supplies ProjMatrix.Inverse(); when zero, it is computed from ProjMatrix. + InvProjMatrix math3d.Mat4 +} + +// DefaultSSAOConfig returns balanced defaults for 3D SSAO. +func DefaultSSAOConfig() SSAOConfig { + return SSAOConfig{ + Radius: 0.6, + Bias: 0.025, + Intensity: 1.2, + Power: 1.5, + SampleCount: 12, + BlurRadius: 2, + DepthThreshold: 0.2, + Near: 0.1, + Far: 100.0, + } +} + +// SSAOConfigFromCamera initializes an [SSAOConfig] using cam's projection matrix +// and clip planes combined with [DefaultSSAOConfig] quality settings. +func SSAOConfigFromCamera(cam *scene3d.Camera) SSAOConfig { + cfg := DefaultSSAOConfig() + if cam != nil { + cfg.ProjMatrix = cam.ProjMatrix() + cfg.Near = cam.Projection.Near + cfg.Far = cam.Projection.Far + } + return cfg +} + +// Validate checks that every field of c is finite and within its valid range. +// Every error wraps [ErrInvalidPostProcess]. +func (c SSAOConfig) Validate() error { + if !finite(c.Radius) || c.Radius <= 0 { + return fmt.Errorf("%w: ssao Radius %v must be finite and > 0", ErrInvalidPostProcess, c.Radius) + } + if !finite(c.Bias) || c.Bias < 0 { + return fmt.Errorf("%w: ssao Bias %v must be finite and >= 0", ErrInvalidPostProcess, c.Bias) + } + if !finite(c.Intensity) || c.Intensity < 0 || c.Intensity > 4 { + return fmt.Errorf("%w: ssao Intensity %v must be finite and in [0, 4]", ErrInvalidPostProcess, c.Intensity) + } + if !finite(c.Power) || c.Power <= 0 { + return fmt.Errorf("%w: ssao Power %v must be finite and > 0", ErrInvalidPostProcess, c.Power) + } + if c.SampleCount != 0 && (c.SampleCount < postMinSSAOSamples || c.SampleCount > postMaxSSAOSamples) { + return fmt.Errorf("%w: ssao SampleCount %d must be 0 or in [%d, %d]", ErrInvalidPostProcess, c.SampleCount, postMinSSAOSamples, postMaxSSAOSamples) + } + if c.BlurRadius < 0 || c.BlurRadius > postMaxSSAOBlurRadius { + return fmt.Errorf("%w: ssao BlurRadius %d must be in [0, %d]", ErrInvalidPostProcess, c.BlurRadius, postMaxSSAOBlurRadius) + } + if !finite(c.DepthThreshold) || c.DepthThreshold < 0 { + return fmt.Errorf("%w: ssao DepthThreshold %v must be finite and >= 0", ErrInvalidPostProcess, c.DepthThreshold) + } + if c.ProjMatrix != (math3d.Mat4{}) { + for _, f := range c.ProjMatrix { + if !finite(f) { + return fmt.Errorf("%w: ssao ProjMatrix contains non-finite value", ErrInvalidPostProcess) + } + } + if c.InvProjMatrix == (math3d.Mat4{}) { + if _, ok := c.ProjMatrix.Inverse(); !ok { + return fmt.Errorf("%w: ssao ProjMatrix is singular", ErrInvalidPostProcess) + } + } + } else { + if !finite(c.Near) || !finite(c.Far) || c.Near <= 0 || c.Far <= c.Near { + return fmt.Errorf("%w: ssao requires invertible ProjMatrix or 0 < Near < Far (got Near=%v, Far=%v)", ErrInvalidPostProcess, c.Near, c.Far) + } + } + if c.InvProjMatrix != (math3d.Mat4{}) { + for _, f := range c.InvProjMatrix { + if !finite(f) { + return fmt.Errorf("%w: ssao InvProjMatrix contains non-finite value", ErrInvalidPostProcess) + } + } + } + return nil +} + +func (c SSAOConfig) normalized() SSAOConfig { + if c.SampleCount == 0 { + c.SampleCount = 12 + } + if c.DepthThreshold == 0 { + c.DepthThreshold = 0.2 + } + return c +} + +func (c SSAOConfig) resolveMatrices(w, h uint32) (proj, invProj math3d.Mat4) { + if c.ProjMatrix != (math3d.Mat4{}) { + proj = c.ProjMatrix + } else { + aspect := float32(w) / float32(max(h, 1)) + proj = math3d.Perspective(math3d.DegToRad(60), aspect, c.Near, c.Far) + } + if c.InvProjMatrix != (math3d.Mat4{}) { + invProj = c.InvProjMatrix + } else if inv, ok := proj.Inverse(); ok { + invProj = inv + } else { + invProj = math3d.Mat4Identity() + } + return proj, invProj +} + +// buildSSAOKernel generates a deterministic low-discrepancy hemisphere sample kernel +// in tangent space (+Z along surface normal) with samples concentrated closer to the origin. +func buildSSAOKernel(count int) [postMaxSSAOSamples][4]float32 { + var out [postMaxSSAOSamples][4]float32 + if count < 1 { + count = 1 + } + if count > postMaxSSAOSamples { + count = postMaxSSAOSamples + } + const goldenAngle = 2.39996322972865332 // pi * (3 - sqrt(5)) + for i := range count { + t := (float64(i) + 0.5) / float64(count) + // Cosine-weighted elevation in [0.15, 0.98] avoids grazing-angle self-occlusion. + z := 0.15 + 0.83*t + rXY := math.Sqrt(max(0, 1.0-z*z)) + theta := float64(i) * goldenAngle + x := math.Cos(theta) * rXY + y := math.Sin(theta) * rXY + // Accelerating radial distribution puts more taps close to contact crevices. + frac := float64(i) / float64(count) + scale := 0.12 + 0.88*(frac*frac) + out[i] = [4]float32{ + float32(x * scale), + float32(y * scale), + float32(z * scale), + 0, + } + } + return out +} + +// SSAOPassOptions configures [NewSSAOPass]. +type SSAOPassOptions struct { + Label string + Width uint32 + Height uint32 + ColorFormat gpu.TextureFormat // intermediate color format; defaults to FormatRGBA16Float + OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm + Retained bool + Config SSAOConfig +} + +// SSAOPass computes screen-space ambient occlusion from a 3D depth texture, +// optionally filters it with a depth-aware bilateral blur, and multiplies the +// resulting occlusion factor into a scene color texture. +type SSAOPass struct { + cx *core.Scope + label string + width uint32 + height uint32 + colorFormat gpu.TextureFormat + outputFormat gpu.TextureFormat + retained bool + cfg SSAOConfig + + vb *gpu.Buffer + nearestSamp *gpu.Sampler + linearSamp *gpu.Sampler + ssaoBuf *gpu.Buffer + blurBuf *gpu.Buffer + + ssaoLayout *gpu.BindGroupLayout + blurLayout *gpu.BindGroupLayout + compLayout *gpu.BindGroupLayout + + ssaoPipe *gpu.Pipeline + blurPipe *gpu.Pipeline + compPipe *gpu.Pipeline + compOutPipe *gpu.Pipeline + + aoRawRT *gpu.RenderTarget + aoBlurRT *gpu.RenderTarget + + cachedSSAODepth *gpu.Texture + cachedSSAOBG *gpu.BindGroup + cachedBlurDepth *gpu.Texture + cachedBlurBG *gpu.BindGroup + cachedCompSrc *gpu.Texture + cachedCompAO *gpu.Texture + cachedCompBG *gpu.BindGroup + + lastAO *gpu.Texture + closed bool +} + +// NewSSAOPass creates a scope-owned [SSAOPass] on dev. +func NewSSAOPass(cx *core.Scope, dev *gpu.Device, opts SSAOPassOptions) (*SSAOPass, error) { + if err := postValidateSize(opts.Width, opts.Height); err != nil { + return nil, err + } + if err := opts.Config.Validate(); err != nil { + return nil, err + } + colorFmt, err := postResolveColorFormat(opts.ColorFormat) + if err != nil { + return nil, err + } + outFmt, err := postResolveOutputFormat(dev, opts.OutputFormat) + if err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + shaders, err := getPostShaders() + if err != nil { + return nil, err + } + + label := opts.Label + if label == "" { + label = "render3d.ssao" + } + + p := &SSAOPass{ + cx: cx, + label: label, + width: opts.Width, + height: opts.Height, + colorFormat: colorFmt, + outputFormat: outFmt, + retained: opts.Retained, + cfg: opts.Config.normalized(), + } + + if p.vb, err = createPostFullscreenVB(cx, dev, opts.Retained); err != nil { + _ = p.Close() + return nil, err + } + if p.nearestSamp, err = dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".nearest", + MinFilter: gpu.FilterNearest, + MagFilter: gpu.FilterNearest, + MipmapFilter: gpu.FilterNearest, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + if p.linearSamp, err = dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".linear", + MinFilter: gpu.FilterLinear, + MagFilter: gpu.FilterLinear, + MipmapFilter: gpu.FilterLinear, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + if p.ssaoBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".u", + Size: postSSAOUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + if p.blurBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".blur.u", + Size: postSSAOBlurUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + + if err := p.buildPipelines(dev, shaders); err != nil { + _ = p.Close() + return nil, err + } + if err := p.allocTargets(dev); err != nil { + _ = p.Close() + return nil, err + } + return p, nil +} + +func (p *SSAOPass) buildPipelines(dev *gpu.Device, shaders *postShaderCache) error { + ssaoLayout, err := dev.CreateBindGroupLayoutDesc(p.cx, gpu.BindGroupLayoutDesc{ + Label: p.label + ".layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + return err + } + blurLayout, err := dev.CreateBindGroupLayoutDesc(p.cx, gpu.BindGroupLayoutDesc{ + Label: p.label + ".blur.layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + _ = ssaoLayout.Close() + return err + } + compLayout, err := dev.CreateBindGroupLayoutDesc(p.cx, gpu.BindGroupLayoutDesc{ + Label: p.label + ".comp.layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + _ = postCloseAll(ssaoLayout, blurLayout) + return err + } + ssaoPipe, err := createPostPipeline(p.cx, dev, p.label+".pipe", shaders.ssao, "fs_ssao", ssaoLayout, gpu.FormatRGBA8Unorm) + if err != nil { + _ = postCloseAll(ssaoLayout, blurLayout, compLayout) + return err + } + blurPipe, err := createPostPipeline(p.cx, dev, p.label+".blur.pipe", shaders.ssaoBlur, "fs_ssao_blur", blurLayout, gpu.FormatRGBA8Unorm) + if err != nil { + _ = postCloseAll(ssaoPipe, ssaoLayout, blurLayout, compLayout) + return err + } + compPipe, err := createPostPipeline(p.cx, dev, p.label+".comp.pipe", shaders.ssaoComposite, "fs_ssao_composite", compLayout, p.colorFormat) + if err != nil { + _ = postCloseAll(ssaoPipe, blurPipe, ssaoLayout, blurLayout, compLayout) + return err + } + var compOutPipe *gpu.Pipeline + if p.outputFormat != p.colorFormat { + compOutPipe, err = createPostPipeline(p.cx, dev, p.label+".comp.out", shaders.ssaoComposite, "fs_ssao_composite", compLayout, p.outputFormat) + if err != nil { + _ = postCloseAll(ssaoPipe, blurPipe, compPipe, ssaoLayout, blurLayout, compLayout) + return err + } + } + _ = postCloseAll(p.cachedSSAOBG, p.cachedBlurBG, p.cachedCompBG, + p.ssaoPipe, p.blurPipe, p.compPipe, p.compOutPipe, + p.ssaoLayout, p.blurLayout, p.compLayout) + p.ssaoLayout = ssaoLayout + p.blurLayout = blurLayout + p.compLayout = compLayout + p.ssaoPipe = ssaoPipe + p.blurPipe = blurPipe + p.compPipe = compPipe + p.compOutPipe = compOutPipe + p.cachedSSAODepth = nil + p.cachedSSAOBG = nil + p.cachedBlurDepth = nil + p.cachedBlurBG = nil + p.cachedCompSrc = nil + p.cachedCompAO = nil + p.cachedCompBG = nil + return nil +} + +func (p *SSAOPass) allocTargets(dev *gpu.Device) error { + rawRT, err := dev.CreateRenderTarget(p.cx, gpu.RenderTargetDesc{ + Label: p.label + ".raw", + Width: p.width, + Height: p.height, + ColorFormat: gpu.FormatRGBA8Unorm, + Retained: p.retained, + }) + if err != nil { + return err + } + blurRT, err := dev.CreateRenderTarget(p.cx, gpu.RenderTargetDesc{ + Label: p.label + ".blur", + Width: p.width, + Height: p.height, + ColorFormat: gpu.FormatRGBA8Unorm, + Retained: p.retained, + }) + if err != nil { + _ = rawRT.Close() + return err + } + _ = postCloseAll(p.cachedBlurBG, p.cachedCompBG, p.aoRawRT, p.aoBlurRT) + p.aoRawRT = rawRT + p.aoBlurRT = blurRT + p.cachedBlurDepth = nil + p.cachedBlurBG = nil + p.cachedCompSrc = nil + p.cachedCompAO = nil + p.cachedCompBG = nil + p.lastAO = rawRT.Color + return nil +} + +// Config returns the pass's current normalized [SSAOConfig]. +func (p *SSAOPass) Config() SSAOConfig { + if p == nil { + return SSAOConfig{} + } + return p.cfg +} + +// SetConfig validates and updates the SSAO parameters. +func (p *SSAOPass) SetConfig(cfg SSAOConfig) error { + if p == nil || p.closed { + return fmt.Errorf("%w: ssao pass is not valid", ErrInvalidPostProcess) + } + if err := cfg.Validate(); err != nil { + return err + } + p.cfg = cfg.normalized() + return nil +} + +// Width returns the configured target width in pixels. +func (p *SSAOPass) Width() uint32 { + if p == nil { + return 0 + } + return p.width +} + +// Height returns the configured target height in pixels. +func (p *SSAOPass) Height() uint32 { + if p == nil { + return 0 + } + return p.height +} + +// AOTexture returns the most recently computed ambient occlusion texture +// (blurred when BlurRadius > 0, raw otherwise). +func (p *SSAOPass) AOTexture() *gpu.Texture { + if p == nil || p.closed { + return nil + } + return p.lastAO +} + +// Valid reports whether the pass is open and its GPU resources are live. +func (p *SSAOPass) Valid() bool { + return p != nil && !p.closed && + p.vb.Valid() && p.aoRawRT.Valid() && p.aoBlurRT.Valid() && + p.ssaoPipe.Valid() && p.blurPipe.Valid() && p.compPipe.Valid() && + (p.compOutPipe == nil || p.compOutPipe.Valid()) +} + +func (p *SSAOPass) ensureLive(dev *gpu.Device) error { + if p == nil || p.closed { + return fmt.Errorf("%w: ssao pass is not valid", ErrInvalidPostProcess) + } + if p.Valid() { + return nil + } + if !p.retained || !p.vb.Valid() || !p.aoRawRT.Valid() || !p.aoBlurRT.Valid() { + return fmt.Errorf("%w: ssao pass is not valid", ErrInvalidPostProcess) + } + shaders, err := getPostShaders() + if err != nil { + return err + } + return p.buildPipelines(dev, shaders) +} + +// Resize recreates the pass's offscreen AO targets for a new viewport size. +func (p *SSAOPass) Resize(dev *gpu.Device, width, height uint32) error { + if p == nil || p.closed { + return fmt.Errorf("%w: ssao pass is not valid", ErrInvalidPostProcess) + } + if err := postValidateSize(width, height); err != nil { + return err + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if p.width == width && p.height == height && p.aoRawRT.Valid() && p.aoBlurRT.Valid() { + return nil + } + p.width, p.height = width, height + return p.allocTargets(dev) +} + +// ComputeAO evaluates the SSAO hemisphere pass (and optional bilateral blur) from +// depthTex and returns the resulting AO texture for inspection or custom compositing. +func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec PostPassRecorder, depthTex *gpu.Texture) (*gpu.Texture, error) { + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if err := p.ensureLive(dev); err != nil { + return nil, err + } + if rec == nil { + return nil, fmt.Errorf("%w: nil render pass recorder", ErrInvalidPostProcess) + } + if depthTex == nil || !depthTex.Valid() { + return nil, fmt.Errorf("%w: invalid depth texture", ErrInvalidPostProcess) + } + + proj, invProj := p.cfg.resolveMatrices(p.width, p.height) + kernel := buildSSAOKernel(p.cfg.SampleCount) + + var uData [postSSAOUniformSize]byte + postPutMat4(uData[:], 0, proj) + postPutMat4(uData[:], 64, invProj) + postPutFloat32(uData[:], 128, p.cfg.Radius) + postPutFloat32(uData[:], 132, p.cfg.Bias) + postPutFloat32(uData[:], 136, p.cfg.Intensity) + postPutFloat32(uData[:], 140, p.cfg.Power) + postPutFloat32(uData[:], 144, 1.0/float32(p.width)) + postPutFloat32(uData[:], 148, 1.0/float32(p.height)) + postPutFloat32(uData[:], 152, float32(p.cfg.SampleCount)) + postPutFloat32(uData[:], 156, 0) + for i := range postMaxSSAOSamples { + base := 160 + i*16 + postPutFloat32(uData[:], base+0, kernel[i][0]) + postPutFloat32(uData[:], base+4, kernel[i][1]) + postPutFloat32(uData[:], base+8, kernel[i][2]) + postPutFloat32(uData[:], base+12, kernel[i][3]) + } + dev.WriteBuffer(p.ssaoBuf, 0, uData[:]) + + if p.cachedSSAODepth != depthTex || !p.cachedSSAOBG.Valid() { + bg, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".bg", + Layout: p.ssaoLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.ssaoBuf, Size: postSSAOUniformSize}, + {Binding: 1, Texture: depthTex}, + {Binding: 2, Sampler: p.nearestSamp}, + }, + }) + if err != nil { + return nil, err + } + _ = postCloseAll(p.cachedSSAOBG) + p.cachedSSAODepth = depthTex + p.cachedSSAOBG = bg + } + + drawPostFullscreen(rec, p.label+".ao", p.aoRawRT.Color, p.ssaoPipe, p.cachedSSAOBG, p.vb) + aoTex := p.aoRawRT.Color + + if p.cfg.BlurRadius > 0 && p.cfg.Intensity > 0 { + var bData [postSSAOBlurUniformSize]byte + postPutMat4(bData[:], 0, invProj) + postPutFloat32(bData[:], 64, 1.0/float32(p.width)) + postPutFloat32(bData[:], 68, 1.0/float32(p.height)) + postPutFloat32(bData[:], 72, float32(p.cfg.BlurRadius)) + postPutFloat32(bData[:], 76, p.cfg.DepthThreshold) + dev.WriteBuffer(p.blurBuf, 0, bData[:]) + + if p.cachedBlurDepth != depthTex || !p.cachedBlurBG.Valid() { + bg, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".blur.bg", + Layout: p.blurLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.blurBuf, Size: postSSAOBlurUniformSize}, + {Binding: 1, Texture: p.aoRawRT.Color}, + {Binding: 2, Texture: depthTex}, + {Binding: 3, Sampler: p.nearestSamp}, + }, + }) + if err != nil { + return nil, err + } + _ = postCloseAll(p.cachedBlurBG) + p.cachedBlurDepth = depthTex + p.cachedBlurBG = bg + } + drawPostFullscreen(rec, p.label+".blur", p.aoBlurRT.Color, p.blurPipe, p.cachedBlurBG, p.vb) + aoTex = p.aoBlurRT.Color + } + + p.lastAO = aoTex + return aoTex, nil +} + +// Apply computes SSAO from depthTex and multiplies it onto srcColor, writing to +// dstColor (nil writes to the swapchain using OutputFormat). +func (p *SSAOPass) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { + return p.applyWithOutput(dev, rec, srcColor, depthTex, dstColor, dstColor == nil) +} + +func (p *SSAOPass) applyWithOutput(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { + if srcColor == nil || !srcColor.Valid() { + return fmt.Errorf("%w: invalid source color texture", ErrInvalidPostProcess) + } + if dstColor != nil && !dstColor.Valid() { + return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) + } + aoTex, err := p.ComputeAO(dev, rec, depthTex) + if err != nil { + return err + } + if p.cachedCompSrc != srcColor || p.cachedCompAO != aoTex || !p.cachedCompBG.Valid() { + bg, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".comp.bg", + Layout: p.compLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Texture: srcColor}, + {Binding: 1, Texture: aoTex}, + {Binding: 2, Sampler: p.linearSamp}, + }, + }) + if err != nil { + return err + } + _ = postCloseAll(p.cachedCompBG) + p.cachedCompSrc = srcColor + p.cachedCompAO = aoTex + p.cachedCompBG = bg + } + pipe := p.compPipe + if useOutputFormat && p.compOutPipe != nil { + pipe = p.compOutPipe + } + drawPostFullscreen(rec, p.label+".composite", dstColor, pipe, p.cachedCompBG, p.vb) + return nil +} + +// Close releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once. +func (p *SSAOPass) Close() error { + if p == nil || p.closed { + return nil + } + p.closed = true + p.cachedSSAODepth = nil + p.cachedBlurDepth = nil + p.cachedCompSrc = nil + p.cachedCompAO = nil + p.lastAO = nil + return postCloseAll( + p.cachedSSAOBG, p.cachedBlurBG, p.cachedCompBG, + p.aoRawRT, p.aoBlurRT, + p.ssaoPipe, p.blurPipe, p.compPipe, p.compOutPipe, + p.ssaoLayout, p.blurLayout, p.compLayout, + p.ssaoBuf, p.blurBuf, + p.nearestSamp, p.linearSamp, p.vb, + ) +} + +// ============================================================================ +// Depth of Field +// ============================================================================ + +// DepthOfFieldConfig tunes depth-aware disc bokeh Depth of Field. +type DepthOfFieldConfig struct { + // FocusDistance is the view-space distance from the camera that renders sharpest (> 0). Default: 5.0. + FocusDistance float32 + // FocusRange is the half-width around FocusDistance over which the Circle of Confusion + // ramps from 0 (in focus) to 1 (maximum blur). Must be > 0. Default: 2.0. + FocusRange float32 + // MaxBlurRadius is the maximum bokeh disc radius in pixels at CoC = 1 (>= 0). + // 0 leaves the scene unchanged. Default: 6.0. + MaxBlurRadius float32 + // Near and Far are the camera clip planes used to linearize [0, 1] depth values (0 < Near < Far). + Near float32 + Far float32 + // Orthographic selects linear orthographic depth reconstruction instead of perspective. + Orthographic bool +} + +// DefaultDepthOfFieldConfig returns balanced defaults for 3D Depth of Field. +func DefaultDepthOfFieldConfig() DepthOfFieldConfig { + return DepthOfFieldConfig{ + FocusDistance: 5.0, + FocusRange: 2.0, + MaxBlurRadius: 6.0, + Near: 0.1, + Far: 100.0, + } +} + +// DepthOfFieldConfigFromCamera initializes a [DepthOfFieldConfig] with cam's clip +// planes and projection kind. +func DepthOfFieldConfigFromCamera(cam *scene3d.Camera, focusDistance, focusRange, maxBlurRadius float32) DepthOfFieldConfig { + cfg := DefaultDepthOfFieldConfig() + cfg.FocusDistance = focusDistance + cfg.FocusRange = focusRange + cfg.MaxBlurRadius = maxBlurRadius + if cam != nil { + if cam.Projection.Near > 0 { + cfg.Near = cam.Projection.Near + } + if cam.Projection.Far > cfg.Near { + cfg.Far = cam.Projection.Far + } + cfg.Orthographic = cam.Projection.Kind == scene3d.ProjectionOrthographic + } + return cfg +} + +// Validate checks that every field of c is finite and within its valid range. +// Every error wraps [ErrInvalidPostProcess]. +func (c DepthOfFieldConfig) Validate() error { + if !finite(c.FocusDistance) || c.FocusDistance <= 0 { + return fmt.Errorf("%w: dof FocusDistance %v must be finite and > 0", ErrInvalidPostProcess, c.FocusDistance) + } + if !finite(c.FocusRange) || c.FocusRange <= 0 { + return fmt.Errorf("%w: dof FocusRange %v must be finite and > 0", ErrInvalidPostProcess, c.FocusRange) + } + if !finite(c.MaxBlurRadius) || c.MaxBlurRadius < 0 { + return fmt.Errorf("%w: dof MaxBlurRadius %v must be finite and >= 0", ErrInvalidPostProcess, c.MaxBlurRadius) + } + if !finite(c.Near) || !finite(c.Far) || c.Near <= 0 || c.Far <= c.Near { + return fmt.Errorf("%w: dof requires 0 < Near < Far (got Near=%v, Far=%v)", ErrInvalidPostProcess, c.Near, c.Far) + } + return nil +} + +// buildDoFDiscTaps returns 18 deterministic 2-ring disc bokeh offsets: +// 6 taps on the inner ring (r = 0.45) and 12 taps on the outer ring (r = 0.95). +func buildDoFDiscTaps() [postDoFTapCount][4]float32 { + var taps [postDoFTapCount][4]float32 + idx := 0 + const innerR = 0.45 + for i := range 6 { + a := float64(i) * (2.0 * math.Pi / 6.0) + taps[idx] = [4]float32{ + float32(math.Cos(a) * innerR), + float32(math.Sin(a) * innerR), + innerR, + 0, + } + idx++ + } + const outerR = 0.95 + for i := range 12 { + a := (float64(i) + 0.5) * (2.0 * math.Pi / 12.0) + taps[idx] = [4]float32{ + float32(math.Cos(a) * outerR), + float32(math.Sin(a) * outerR), + outerR, + 0, + } + idx++ + } + return taps +} + +// DepthOfFieldPassOptions configures [NewDepthOfFieldPass]. +type DepthOfFieldPassOptions struct { + Label string + Width uint32 + Height uint32 + ColorFormat gpu.TextureFormat // intermediate color/CoC format; defaults to FormatRGBA16Float + OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm + Retained bool + Config DepthOfFieldConfig +} + +// DepthOfFieldPass computes per-pixel signed Circle of Confusion from depth and +// gathers a depth-aware disc bokeh blur that keeps in-focus silhouettes sharp. +type DepthOfFieldPass struct { + cx *core.Scope + label string + width uint32 + height uint32 + colorFormat gpu.TextureFormat + outputFormat gpu.TextureFormat + retained bool + cfg DepthOfFieldConfig + + vb *gpu.Buffer + linearSamp *gpu.Sampler + nearestSamp *gpu.Sampler + cocBuf *gpu.Buffer + bokehBuf *gpu.Buffer + + cocLayout *gpu.BindGroupLayout + bokehLayout *gpu.BindGroupLayout + + cocPipe *gpu.Pipeline + bokehPipe *gpu.Pipeline + bokehOutPipe *gpu.Pipeline + + cocRT *gpu.RenderTarget + + cachedCoCSrc *gpu.Texture + cachedCoCDepth *gpu.Texture + cachedCoCBG *gpu.BindGroup + cachedBokehSrc *gpu.Texture + cachedBokehBG *gpu.BindGroup + + closed bool +} + +// NewDepthOfFieldPass creates a scope-owned [DepthOfFieldPass] on dev. +func NewDepthOfFieldPass(cx *core.Scope, dev *gpu.Device, opts DepthOfFieldPassOptions) (*DepthOfFieldPass, error) { + if err := postValidateSize(opts.Width, opts.Height); err != nil { + return nil, err + } + if err := opts.Config.Validate(); err != nil { + return nil, err + } + colorFmt, err := postResolveColorFormat(opts.ColorFormat) + if err != nil { + return nil, err + } + outFmt, err := postResolveOutputFormat(dev, opts.OutputFormat) + if err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + shaders, err := getPostShaders() + if err != nil { + return nil, err + } + + label := opts.Label + if label == "" { + label = "render3d.dof" + } + + p := &DepthOfFieldPass{ + cx: cx, + label: label, + width: opts.Width, + height: opts.Height, + colorFormat: colorFmt, + outputFormat: outFmt, + retained: opts.Retained, + cfg: opts.Config, + } + + if p.vb, err = createPostFullscreenVB(cx, dev, opts.Retained); err != nil { + _ = p.Close() + return nil, err + } + if p.linearSamp, err = dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".linear", + MinFilter: gpu.FilterLinear, + MagFilter: gpu.FilterLinear, + MipmapFilter: gpu.FilterLinear, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + if p.nearestSamp, err = dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".nearest", + MinFilter: gpu.FilterNearest, + MagFilter: gpu.FilterNearest, + MipmapFilter: gpu.FilterNearest, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + if p.cocBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".coc.u", + Size: postDoFCoCUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + if p.bokehBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".bokeh.u", + Size: postDoFBokehUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: opts.Retained, + }); err != nil { + _ = p.Close() + return nil, err + } + + if err := p.buildPipelines(dev, shaders); err != nil { + _ = p.Close() + return nil, err + } + if err := p.allocTargets(dev); err != nil { + _ = p.Close() + return nil, err + } + return p, nil +} + +func (p *DepthOfFieldPass) buildPipelines(dev *gpu.Device, shaders *postShaderCache) error { + cocLayout, err := dev.CreateBindGroupLayoutDesc(p.cx, gpu.BindGroupLayoutDesc{ + Label: p.label + ".coc.layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + {Binding: 4, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + return err + } + bokehLayout, err := dev.CreateBindGroupLayoutDesc(p.cx, gpu.BindGroupLayoutDesc{ + Label: p.label + ".bokeh.layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + _ = cocLayout.Close() + return err + } + cocPipe, err := createPostPipeline(p.cx, dev, p.label+".coc.pipe", shaders.dofCoC, "fs_dof_coc", cocLayout, p.colorFormat) + if err != nil { + _ = postCloseAll(cocLayout, bokehLayout) + return err + } + bokehPipe, err := createPostPipeline(p.cx, dev, p.label+".bokeh.pipe", shaders.dofBokeh, "fs_dof_bokeh", bokehLayout, p.colorFormat) + if err != nil { + _ = postCloseAll(cocPipe, cocLayout, bokehLayout) + return err + } + var bokehOutPipe *gpu.Pipeline + if p.outputFormat != p.colorFormat { + bokehOutPipe, err = createPostPipeline(p.cx, dev, p.label+".bokeh.out", shaders.dofBokeh, "fs_dof_bokeh", bokehLayout, p.outputFormat) + if err != nil { + _ = postCloseAll(cocPipe, bokehPipe, cocLayout, bokehLayout) + return err + } + } + _ = postCloseAll(p.cachedCoCBG, p.cachedBokehBG, + p.cocPipe, p.bokehPipe, p.bokehOutPipe, + p.cocLayout, p.bokehLayout) + p.cocLayout = cocLayout + p.bokehLayout = bokehLayout + p.cocPipe = cocPipe + p.bokehPipe = bokehPipe + p.bokehOutPipe = bokehOutPipe + p.cachedCoCSrc = nil + p.cachedCoCDepth = nil + p.cachedCoCBG = nil + p.cachedBokehSrc = nil + p.cachedBokehBG = nil + return nil +} + +func (p *DepthOfFieldPass) allocTargets(dev *gpu.Device) error { + rt, err := dev.CreateRenderTarget(p.cx, gpu.RenderTargetDesc{ + Label: p.label + ".coc", + Width: p.width, + Height: p.height, + ColorFormat: p.colorFormat, + Retained: p.retained, + }) + if err != nil { + return err + } + _ = postCloseAll(p.cachedBokehBG, p.cocRT) + p.cocRT = rt + p.cachedBokehSrc = nil + p.cachedBokehBG = nil + return nil +} + +// Config returns the pass's current [DepthOfFieldConfig]. +func (p *DepthOfFieldPass) Config() DepthOfFieldConfig { + if p == nil { + return DepthOfFieldConfig{} + } + return p.cfg +} + +// SetConfig validates and updates the Depth of Field parameters. +func (p *DepthOfFieldPass) SetConfig(cfg DepthOfFieldConfig) error { + if p == nil || p.closed { + return fmt.Errorf("%w: dof pass is not valid", ErrInvalidPostProcess) + } + if err := cfg.Validate(); err != nil { + return err + } + p.cfg = cfg + return nil +} + +// Width returns the configured target width in pixels. +func (p *DepthOfFieldPass) Width() uint32 { + if p == nil { + return 0 + } + return p.width +} + +// Height returns the configured target height in pixels. +func (p *DepthOfFieldPass) Height() uint32 { + if p == nil { + return 0 + } + return p.height +} + +// Valid reports whether the pass is open and its GPU resources are live. +func (p *DepthOfFieldPass) Valid() bool { + return p != nil && !p.closed && + p.vb.Valid() && p.cocRT.Valid() && + p.cocPipe.Valid() && p.bokehPipe.Valid() && + (p.bokehOutPipe == nil || p.bokehOutPipe.Valid()) +} + +func (p *DepthOfFieldPass) ensureLive(dev *gpu.Device) error { + if p == nil || p.closed { + return fmt.Errorf("%w: dof pass is not valid", ErrInvalidPostProcess) + } + if p.Valid() { + return nil + } + if !p.retained || !p.vb.Valid() || !p.cocRT.Valid() { + return fmt.Errorf("%w: dof pass is not valid", ErrInvalidPostProcess) + } + shaders, err := getPostShaders() + if err != nil { + return err + } + return p.buildPipelines(dev, shaders) +} + +// Resize recreates the pass's offscreen CoC target for a new viewport size. +func (p *DepthOfFieldPass) Resize(dev *gpu.Device, width, height uint32) error { + if p == nil || p.closed { + return fmt.Errorf("%w: dof pass is not valid", ErrInvalidPostProcess) + } + if err := postValidateSize(width, height); err != nil { + return err + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if p.width == width && p.height == height && p.cocRT.Valid() { + return nil + } + p.width, p.height = width, height + return p.allocTargets(dev) +} + +// Apply runs the CoC prepass and depth-aware disc bokeh gather from srcColor and +// depthTex into dstColor (nil writes to the swapchain using OutputFormat). +func (p *DepthOfFieldPass) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { + return p.applyWithOutput(dev, rec, srcColor, depthTex, dstColor, dstColor == nil) +} + +func (p *DepthOfFieldPass) applyWithOutput(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if err := p.ensureLive(dev); err != nil { + return err + } + if rec == nil { + return fmt.Errorf("%w: nil render pass recorder", ErrInvalidPostProcess) + } + if srcColor == nil || !srcColor.Valid() { + return fmt.Errorf("%w: invalid source color texture", ErrInvalidPostProcess) + } + if depthTex == nil || !depthTex.Valid() { + return fmt.Errorf("%w: invalid depth texture", ErrInvalidPostProcess) + } + if dstColor != nil && !dstColor.Valid() { + return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) + } + + var cocData [postDoFCoCUniformSize]byte + postPutFloat32(cocData[:], 0, p.cfg.FocusDistance) + postPutFloat32(cocData[:], 4, p.cfg.FocusRange) + postPutFloat32(cocData[:], 8, p.cfg.Near) + postPutFloat32(cocData[:], 12, p.cfg.Far) + if p.cfg.Orthographic { + postPutFloat32(cocData[:], 16, 1) + } + dev.WriteBuffer(p.cocBuf, 0, cocData[:]) + + var bokehData [postDoFBokehUniformSize]byte + postPutFloat32(bokehData[:], 0, 1.0/float32(p.width)) + postPutFloat32(bokehData[:], 4, 1.0/float32(p.height)) + postPutFloat32(bokehData[:], 8, p.cfg.MaxBlurRadius) + postPutFloat32(bokehData[:], 12, 0) + taps := buildDoFDiscTaps() + for i := range postDoFTapCount { + base := 16 + i*16 + postPutFloat32(bokehData[:], base+0, taps[i][0]) + postPutFloat32(bokehData[:], base+4, taps[i][1]) + postPutFloat32(bokehData[:], base+8, taps[i][2]) + postPutFloat32(bokehData[:], base+12, taps[i][3]) + } + dev.WriteBuffer(p.bokehBuf, 0, bokehData[:]) + + if p.cachedCoCSrc != srcColor || p.cachedCoCDepth != depthTex || !p.cachedCoCBG.Valid() { + bg, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".coc.bg", + Layout: p.cocLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.cocBuf, Size: postDoFCoCUniformSize}, + {Binding: 1, Texture: srcColor}, + {Binding: 2, Texture: depthTex}, + {Binding: 3, Sampler: p.linearSamp}, + {Binding: 4, Sampler: p.nearestSamp}, + }, + }) + if err != nil { + return err + } + _ = postCloseAll(p.cachedCoCBG) + p.cachedCoCSrc = srcColor + p.cachedCoCDepth = depthTex + p.cachedCoCBG = bg + } + if p.cachedBokehSrc != srcColor || !p.cachedBokehBG.Valid() { + bg, err := dev.CreateBindGroupDesc(p.cx, gpu.BindGroupDesc{ + Label: p.label + ".bokeh.bg", + Layout: p.bokehLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: p.bokehBuf, Size: postDoFBokehUniformSize}, + {Binding: 1, Texture: srcColor}, + {Binding: 2, Texture: p.cocRT.Color}, + {Binding: 3, Sampler: p.linearSamp}, + }, + }) + if err != nil { + return err + } + _ = postCloseAll(p.cachedBokehBG) + p.cachedBokehSrc = srcColor + p.cachedBokehBG = bg + } + + // 1. CoC prepass -> cocRT. + drawPostFullscreen(rec, p.label+".coc", p.cocRT.Color, p.cocPipe, p.cachedCoCBG, p.vb) + + // 2. Depth-aware disc bokeh gather -> dstColor (or swapchain). + pipe := p.bokehPipe + if useOutputFormat && p.bokehOutPipe != nil { + pipe = p.bokehOutPipe + } + drawPostFullscreen(rec, p.label+".bokeh", dstColor, pipe, p.cachedBokehBG, p.vb) + return nil +} + +// Close releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once. +func (p *DepthOfFieldPass) Close() error { + if p == nil || p.closed { + return nil + } + p.closed = true + p.cachedCoCSrc = nil + p.cachedCoCDepth = nil + p.cachedBokehSrc = nil + return postCloseAll( + p.cachedCoCBG, p.cachedBokehBG, + p.cocRT, + p.cocPipe, p.bokehPipe, p.bokehOutPipe, + p.cocLayout, p.bokehLayout, + p.cocBuf, p.bokehBuf, + p.linearSamp, p.nearestSamp, p.vb, + ) +} + +// ============================================================================ +// Composable PostStack3D +// ============================================================================ + +// PostStack3DOptions configures [NewPostStack3D]. +type PostStack3DOptions struct { + Label string + // Width and Height of the offscreen 3D scene and post-processing targets (must be > 0). + Width uint32 + Height uint32 + // ColorFormat is the scene and intermediate ping-pong color format. + // Defaults to [gpu.FormatRGBA16Float] when zero, preserving HDR highlights for Bloom. + ColorFormat gpu.TextureFormat + // DepthFormat is the scene render target's depth format. Defaults to [gpu.FormatDepth32Float] when zero. + DepthFormat gpu.TextureFormat + // OutputFormat is the format of the final destination (swapchain or dstColor). + // Defaults to dev.SurfaceFormat() (or [gpu.FormatRGBA8Unorm]) when zero. + OutputFormat gpu.TextureFormat + // Retained opts offscreen targets, buffers, and samplers into automatic recreation after device loss. + Retained bool + + // EnableSSAO enables the SSAO pass (stage 1). When false and SSAO is zero, DefaultSSAOConfig is prepared for later enabling. + EnableSSAO bool + SSAO SSAOConfig + // EnableDoF enables the Depth of Field pass (stage 2). + EnableDoF bool + DoF DepthOfFieldConfig + // EnableBloom enables the Bloom pass (stage 3). + EnableBloom bool + Bloom BloomConfig +} + +// PostStack3D composes SSAO, Depth of Field, and Bloom over an offscreen 3D +// color+depth render target, routing enabled passes cleanly through ping-pong +// offscreen targets and writing the final result to the swapchain or a chosen +// destination texture. +// +// Execution order is fixed to SSAO -> Depth of Field -> Bloom so ambient +// occlusion darkens crevices before bokeh blurring and highlights bloom after +// optical blur. All passes use portable WGSL compatible with both full and +// compute-free (WebGL 2 / OpenGL ES 3.0) NSGo GPU profiles. +type PostStack3D struct { + cx *core.Scope + label string + width uint32 + height uint32 + colorFormat gpu.TextureFormat + depthFormat gpu.TextureFormat + outputFormat gpu.TextureFormat + retained bool + + enableSSAO bool + enableDoF bool + enableBloom bool + + ssao *SSAOPass + dof *DepthOfFieldPass + bloom *BloomPass + + sceneRT *gpu.RenderTarget + pingRT *gpu.RenderTarget + pongRT *gpu.RenderTarget + + vb *gpu.Buffer + linearSamp *gpu.Sampler + blitLayout *gpu.BindGroupLayout + blitPipe *gpu.Pipeline + blitOutPipe *gpu.Pipeline + + cachedBlitSrc *gpu.Texture + cachedBlitBG *gpu.BindGroup + + closed bool +} + +// NewPostStack3D creates a scope-owned composable 3D post-processing stack on dev. +func NewPostStack3D(cx *core.Scope, dev *gpu.Device, opts PostStack3DOptions) (*PostStack3D, error) { + if err := postValidateSize(opts.Width, opts.Height); err != nil { + return nil, err + } + colorFmt, err := postResolveColorFormat(opts.ColorFormat) + if err != nil { + return nil, err + } + depthFmt, err := postResolveDepthFormat(opts.DepthFormat) + if err != nil { + return nil, err + } + outFmt, err := postResolveOutputFormat(dev, opts.OutputFormat) + if err != nil { + return nil, err + } + + ssaoCfg := opts.SSAO + if !opts.EnableSSAO && ssaoCfg == (SSAOConfig{}) { + ssaoCfg = DefaultSSAOConfig() + } + if err := ssaoCfg.Validate(); err != nil { + return nil, err + } + dofCfg := opts.DoF + if !opts.EnableDoF && dofCfg == (DepthOfFieldConfig{}) { + dofCfg = DefaultDepthOfFieldConfig() + } + if err := dofCfg.Validate(); err != nil { + return nil, err + } + bloomCfg := opts.Bloom + if !opts.EnableBloom && bloomCfg == (BloomConfig{}) { + bloomCfg = DefaultBloomConfig() + } + if err := bloomCfg.Validate(); err != nil { + return nil, err + } + + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + shaders, err := getPostShaders() + if err != nil { + return nil, err + } + + label := opts.Label + if label == "" { + label = "render3d.post" + } + + s := &PostStack3D{ + cx: cx, + label: label, + width: opts.Width, + height: opts.Height, + colorFormat: colorFmt, + depthFormat: depthFmt, + outputFormat: outFmt, + retained: opts.Retained, + enableSSAO: opts.EnableSSAO, + enableDoF: opts.EnableDoF, + enableBloom: opts.EnableBloom, + } + + if s.ssao, err = NewSSAOPass(cx, dev, SSAOPassOptions{ + Label: label + ".ssao", + Width: opts.Width, + Height: opts.Height, + ColorFormat: colorFmt, + OutputFormat: outFmt, + Retained: opts.Retained, + Config: ssaoCfg, + }); err != nil { + _ = s.Close() + return nil, err + } + if s.dof, err = NewDepthOfFieldPass(cx, dev, DepthOfFieldPassOptions{ + Label: label + ".dof", + Width: opts.Width, + Height: opts.Height, + ColorFormat: colorFmt, + OutputFormat: outFmt, + Retained: opts.Retained, + Config: dofCfg, + }); err != nil { + _ = s.Close() + return nil, err + } + if s.bloom, err = NewBloomPass(cx, dev, BloomPassOptions{ + Label: label + ".bloom", + Width: opts.Width, + Height: opts.Height, + ColorFormat: colorFmt, + OutputFormat: outFmt, + Retained: opts.Retained, + Config: bloomCfg, + }); err != nil { + _ = s.Close() + return nil, err + } + + if s.vb, err = createPostFullscreenVB(cx, dev, opts.Retained); err != nil { + _ = s.Close() + return nil, err + } + if s.linearSamp, err = dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".blit.samp", + MinFilter: gpu.FilterLinear, + MagFilter: gpu.FilterLinear, + MipmapFilter: gpu.FilterLinear, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Retained: opts.Retained, + }); err != nil { + _ = s.Close() + return nil, err + } + if err := s.buildPipelines(dev, shaders); err != nil { + _ = s.Close() + return nil, err + } + if err := s.allocTargets(dev); err != nil { + _ = s.Close() + return nil, err + } + return s, nil +} + +func (s *PostStack3D) buildPipelines(dev *gpu.Device, shaders *postShaderCache) error { + blitLayout, err := dev.CreateBindGroupLayoutDesc(s.cx, gpu.BindGroupLayoutDesc{ + Label: s.label + ".blit.layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }, + }) + if err != nil { + return err + } + blitPipe, err := createPostPipeline(s.cx, dev, s.label+".blit", shaders.blit, "fs_blit", blitLayout, s.colorFormat) + if err != nil { + _ = blitLayout.Close() + return err + } + var blitOutPipe *gpu.Pipeline + if s.outputFormat != s.colorFormat { + blitOutPipe, err = createPostPipeline(s.cx, dev, s.label+".blit.out", shaders.blit, "fs_blit", blitLayout, s.outputFormat) + if err != nil { + _ = postCloseAll(blitPipe, blitLayout) + return err + } + } + _ = postCloseAll(s.cachedBlitBG, s.blitPipe, s.blitOutPipe, s.blitLayout) + s.blitLayout = blitLayout + s.blitPipe = blitPipe + s.blitOutPipe = blitOutPipe + s.cachedBlitSrc = nil + s.cachedBlitBG = nil + return nil +} + +func (s *PostStack3D) allocTargets(dev *gpu.Device) error { + sceneRT, err := dev.CreateRenderTarget(s.cx, gpu.RenderTargetDesc{ + Label: s.label + ".scene", + Width: s.width, + Height: s.height, + ColorFormat: s.colorFormat, + DepthFormat: s.depthFormat, + Retained: s.retained, + }) + if err != nil { + return err + } + pingRT, err := dev.CreateRenderTarget(s.cx, gpu.RenderTargetDesc{ + Label: s.label + ".ping", + Width: s.width, + Height: s.height, + ColorFormat: s.colorFormat, + Retained: s.retained, + }) + if err != nil { + _ = sceneRT.Close() + return err + } + pongRT, err := dev.CreateRenderTarget(s.cx, gpu.RenderTargetDesc{ + Label: s.label + ".pong", + Width: s.width, + Height: s.height, + ColorFormat: s.colorFormat, + Retained: s.retained, + }) + if err != nil { + _ = sceneRT.Close() + _ = pingRT.Close() + return err + } + _ = postCloseAll(s.cachedBlitBG, s.sceneRT, s.pingRT, s.pongRT) + s.sceneRT = sceneRT + s.pingRT = pingRT + s.pongRT = pongRT + s.cachedBlitSrc = nil + s.cachedBlitBG = nil + return nil +} + +// SceneTarget returns the stack-managed offscreen 3D color+depth [gpu.RenderTarget]. +func (s *PostStack3D) SceneTarget() *gpu.RenderTarget { + if s == nil || s.closed { + return nil + } + return s.sceneRT +} + +// BeginScenePass begins a render pass targeting [PostStack3D.SceneTarget], clearing +// color to clearColor and depth to 1.0 and storing both attachments for post-processing. +func (s *PostStack3D) BeginScenePass(rec PostPassRecorder, clearColor core.Color) *gpu.RenderPass { + if s == nil || s.closed || rec == nil || !s.sceneRT.Valid() { + return nil + } + return rec.BeginRenderPass(gpu.RenderPassDesc{ + Label: s.label + ".scene", + ColorAttachments: []gpu.ColorAttachment{{ + Texture: s.sceneRT.Color, + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: clearColor, + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: s.sceneRT.Depth, + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) +} + +// SSAO returns the underlying [SSAOPass]. +func (s *PostStack3D) SSAO() *SSAOPass { + if s == nil { + return nil + } + return s.ssao +} + +// DepthOfField returns the underlying [DepthOfFieldPass]. +func (s *PostStack3D) DepthOfField() *DepthOfFieldPass { + if s == nil { + return nil + } + return s.dof +} + +// Bloom returns the underlying [BloomPass]. +func (s *PostStack3D) Bloom() *BloomPass { + if s == nil { + return nil + } + return s.bloom +} + +// SetSSAO enables or disables SSAO and updates its configuration. +func (s *PostStack3D) SetSSAO(enabled bool, cfg SSAOConfig) error { + if s == nil || s.closed { + return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) + } + if err := s.ssao.SetConfig(cfg); err != nil { + return err + } + s.enableSSAO = enabled + return nil +} + +// SetDepthOfField enables or disables Depth of Field and updates its configuration. +func (s *PostStack3D) SetDepthOfField(enabled bool, cfg DepthOfFieldConfig) error { + if s == nil || s.closed { + return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) + } + if err := s.dof.SetConfig(cfg); err != nil { + return err + } + s.enableDoF = enabled + return nil +} + +// SetBloom enables or disables Bloom and updates its configuration. +func (s *PostStack3D) SetBloom(enabled bool, cfg BloomConfig) error { + if s == nil || s.closed { + return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) + } + if err := s.bloom.SetConfig(cfg); err != nil { + return err + } + s.enableBloom = enabled + return nil +} + +// Width returns the stack's offscreen target width in pixels. +func (s *PostStack3D) Width() uint32 { + if s == nil { + return 0 + } + return s.width +} + +// Height returns the stack's offscreen target height in pixels. +func (s *PostStack3D) Height() uint32 { + if s == nil { + return 0 + } + return s.height +} + +// ColorFormat returns the offscreen scene and intermediate color target format. +func (s *PostStack3D) ColorFormat() gpu.TextureFormat { + if s == nil { + return gpu.FormatUndefined + } + return s.colorFormat +} + +// DepthFormat returns the offscreen scene depth target format. +func (s *PostStack3D) DepthFormat() gpu.TextureFormat { + if s == nil { + return gpu.FormatUndefined + } + return s.depthFormat +} + +// OutputFormat returns the final destination format (swapchain or dstColor). +func (s *PostStack3D) OutputFormat() gpu.TextureFormat { + if s == nil { + return gpu.FormatUndefined + } + return s.outputFormat +} + +// Valid reports whether the stack and every internal pass and target are live. +func (s *PostStack3D) Valid() bool { + return s != nil && !s.closed && + s.sceneRT.Valid() && s.pingRT.Valid() && s.pongRT.Valid() && + s.vb.Valid() && s.blitPipe.Valid() && (s.blitOutPipe == nil || s.blitOutPipe.Valid()) && + s.ssao.Valid() && s.dof.Valid() && s.bloom.Valid() +} + +func (s *PostStack3D) ensureLive(dev *gpu.Device) error { + if s == nil || s.closed { + return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) + } + if s.Valid() { + return nil + } + if !s.retained || !s.sceneRT.Valid() || !s.pingRT.Valid() || !s.pongRT.Valid() || !s.vb.Valid() { + return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) + } + shaders, err := getPostShaders() + if err != nil { + return err + } + if !s.blitPipe.Valid() || (s.blitOutPipe != nil && !s.blitOutPipe.Valid()) { + if err := s.buildPipelines(dev, shaders); err != nil { + return err + } + } + if err := s.ssao.ensureLive(dev); err != nil { + return err + } + if err := s.dof.ensureLive(dev); err != nil { + return err + } + return s.bloom.ensureLive(dev) +} + +// Resize recreates the stack's scene, ping-pong, and per-pass offscreen targets. +func (s *PostStack3D) Resize(dev *gpu.Device, width, height uint32) error { + if s == nil || s.closed { + return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) + } + if err := postValidateSize(width, height); err != nil { + return err + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if s.width == width && s.height == height && s.Valid() { + return nil + } + s.width, s.height = width, height + if err := s.allocTargets(dev); err != nil { + return err + } + if err := s.ssao.Resize(dev, width, height); err != nil { + return err + } + if err := s.dof.Resize(dev, width, height); err != nil { + return err + } + if err := s.bloom.Resize(dev, width, height); err != nil { + return err + } + return nil +} + +// ApplyScene executes all enabled passes on [PostStack3D.SceneTarget]'s color +// and depth attachments, writing the result into dstColor (nil targets the swapchain). +func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec PostPassRecorder, dstColor *gpu.Texture) error { + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if err := s.ensureLive(dev); err != nil { + return err + } + return s.Apply(dev, rec, s.sceneRT.Color, s.sceneRT.Depth, dstColor) +} + +// Apply executes all enabled passes in order (SSAO -> Depth of Field -> Bloom) +// on caller-provided srcColor and depthTex textures, writing the final result +// into dstColor (nil writes to the swapchain using OutputFormat). If depthTex +// is nil, depth-dependent passes (SSAO and Depth of Field) are skipped; if no +// pass runs, srcColor is blitted cleanly to dstColor. +func (s *PostStack3D) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if err := s.ensureLive(dev); err != nil { + return err + } + if rec == nil { + return fmt.Errorf("%w: nil render pass recorder", ErrInvalidPostProcess) + } + if srcColor == nil || !srcColor.Valid() { + return fmt.Errorf("%w: invalid source color texture", ErrInvalidPostProcess) + } + if depthTex != nil && !depthTex.Valid() { + return fmt.Errorf("%w: invalid depth texture", ErrInvalidPostProcess) + } + if dstColor != nil && !dstColor.Valid() { + return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) + } + + type stage uint8 + const ( + stageSSAO stage = iota + 1 + stageDoF + stageBloom + ) + var active [3]stage + n := 0 + if s.enableSSAO && depthTex != nil { + active[n] = stageSSAO + n++ + } + if s.enableDoF && depthTex != nil { + active[n] = stageDoF + n++ + } + if s.enableBloom { + active[n] = stageBloom + n++ + } + + useOutputFormat := dstColor == nil + + if n == 0 { + if s.cachedBlitSrc != srcColor || !s.cachedBlitBG.Valid() { + bg, err := dev.CreateBindGroupDesc(s.cx, gpu.BindGroupDesc{ + Label: s.label + ".blit.bg", + Layout: s.blitLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Texture: srcColor}, + {Binding: 1, Sampler: s.linearSamp}, + }, + }) + if err != nil { + return err + } + _ = postCloseAll(s.cachedBlitBG) + s.cachedBlitSrc = srcColor + s.cachedBlitBG = bg + } + pipe := s.blitPipe + if useOutputFormat && s.blitOutPipe != nil { + pipe = s.blitOutPipe + } + drawPostFullscreen(rec, s.label+".blit", dstColor, pipe, s.cachedBlitBG, s.vb) + return nil + } + + cur := srcColor + pingNext := true + for i := range n { + last := i == n-1 + var target *gpu.Texture + targetUsesOutput := false + if last { + target = dstColor + targetUsesOutput = useOutputFormat + } else { + if pingNext { + target = s.pingRT.Color + } else { + target = s.pongRT.Color + } + pingNext = !pingNext + } + + var err error + switch active[i] { + case stageSSAO: + err = s.ssao.applyWithOutput(dev, rec, cur, depthTex, target, targetUsesOutput) + case stageDoF: + err = s.dof.applyWithOutput(dev, rec, cur, depthTex, target, targetUsesOutput) + case stageBloom: + err = s.bloom.applyWithOutput(dev, rec, cur, target, targetUsesOutput) + } + if err != nil { + return err + } + cur = target + } + return nil +} + +// Close releases all GPU resources owned by s and its passes. It is safe to call on a nil receiver or more than once. +func (s *PostStack3D) Close() error { + if s == nil || s.closed { + return nil + } + s.closed = true + s.cachedBlitSrc = nil + return postCloseAll( + s.cachedBlitBG, + s.sceneRT, s.pingRT, s.pongRT, + s.ssao, s.dof, s.bloom, + s.blitPipe, s.blitOutPipe, s.blitLayout, + s.linearSamp, s.vb, + ) +} diff --git a/packages/game/render3d/post3d_test.go b/packages/game/render3d/post3d_test.go new file mode 100644 index 00000000..0f6103ae --- /dev/null +++ b/packages/game/render3d/post3d_test.go @@ -0,0 +1,1040 @@ +package render3d_test + +import ( + "encoding/binary" + "errors" + "image" + "math" + "testing" + "time" + + "github.com/nsgo-dev/game/packages/game/gametest" + "github.com/nsgo-dev/game/packages/game/math3d" + "github.com/nsgo-dev/game/packages/game/render3d" + "github.com/nsgo-dev/game/packages/game/scene3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +const ( + post3dWidth = 128 + post3dHeight = 96 +) + +// post3dSceneWGSL renders unlit/HDR vertex-colored 3D geometry (rgb may exceed 1.0 for HDR emissives). +const post3dSceneWGSL = render3d.CameraWGSL + ` +struct Post3DVertexIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) color: vec4, +} + +struct Post3DVertexOut { + @builtin(position) clip: vec4, + @location(0) normal: vec3, + @location(1) color: vec4, +} + +@vertex +fn vs_main(in: Post3DVertexIn) -> Post3DVertexOut { + var out: Post3DVertexOut; + out.clip = camera.view_proj * vec4(in.pos, 1.0); + out.normal = in.normal; + out.color = in.color; + return out; +} + +@fragment +fn fs_main(in: Post3DVertexOut) -> @location(0) vec4 { + // color.a encodes shading mode: 1.0 = unlit/emissive (preserves HDR > 1.0), 0.5 = subtle directional shade. + if (in.color.a > 0.75) { + return vec4(in.color.rgb, 1.0); + } + let l = normalize(vec3(0.35, 0.85, 0.4)); + let k = 0.65 + 0.35 * max(dot(normalize(in.normal), l), 0.0); + return vec4(in.color.rgb * k, 1.0); +} +` + +func post3dAppendVert(dst []float32, p, n math3d.Vec3, col [3]float32, mode float32) []float32 { + return append(dst, p.X, p.Y, p.Z, n.X, n.Y, n.Z, col[0], col[1], col[2], mode) +} + +func post3dAppendQuad(dst []float32, a, b, c, d, n math3d.Vec3, col [3]float32, mode float32) []float32 { + for _, p := range [...]math3d.Vec3{a, b, c, a, c, d} { + dst = post3dAppendVert(dst, p, n, col, mode) + } + return dst +} + +func post3dAppendBox(dst []float32, center, half math3d.Vec3, col [3]float32, mode float32) []float32 { + type face struct { + n, u, v math3d.Vec3 + hn, hu, hv float32 + } + faces := [...]face{ + {math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}, math3d.Vec3{Y: 1}, half.X, half.Z, half.Y}, + {math3d.Vec3{X: -1}, math3d.Vec3{Z: 1}, math3d.Vec3{Y: 1}, half.X, half.Z, half.Y}, + {math3d.Vec3{Y: 1}, math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}, half.Y, half.X, half.Z}, + {math3d.Vec3{Y: -1}, math3d.Vec3{X: 1}, math3d.Vec3{Z: 1}, half.Y, half.X, half.Z}, + {math3d.Vec3{Z: 1}, math3d.Vec3{X: 1}, math3d.Vec3{Y: 1}, half.Z, half.X, half.Y}, + {math3d.Vec3{Z: -1}, math3d.Vec3{X: -1}, math3d.Vec3{Y: 1}, half.Z, half.X, half.Y}, + } + for _, f := range faces { + c := center.Add(f.n.Scale(f.hn)) + u, v := f.u.Scale(f.hu), f.v.Scale(f.hv) + dst = post3dAppendQuad(dst, + c.Sub(u).Sub(v), c.Add(u).Sub(v), c.Add(u).Add(v), c.Sub(u).Add(v), + f.n, col, mode) + } + return dst +} + +// post3dAppendCheckerPanel appends a front-facing (+Z) grid of alternating high-contrast tiles, +// ideal for measuring spatial sharpness vs Depth of Field blur. +func post3dAppendCheckerPanel(dst []float32, center math3d.Vec3, width, height float32, cols, rows int, colA, colB [3]float32) []float32 { + n := math3d.Vec3{Z: 1} + dx := width / float32(cols) + dy := height / float32(rows) + x0 := center.X - width*0.5 + y0 := center.Y - height*0.5 + for r := range rows { + for c := range cols { + col := colA + if (r+c)%2 != 0 { + col = colB + } + xa := x0 + float32(c)*dx + xb := xa + dx + ya := y0 + float32(r)*dy + yb := ya + dy + dst = post3dAppendQuad(dst, + math3d.Vec3{X: xa, Y: ya, Z: center.Z}, + math3d.Vec3{X: xb, Y: ya, Z: center.Z}, + math3d.Vec3{X: xb, Y: yb, Z: center.Z}, + math3d.Vec3{X: xa, Y: yb, Z: center.Z}, + n, col, 1.0) + } + } + return dst +} + +func post3dPackFloats(fs []float32) []byte { + out := make([]byte, len(fs)*4) + for i, f := range fs { + binary.LittleEndian.PutUint32(out[i*4:], math.Float32bits(f)) + } + return out +} + +type post3dScenePipeline struct { + cam *render3d.CameraBuffer + pipe *gpu.Pipeline +} + +func newPost3dScenePipeline(t *testing.T, cx *core.Scope, dev *gpu.Device, colorFmt, depthFmt gpu.TextureFormat) *post3dScenePipeline { + t.Helper() + cam, err := render3d.NewCameraBuffer(cx, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + mod, err := gpu.CompileWGSL(post3dSceneWGSL) + if err != nil { + t.Fatalf("CompileWGSL: %v", err) + } + pipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ + Label: "post3d.test.scene", + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, + Layouts: []*gpu.BindGroupLayout{render3d.CameraGroup: cam.Layout()}, + VertexBuffers: []gpu.VertexBufferLayout{{ + Stride: 10 * 4, + Attributes: []gpu.VertexAttribute{ + {Location: 0, Offset: 0, Format: gpu.VertexFloat32x3}, + {Location: 1, Offset: 3 * 4, Format: gpu.VertexFloat32x3}, + {Location: 2, Offset: 6 * 4, Format: gpu.VertexFloat32x4}, + }, + }}, + Primitive: gpu.PrimitiveState{Topology: gpu.TopologyTriangleList, CullMode: gpu.CullNone}, + DepthStencil: &gpu.DepthStencilState{ + Format: depthFmt, + DepthWrite: true, + DepthCompare: gpu.CompareLess, + }, + Targets: []gpu.ColorTargetState{{Format: colorFmt, WriteMask: gpu.ColorWriteAll}}, + }) + if err != nil { + t.Fatalf("CreatePipeline scene: %v", err) + } + return &post3dScenePipeline{cam: cam, pipe: pipe} +} + +func (sp *post3dScenePipeline) draw(pass *gpu.RenderPass, vb *gpu.Buffer, vertCount uint32) { + pass.SetPipeline(sp.pipe) + pass.SetBindGroup(render3d.CameraGroup, sp.cam.BindGroup()) + pass.SetVertexBuffer(0, vb, 0) + pass.Draw(vertCount, 0) +} + +func post3dAssertGolden(t *testing.T, name string, got *image.RGBA) { + t.Helper() + path := gametest.GoldenPath("", name) + if gametest.ShouldUpdateGolden() { + if err := gametest.WritePNG(path, got); err != nil { + t.Fatal(err) + } + return + } + want, err := gametest.ReadPNG(path) + if err != nil { + t.Fatalf("read reference %s: %v (UPDATE_GOLDEN=1 writes it)", path, err) + } + if !want.Bounds().Eq(got.Bounds()) { + t.Fatalf("%s: size %v, reference %v", name, got.Bounds(), want.Bounds()) + } + const channelTolerance = 3 + far := 0 + b := got.Bounds() + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + g := got.RGBAAt(x, y) + wr, wg, wb, wa := want.At(x, y).RGBA() + w := [4]int{int(wr >> 8), int(wg >> 8), int(wb >> 8), int(wa >> 8)} + for i, c := range [4]int{int(g.R), int(g.G), int(g.B), int(g.A)} { + if d := c - w[i]; d > channelTolerance || d < -channelTolerance { + far++ + break + } + } + } + } + if limit := b.Dx() * b.Dy() / 200; far > limit { + dir := t.TempDir() + diff, _ := gametest.DiffImage(got, want) + _ = gametest.WritePNG(dir+"/"+name+".got.png", got) + _ = gametest.WritePNG(dir+"/"+name+".diff.png", diff) + t.Fatalf("%s: %d pixels differ from reference (limit %d); got and diff written to %s", name, far, limit, dir) + } +} + +func post3dLuma(img *image.RGBA, x, y int) float64 { + c := img.RGBAAt(x, y) + return (0.2126*float64(c.R) + 0.7152*float64(c.G) + 0.0722*float64(c.B)) / 255.0 +} + +func post3dRegionLumaMean(img *image.RGBA, x0, y0, x1, y1 int) float64 { + var sum float64 + n := 0 + for y := y0; y < y1; y++ { + for x := x0; x < x1; x++ { + sum += post3dLuma(img, x, y) + n++ + } + } + if n == 0 { + return 0 + } + return sum / float64(n) +} + +// post3dRegionContrast measures mean horizontal + vertical adjacent-pixel luminance gradient +// inside [x0, x1) x [y0, y1), which drops cleanly when a checkerboard blurs. +func post3dRegionContrast(img *image.RGBA, x0, y0, x1, y1 int) float64 { + var sum float64 + n := 0 + for y := y0; y < y1-1; y++ { + for x := x0; x < x1-1; x++ { + c := post3dLuma(img, x, y) + r := post3dLuma(img, x+1, y) + d := post3dLuma(img, x, y+1) + sum += math.Abs(c-r) + math.Abs(c-d) + n++ + } + } + if n == 0 { + return 0 + } + return sum / float64(n) +} + +func post3dMaxChannelDiff(a, b *image.RGBA) int { + maxD := 0 + bounds := a.Bounds() + for y := bounds.Min.Y; y < bounds.Max.Y; y++ { + for x := bounds.Min.X; x < bounds.Max.X; x++ { + ca := a.RGBAAt(x, y) + cb := b.RGBAAt(x, y) + for _, d := range [4]int{ + int(ca.R) - int(cb.R), + int(ca.G) - int(cb.G), + int(ca.B) - int(cb.B), + int(ca.A) - int(cb.A), + } { + if d < 0 { + d = -d + } + if d > maxD { + maxD = d + } + } + } + } + return maxD +} + +func TestPost3DBloomMatchesReference(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dWidth, post3dHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + + sceneRT, err := dev.CreateRenderTarget(nil, gpu.RenderTargetDesc{ + Label: "bloom.scene", + Width: post3dWidth, + Height: post3dHeight, + ColorFormat: gpu.FormatRGBA16Float, + DepthFormat: gpu.FormatDepth32Float, + }) + if err != nil { + t.Fatalf("CreateRenderTarget: %v", err) + } + defer func() { _ = sceneRT.Close() }() + + sp := newPost3dScenePipeline(t, nil, dev, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + defer func() { _ = sp.cam.Close() }() + + // Scene: one bright HDR emissive box on the left, one muted box on the right, against a dark background. + var verts []float32 + verts = post3dAppendBox(verts, math3d.Vec3{X: -1.1, Y: 0.0, Z: 0.0}, math3d.Vec3{X: 0.45, Y: 0.45, Z: 0.45}, [3]float32{2.4, 1.7, 0.5}, 1.0) + verts = post3dAppendBox(verts, math3d.Vec3{X: 1.2, Y: 0.0, Z: 0.0}, math3d.Vec3{X: 0.45, Y: 0.45, Z: 0.45}, [3]float32{0.2, 0.3, 0.45}, 1.0) + vb, err := dev.CreateBuffer(nil, gpu.BufferDesc{Label: "bloom.verts", Usage: gpu.UsageVertex, Data: post3dPackFloats(verts)}) + if err != nil { + t.Fatalf("CreateBuffer: %v", err) + } + defer func() { _ = vb.Close() }() + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Z: 5.0}, math3d.DegToRad(45), float32(post3dWidth)/float32(post3dHeight), 0.1, 50) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + + bloom, err := render3d.NewBloomPass(nil, dev, render3d.BloomPassOptions{ + Width: post3dWidth, + Height: post3dHeight, + ColorFormat: gpu.FormatRGBA16Float, + OutputFormat: gpu.FormatRGBA8Unorm, + Config: render3d.BloomConfig{ + Threshold: 0.85, + SoftKnee: 0.35, + Intensity: 0.9, + Radius: 1.6, + BlurPasses: 2, + HalfRes: true, + }, + }) + if err != nil { + t.Fatalf("NewBloomPass: %v", err) + } + defer func() { _ = bloom.Close() }() + + renderFrame := func(cfg render3d.BloomConfig) *image.RGBA { + if err := bloom.SetConfig(cfg); err != nil { + t.Fatalf("SetConfig: %v", err) + } + sp.cam.WriteCamera(cam) + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{ + Texture: sceneRT.Color, + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: core.RGB(0x06080d), + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: sceneRT.Depth, + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) + sp.draw(pass, vb, uint32(len(verts)/10)) + pass.End() + if err := bloom.Apply(dev, enc, sceneRT.Color, nil); err != nil { + t.Fatalf("BloomPass.Apply: %v", err) + } + dev.Submit(enc.Finish()) + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + return sr.Image() + } + + bloomImg := renderFrame(bloom.Config()) + post3dAssertGolden(t, "post3d_bloom", bloomImg) + + noIntensity := bloom.Config() + noIntensity.Intensity = 0 + rawImg := renderFrame(noIntensity) + + highThresh := bloom.Config() + highThresh.Threshold = 5.0 + highThresh.SoftKnee = 0 + highThreshImg := renderFrame(highThresh) + + // High threshold above HDR brightness leaves scene identical to Intensity=0. + if diff := post3dMaxChannelDiff(rawImg, highThreshImg); diff > 1 { + t.Errorf("high threshold diff vs zero intensity = %d, want <= 1", diff) + } + + // Count halo pixels around the bright left box that were dark in rawImg and brightened in bloomImg. + haloPixels := 0 + mutedHaloPixels := 0 + for y := 0; y < post3dHeight; y++ { + for x := 0; x < post3dWidth; x++ { + rL := post3dLuma(rawImg, x, y) + bL := post3dLuma(bloomImg, x, y) + if rL < 0.08 && bL-rL > 0.05 { + if x < post3dWidth/2 { + haloPixels++ + } else { + mutedHaloPixels++ + } + } + } + } + if haloPixels < 150 { + t.Errorf("bright HDR box produced only %d halo pixels, want >= 150", haloPixels) + } + if mutedHaloPixels > 5 { + t.Errorf("muted non-blooming box produced %d halo pixels, want <= 5", mutedHaloPixels) + } +} + +func TestPost3DSSAOMatchesReference(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dWidth, post3dHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + + sceneRT, err := dev.CreateRenderTarget(nil, gpu.RenderTargetDesc{ + Label: "ssao.scene", + Width: post3dWidth, + Height: post3dHeight, + ColorFormat: gpu.FormatRGBA16Float, + DepthFormat: gpu.FormatDepth32Float, + }) + if err != nil { + t.Fatalf("CreateRenderTarget: %v", err) + } + defer func() { _ = sceneRT.Close() }() + + sp := newPost3dScenePipeline(t, nil, dev, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + defer func() { _ = sp.cam.Close() }() + + // Uniform unlit gray floor + back wall + cube resting directly on the floor so all darkening comes from SSAO. + gray := [3]float32{0.82, 0.82, 0.82} + var verts []float32 + // Floor at Y = 0 + verts = post3dAppendQuad(verts, + math3d.Vec3{X: -6, Y: 0, Z: 6}, + math3d.Vec3{X: 6, Y: 0, Z: 6}, + math3d.Vec3{X: 6, Y: 0, Z: -3}, + math3d.Vec3{X: -6, Y: 0, Z: -3}, + math3d.Vec3Up(), gray, 1.0) + // Back wall at Z = -2.2 + verts = post3dAppendQuad(verts, + math3d.Vec3{X: -6, Y: 0, Z: -2.2}, + math3d.Vec3{X: 6, Y: 0, Z: -2.2}, + math3d.Vec3{X: 6, Y: 4, Z: -2.2}, + math3d.Vec3{X: -6, Y: 4, Z: -2.2}, + math3d.Vec3{Z: 1}, gray, 1.0) + // Cube resting on the floor (Y in [0, 1.2]) + verts = post3dAppendBox(verts, math3d.Vec3{X: 0, Y: 0.6, Z: 0.0}, math3d.Vec3{X: 0.65, Y: 0.6, Z: 0.65}, gray, 1.0) + + vb, err := dev.CreateBuffer(nil, gpu.BufferDesc{Label: "ssao.verts", Usage: gpu.UsageVertex, Data: post3dPackFloats(verts)}) + if err != nil { + t.Fatalf("CreateBuffer: %v", err) + } + defer func() { _ = vb.Close() }() + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 2.2, Y: 2.4, Z: 3.6}, math3d.DegToRad(48), float32(post3dWidth)/float32(post3dHeight), 0.2, 30) + cam.LookAt(math3d.Vec3{X: 0, Y: 0.4, Z: -0.3}, math3d.Vec3Up()) + + cfg := render3d.SSAOConfigFromCamera(cam) + cfg.Radius = 0.85 + cfg.Bias = 0.03 + cfg.Intensity = 1.8 + cfg.Power = 1.6 + cfg.SampleCount = 12 + cfg.BlurRadius = 2 + cfg.DepthThreshold = 0.25 + + ssao, err := render3d.NewSSAOPass(nil, dev, render3d.SSAOPassOptions{ + Width: post3dWidth, + Height: post3dHeight, + ColorFormat: gpu.FormatRGBA16Float, + OutputFormat: gpu.FormatRGBA8Unorm, + Config: cfg, + }) + if err != nil { + t.Fatalf("NewSSAOPass: %v", err) + } + defer func() { _ = ssao.Close() }() + + renderFrame := func(c render3d.SSAOConfig) *image.RGBA { + if err := ssao.SetConfig(c); err != nil { + t.Fatalf("SetConfig: %v", err) + } + sp.cam.WriteCamera(cam) + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{ + Texture: sceneRT.Color, + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: core.RGB(0x284060), + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: sceneRT.Depth, + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) + sp.draw(pass, vb, uint32(len(verts)/10)) + pass.End() + if err := ssao.Apply(dev, enc, sceneRT.Color, sceneRT.Depth, nil); err != nil { + t.Fatalf("SSAOPass.Apply: %v", err) + } + dev.Submit(enc.Finish()) + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + return sr.Image() + } + + ssaoImg := renderFrame(cfg) + post3dAssertGolden(t, "post3d_ssao", ssaoImg) + + if ssao.AOTexture() == nil || !ssao.AOTexture().Valid() { + t.Error("AOTexture() invalid after Apply") + } + + // Project a point right in the concave cube-to-floor crease and a point on open flat floor. + creasePt, _, ok1 := cam.WorldToScreen(math3d.Vec3{X: 0.72, Y: 0.02, Z: 0.0}, post3dWidth, post3dHeight) + openPt, _, ok2 := cam.WorldToScreen(math3d.Vec3{X: -1.6, Y: 0.02, Z: 0.8}, post3dWidth, post3dHeight) + if !ok1 || !ok2 { + t.Fatalf("projected test points out of view: crease=%v(%v) open=%v(%v)", creasePt, ok1, openPt, ok2) + } + cx, cy := int(creasePt.X), int(creasePt.Y) + ox, oy := int(openPt.X), int(openPt.Y) + creaseLuma := post3dRegionLumaMean(ssaoImg, max(0, cx-2), max(0, cy-2), min(post3dWidth, cx+3), min(post3dHeight, cy+3)) + openLuma := post3dRegionLumaMean(ssaoImg, max(0, ox-3), max(0, oy-3), min(post3dWidth, ox+4), min(post3dHeight, oy+4)) + + if creaseLuma >= openLuma-0.08 { + t.Errorf("SSAO crease luma %.3f not meaningfully darker than open floor luma %.3f", creaseLuma, openLuma) + } + + // Intensity = 0 disables ambient occlusion darkening. + zeroCfg := cfg + zeroCfg.Intensity = 0 + noAOImg := renderFrame(zeroCfg) + noAOCrease := post3dRegionLumaMean(noAOImg, max(0, cx-2), max(0, cy-2), min(post3dWidth, cx+3), min(post3dHeight, cy+3)) + if noAOCrease <= creaseLuma+0.08 { + t.Errorf("Intensity=0 crease luma %.3f should be brighter than SSAO crease %.3f", noAOCrease, creaseLuma) + } +} + +func TestPost3DDepthOfFieldMatchesReference(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dWidth, post3dHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + + sceneRT, err := dev.CreateRenderTarget(nil, gpu.RenderTargetDesc{ + Label: "dof.scene", + Width: post3dWidth, + Height: post3dHeight, + ColorFormat: gpu.FormatRGBA16Float, + DepthFormat: gpu.FormatDepth32Float, + }) + if err != nil { + t.Fatalf("CreateRenderTarget: %v", err) + } + defer func() { _ = sceneRT.Close() }() + + sp := newPost3dScenePipeline(t, nil, dev, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + defer func() { _ = sp.cam.Close() }() + + // Three high-contrast checkerboard panels placed at near (dist=2.2), focus (dist=5.0), and far (dist=10.5), + // scaled proportionally to their distance so all three occupy similar screen regions side by side. + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Z: 0}, math3d.DegToRad(50), float32(post3dWidth)/float32(post3dHeight), 0.5, 25.0) + cam.LookAt(math3d.Vec3{Z: -5}, math3d.Vec3Up()) + + var verts []float32 + // Left: near panel at z = -2.2 (red/white checker) + verts = post3dAppendCheckerPanel(verts, math3d.Vec3{X: -0.82, Y: 0, Z: -2.2}, 0.65, 0.95, 6, 8, [3]float32{0.95, 0.2, 0.2}, [3]float32{0.95, 0.95, 0.95}) + // Center: in-focus panel at z = -5.0 (green/black checker) + verts = post3dAppendCheckerPanel(verts, math3d.Vec3{X: 0.0, Y: 0, Z: -5.0}, 1.45, 2.15, 6, 8, [3]float32{0.15, 0.95, 0.25}, [3]float32{0.05, 0.08, 0.05}) + // Right: far panel at z = -10.5 (blue/white checker) + verts = post3dAppendCheckerPanel(verts, math3d.Vec3{X: 3.9, Y: 0, Z: -10.5}, 3.1, 4.5, 6, 8, [3]float32{0.2, 0.4, 0.95}, [3]float32{0.95, 0.95, 0.95}) + + vb, err := dev.CreateBuffer(nil, gpu.BufferDesc{Label: "dof.verts", Usage: gpu.UsageVertex, Data: post3dPackFloats(verts)}) + if err != nil { + t.Fatalf("CreateBuffer: %v", err) + } + defer func() { _ = vb.Close() }() + + dofCfg := render3d.DepthOfFieldConfigFromCamera(cam, 5.0, 1.8, 5.0) + dof, err := render3d.NewDepthOfFieldPass(nil, dev, render3d.DepthOfFieldPassOptions{ + Width: post3dWidth, + Height: post3dHeight, + ColorFormat: gpu.FormatRGBA16Float, + OutputFormat: gpu.FormatRGBA8Unorm, + Config: dofCfg, + }) + if err != nil { + t.Fatalf("NewDepthOfFieldPass: %v", err) + } + defer func() { _ = dof.Close() }() + + renderFrame := func(c render3d.DepthOfFieldConfig) *image.RGBA { + if err := dof.SetConfig(c); err != nil { + t.Fatalf("SetConfig: %v", err) + } + sp.cam.WriteCamera(cam) + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{ + Texture: sceneRT.Color, + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: core.RGB(0x141820), + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: sceneRT.Depth, + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) + sp.draw(pass, vb, uint32(len(verts)/10)) + pass.End() + if err := dof.Apply(dev, enc, sceneRT.Color, sceneRT.Depth, nil); err != nil { + t.Fatalf("DepthOfFieldPass.Apply: %v", err) + } + dev.Submit(enc.Finish()) + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + return sr.Image() + } + + dofImg := renderFrame(dofCfg) + post3dAssertGolden(t, "post3d_dof", dofImg) + + sharpCfg := dofCfg + sharpCfg.MaxBlurRadius = 0 + sharpImg := renderFrame(sharpCfg) + + // Measure local contrast inside each panel's screen region. + nearRaw := post3dRegionContrast(sharpImg, 12, 26, 36, 70) + nearDoF := post3dRegionContrast(dofImg, 12, 26, 36, 70) + focusRaw := post3dRegionContrast(sharpImg, 52, 26, 76, 70) + focusDoF := post3dRegionContrast(dofImg, 52, 26, 76, 70) + farRaw := post3dRegionContrast(sharpImg, 92, 26, 116, 70) + farDoF := post3dRegionContrast(dofImg, 92, 26, 116, 70) + + // In-focus panel preserves high contrast (> 90% of unblurred contrast). + if focusRaw < 0.05 || focusDoF < focusRaw*0.90 { + t.Errorf("in-focus panel blurred unexpectedly: focusDoF=%.4f vs focusRaw=%.4f", focusDoF, focusRaw) + } + // Near and far out-of-focus panels lose substantial high-frequency contrast (< 60% of unblurred contrast). + if nearRaw < 0.05 || nearDoF > nearRaw*0.60 { + t.Errorf("near out-of-focus panel did not blur enough: nearDoF=%.4f vs nearRaw=%.4f", nearDoF, nearRaw) + } + if farRaw < 0.05 || farDoF > farRaw*0.60 { + t.Errorf("far out-of-focus panel did not blur enough: farDoF=%.4f vs farRaw=%.4f", farDoF, farRaw) + } +} + +func TestPost3DStackCombinedResizeAndProfiles(t *testing.T) { + // 1. Combined SSAO + DoF + Bloom golden render on headless software device. + sr := gpu.NewSoftwareRenderer(post3dWidth, post3dHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 1.8, Y: 2.0, Z: 4.5}, math3d.DegToRad(48), float32(post3dWidth)/float32(post3dHeight), 0.2, 40) + cam.LookAt(math3d.Vec3{X: 0, Y: 0.4, Z: -0.5}, math3d.Vec3Up()) + + ssaoCfg := render3d.SSAOConfigFromCamera(cam) + ssaoCfg.Radius = 0.8 + ssaoCfg.Intensity = 1.6 + ssaoCfg.BlurRadius = 1 + + dofCfg := render3d.DepthOfFieldConfigFromCamera(cam, 5.2, 2.5, 3.5) + bloomCfg := render3d.BloomConfig{ + Threshold: 0.9, + SoftKnee: 0.4, + Intensity: 0.8, + Radius: 1.5, + BlurPasses: 2, + HalfRes: true, + } + + stack, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{ + Width: post3dWidth, + Height: post3dHeight, + ColorFormat: gpu.FormatRGBA16Float, + DepthFormat: gpu.FormatDepth32Float, + OutputFormat: gpu.FormatRGBA8Unorm, + EnableSSAO: true, + SSAO: ssaoCfg, + EnableDoF: true, + DoF: dofCfg, + EnableBloom: true, + Bloom: bloomCfg, + }) + if err != nil { + t.Fatalf("NewPostStack3D: %v", err) + } + defer func() { _ = stack.Close() }() + + if stack.Width() != post3dWidth || stack.Height() != post3dHeight || + stack.ColorFormat() != gpu.FormatRGBA16Float || stack.DepthFormat() != gpu.FormatDepth32Float || + stack.OutputFormat() != gpu.FormatRGBA8Unorm || !stack.Valid() { + t.Fatalf("unexpected stack metadata: %dx%d color=%s depth=%s out=%s valid=%v", + stack.Width(), stack.Height(), stack.ColorFormat(), stack.DepthFormat(), stack.OutputFormat(), stack.Valid()) + } + + sp := newPost3dScenePipeline(t, nil, dev, stack.ColorFormat(), stack.DepthFormat()) + defer func() { _ = sp.cam.Close() }() + + var verts []float32 + // Ground floor + verts = post3dAppendQuad(verts, + math3d.Vec3{X: -6, Y: 0, Z: 6}, math3d.Vec3{X: 6, Y: 0, Z: 6}, + math3d.Vec3{X: 6, Y: 0, Z: -8}, math3d.Vec3{X: -6, Y: 0, Z: -8}, + math3d.Vec3Up(), [3]float32{0.55, 0.57, 0.6}, 0.5) + // In-focus matte block resting on ground (shows SSAO contact crease) + verts = post3dAppendBox(verts, math3d.Vec3{X: -0.2, Y: 0.5, Z: -0.2}, math3d.Vec3{X: 0.55, Y: 0.5, Z: 0.55}, [3]float32{0.75, 0.72, 0.68}, 0.5) + // HDR emissive beacon box (produces Bloom halo) + verts = post3dAppendBox(verts, math3d.Vec3{X: 1.35, Y: 0.45, Z: -0.4}, math3d.Vec3{X: 0.35, Y: 0.45, Z: 0.35}, [3]float32{2.5, 1.4, 0.4}, 1.0) + // Far background checkered pillar (blurred by DoF) + verts = post3dAppendCheckerPanel(verts, math3d.Vec3{X: -1.8, Y: 1.2, Z: -5.5}, 2.2, 2.2, 4, 4, [3]float32{0.2, 0.5, 0.85}, [3]float32{0.85, 0.85, 0.85}) + + vb, err := dev.CreateBuffer(nil, gpu.BufferDesc{Label: "combined.verts", Usage: gpu.UsageVertex, Data: post3dPackFloats(verts)}) + if err != nil { + t.Fatalf("CreateBuffer: %v", err) + } + defer func() { _ = vb.Close() }() + + renderCombined := func() *image.RGBA { + sp.cam.WriteCamera(cam) + enc := dev.BeginEncoder() + pass := stack.BeginScenePass(enc, core.RGB(0x0c1018)) + sp.draw(pass, vb, uint32(len(verts)/10)) + pass.End() + if err := stack.ApplyScene(dev, enc, nil); err != nil { + t.Fatalf("ApplyScene: %v", err) + } + dev.Submit(enc.Finish()) + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + return sr.Image() + } + + combinedImg := renderCombined() + post3dAssertGolden(t, "post3d_combined", combinedImg) + + // Passthrough blit when all passes are disabled must differ cleanly from combined post-processed output. + if err := stack.SetSSAO(false, ssaoCfg); err != nil { + t.Fatalf("SetSSAO(false): %v", err) + } + if err := stack.SetDepthOfField(false, dofCfg); err != nil { + t.Fatalf("SetDepthOfField(false): %v", err) + } + if err := stack.SetBloom(false, bloomCfg); err != nil { + t.Fatalf("SetBloom(false): %v", err) + } + blitImg := renderCombined() + if diff := post3dMaxChannelDiff(combinedImg, blitImg); diff < 25 { + t.Errorf("combined post-processing max diff vs passthrough blit = %d, want >= 25", diff) + } + + // Re-enable all passes and resize the stack. + if err := stack.SetSSAO(true, ssaoCfg); err != nil { + t.Fatalf("SetSSAO(true): %v", err) + } + if err := stack.SetDepthOfField(true, dofCfg); err != nil { + t.Fatalf("SetDepthOfField(true): %v", err) + } + if err := stack.SetBloom(true, bloomCfg); err != nil { + t.Fatalf("SetBloom(true): %v", err) + } + if err := stack.Resize(dev, 96, 72); err != nil { + t.Fatalf("Resize: %v", err) + } + if stack.Width() != 96 || stack.Height() != 72 || stack.SceneTarget().Width != 96 || stack.SceneTarget().Height != 72 { + t.Fatalf("Resize did not update dimensions: %dx%d", stack.Width(), stack.Height()) + } + // Resize back and render again. + if err := stack.Resize(dev, post3dWidth, post3dHeight); err != nil { + t.Fatalf("Resize back: %v", err) + } + afterResize := renderCombined() + if diff := post3dMaxChannelDiff(combinedImg, afterResize); diff > 1 { + t.Errorf("render after resize round-trip differed by %d", diff) + } + + // 2. Run inside mounted headless nsgotest gpu.View on both full and NoGPUCompute (WebGL 2 / GLES 3.0) profiles, + // including Retained device-loss recovery. + for _, tc := range []struct { + name string + opts []nsgotest.Option + }{ + {"full", []nsgotest.Option{nsgotest.Size(64, 48)}}, + {"no_gpu_compute", []nsgotest.Option{nsgotest.Size(64, 48), nsgotest.NoGPUCompute()}}, + } { + t.Run(tc.name, func(t *testing.T) { + var ( + viewStack *render3d.PostStack3D + viewPipe *post3dScenePipeline + viewVB *gpu.Buffer + frames int + applyErr error + ) + viewCam := scene3d.NewPerspectiveCamera(math3d.Vec3{Z: 4}, math3d.DegToRad(50), 64.0/48.0, 0.2, 30) + viewCam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + boxVerts := post3dAppendBox(nil, math3d.Vec3Zero(), math3d.Vec3{X: 0.6, Y: 0.6, Z: 0.6}, [3]float32{2.0, 1.2, 0.4}, 1.0) + + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "post3d-view", + Style: core.Style{Width: core.Pt(64), Height: core.Pt(48)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(d *gpu.Device) { + if viewStack == nil { + var err error + viewStack, err = render3d.NewPostStack3D(cx, d, render3d.PostStack3DOptions{ + Width: 64, + Height: 48, + ColorFormat: gpu.FormatRGBA16Float, + DepthFormat: gpu.FormatDepth32Float, + OutputFormat: d.SurfaceFormat(), + Retained: true, + EnableSSAO: true, + SSAO: render3d.SSAOConfigFromCamera(viewCam), + EnableDoF: true, + DoF: render3d.DepthOfFieldConfigFromCamera(viewCam, 4.0, 2.0, 3.0), + EnableBloom: true, + Bloom: render3d.DefaultBloomConfig(), + }) + if err != nil { + applyErr = err + return + } + viewVB, err = d.CreateBuffer(cx, gpu.BufferDesc{ + Usage: gpu.UsageVertex, + Data: post3dPackFloats(boxVerts), + Retained: true, + }) + if err != nil { + applyErr = err + return + } + } + viewPipe = newPost3dScenePipeline(t, cx, d, viewStack.ColorFormat(), viewStack.DepthFormat()) + }, + OnFrame: func(frame *gpu.Frame) { + if viewStack == nil || viewPipe == nil || viewVB == nil { + return + } + viewPipe.cam.WriteCamera(viewCam) + pass := viewStack.BeginScenePass(frame, core.RGB(0x080c14)) + viewPipe.draw(pass, viewVB, uint32(len(boxVerts)/10)) + pass.End() + if err := viewStack.ApplyScene(frame.Device(), frame, nil); err != nil { + applyErr = err + return + } + frame.Submit() + frames++ + }, + }) + }, tc.opts...) + + app.Advance(32 * time.Millisecond) + if applyErr != nil { + t.Fatalf("gpu.View post-processing error: %v", applyErr) + } + if frames == 0 { + t.Fatal("gpu.View rendered 0 frames") + } + img, err := app.GPUReadPixels("id:post3d-view") + if err != nil { + t.Fatalf("GPUReadPixels: %v", err) + } + // Center pixel should be bright (emissive box rendered through PostStack3D). + if l := post3dLuma(img, 32, 24); l < 0.5 { + t.Errorf("gpu.View center pixel luma = %.3f, want >= 0.5", l) + } + + // Verify Retained device-loss restoration continues rendering cleanly. + app.TriggerGPUDeviceLost("id:post3d-view", nsgotest.GPULostContextLost, "context lost") + app.RestoreGPUDevice("id:post3d-view") + prevFrames := frames + app.Advance(32 * time.Millisecond) + if applyErr != nil { + t.Fatalf("after device restore: %v", applyErr) + } + if frames <= prevFrames { + t.Fatalf("no frames drawn after device restore (before=%d after=%d)", prevFrames, frames) + } + restoredImg, err := app.GPUReadPixels("id:post3d-view") + if err != nil { + t.Fatalf("GPUReadPixels after restore: %v", err) + } + if l := post3dLuma(restoredImg, 32, 24); l < 0.5 { + t.Errorf("gpu.View center pixel luma after restore = %.3f, want >= 0.5", l) + } + }) + } +} + +func TestPost3DValidationAndLifecycle(t *testing.T) { + nan := float32(math.NaN()) + inf := float32(math.Inf(1)) + + // BloomConfig validation + for _, tc := range []struct { + name string + cfg render3d.BloomConfig + }{ + {"neg threshold", render3d.BloomConfig{Threshold: -0.1}}, + {"nan threshold", render3d.BloomConfig{Threshold: nan}}, + {"knee > 1", render3d.BloomConfig{SoftKnee: 1.5}}, + {"neg knee", render3d.BloomConfig{SoftKnee: -0.1}}, + {"neg intensity", render3d.BloomConfig{Intensity: -1}}, + {"inf radius", render3d.BloomConfig{Radius: inf}}, + {"too many blur passes", render3d.BloomConfig{BlurPasses: 9}}, + {"neg blur passes", render3d.BloomConfig{BlurPasses: -1}}, + } { + if err := tc.cfg.Validate(); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("BloomConfig(%s).Validate = %v, want ErrInvalidPostProcess", tc.name, err) + } + } + + // SSAOConfig validation + validSSAO := render3d.DefaultSSAOConfig() + for _, tc := range []struct { + name string + mutate func(*render3d.SSAOConfig) + }{ + {"zero radius", func(c *render3d.SSAOConfig) { c.Radius = 0 }}, + {"neg bias", func(c *render3d.SSAOConfig) { c.Bias = -0.01 }}, + {"intensity > 4", func(c *render3d.SSAOConfig) { c.Intensity = 5 }}, + {"zero power", func(c *render3d.SSAOConfig) { c.Power = 0 }}, + {"too few samples", func(c *render3d.SSAOConfig) { c.SampleCount = 2 }}, + {"too many samples", func(c *render3d.SSAOConfig) { c.SampleCount = 24 }}, + {"blur radius > 4", func(c *render3d.SSAOConfig) { c.BlurRadius = 5 }}, + {"neg depth thresh", func(c *render3d.SSAOConfig) { c.DepthThreshold = -1 }}, + {"bad near/far", func(c *render3d.SSAOConfig) { c.Near = 10; c.Far = 5 }}, + {"singular proj", func(c *render3d.SSAOConfig) { c.ProjMatrix = math3d.Mat4{0: 1} }}, + {"nan proj", func(c *render3d.SSAOConfig) { c.ProjMatrix = math3d.Mat4{0: nan} }}, + } { + cfg := validSSAO + tc.mutate(&cfg) + if err := cfg.Validate(); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("SSAOConfig(%s).Validate = %v, want ErrInvalidPostProcess", tc.name, err) + } + } + + // DepthOfFieldConfig validation + validDoF := render3d.DefaultDepthOfFieldConfig() + for _, tc := range []struct { + name string + mutate func(*render3d.DepthOfFieldConfig) + }{ + {"zero focus dist", func(c *render3d.DepthOfFieldConfig) { c.FocusDistance = 0 }}, + {"zero focus range", func(c *render3d.DepthOfFieldConfig) { c.FocusRange = 0 }}, + {"neg max blur", func(c *render3d.DepthOfFieldConfig) { c.MaxBlurRadius = -1 }}, + {"far <= near", func(c *render3d.DepthOfFieldConfig) { c.Near = 5; c.Far = 5 }}, + {"nan near", func(c *render3d.DepthOfFieldConfig) { c.Near = nan }}, + } { + cfg := validDoF + tc.mutate(&cfg) + if err := cfg.Validate(); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("DepthOfFieldConfig(%s).Validate = %v, want ErrInvalidPostProcess", tc.name, err) + } + } + + // Nil receiver safety + var ( + nilBloom *render3d.BloomPass + nilSSAO *render3d.SSAOPass + nilDoF *render3d.DepthOfFieldPass + nilStack *render3d.PostStack3D + ) + if nilBloom.Valid() || nilBloom.Width() != 0 || nilBloom.Height() != 0 || nilBloom.Close() != nil { + t.Error("nil BloomPass methods returned unexpected values") + } + if nilSSAO.Valid() || nilSSAO.Width() != 0 || nilSSAO.Height() != 0 || nilSSAO.AOTexture() != nil || nilSSAO.Close() != nil { + t.Error("nil SSAOPass methods returned unexpected values") + } + if nilDoF.Valid() || nilDoF.Width() != 0 || nilDoF.Height() != 0 || nilDoF.Close() != nil { + t.Error("nil DepthOfFieldPass methods returned unexpected values") + } + if nilStack.Valid() || nilStack.Width() != 0 || nilStack.Height() != 0 || nilStack.SceneTarget() != nil || + nilStack.SSAO() != nil || nilStack.DepthOfField() != nil || nilStack.Bloom() != nil || + nilStack.BeginScenePass(nil, core.RGB(0)) != nil || nilStack.Close() != nil { + t.Error("nil PostStack3D methods returned unexpected values") + } + + // Nil device / invalid dimensions / invalid formats + if _, err := render3d.NewBloomPass(nil, nil, render3d.BloomPassOptions{Width: 16, Height: 16}); !errors.Is(err, gpu.ErrDeviceLost) { + t.Errorf("NewBloomPass(nil dev) = %v, want ErrDeviceLost", err) + } + if _, err := render3d.NewSSAOPass(nil, nil, render3d.SSAOPassOptions{Width: 16, Height: 16, Config: validSSAO}); !errors.Is(err, gpu.ErrDeviceLost) { + t.Errorf("NewSSAOPass(nil dev) = %v, want ErrDeviceLost", err) + } + if _, err := render3d.NewDepthOfFieldPass(nil, nil, render3d.DepthOfFieldPassOptions{Width: 16, Height: 16, Config: validDoF}); !errors.Is(err, gpu.ErrDeviceLost) { + t.Errorf("NewDepthOfFieldPass(nil dev) = %v, want ErrDeviceLost", err) + } + if _, err := render3d.NewPostStack3D(nil, nil, render3d.PostStack3DOptions{Width: 16, Height: 16}); !errors.Is(err, gpu.ErrDeviceLost) { + t.Errorf("NewPostStack3D(nil dev) = %v, want ErrDeviceLost", err) + } + + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + + if _, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{Width: 0, Height: 16}); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("zero width = %v, want ErrInvalidPostProcess", err) + } + if _, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{Width: 16, Height: 16, ColorFormat: gpu.FormatDepth32Float}); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("depth as ColorFormat = %v, want ErrInvalidPostProcess", err) + } + if _, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{Width: 16, Height: 16, DepthFormat: gpu.FormatRGBA8Unorm}); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("color as DepthFormat = %v, want ErrInvalidPostProcess", err) + } + + // Close idempotency & post-close rejection + stack, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{Width: 16, Height: 16, EnableBloom: true, Bloom: render3d.DefaultBloomConfig()}) + if err != nil { + t.Fatalf("NewPostStack3D: %v", err) + } + if err := stack.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if err := stack.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + if stack.Valid() { + t.Error("closed PostStack3D still reports Valid()") + } + if err := stack.Resize(dev, 32, 32); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("Resize after Close = %v, want ErrInvalidPostProcess", err) + } + enc := dev.BeginEncoder() + if err := stack.ApplyScene(dev, enc, nil); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("ApplyScene after Close = %v, want ErrInvalidPostProcess", err) + } +} diff --git a/packages/game/render3d/testdata/golden/post3d_bloom.png b/packages/game/render3d/testdata/golden/post3d_bloom.png new file mode 100644 index 0000000000000000000000000000000000000000..9a53bb31ac4203d4019f9d91b5dcc13efbafb7e4 GIT binary patch literal 3110 zcmZ|R_dgVl;|K6t8F7P*oHG)Mh}>Ca?~s*EvN!QILdNAfVgvX?d)( zo;n)HY3K<_xsCfIJ9i$za^CM{0dfP0znU`Y`dG0x&DM(KQf4Cf z3Bvc?m1Qv)-SwQ$rGG+%U)pozA(4;_u>O_F$dEAnFJzmisP%d5>B-F)w{smBJt*($ zohietFEMJOuE+|D-lR?>LtvOTC`VPlYdGvElztgDe4Dbpqc!Qau<@#BC^beVy!kq8 z610$~42V{`lkon`sQ%dXSoL&m=1Gj!i4-qOO8AG9X<+A2Xxb&T97*7(Nj8RDX#O}0 zx7*9;)XFZ$t=Iv5ug?WVwCw-t2*sx>jg>fBBYc#Tui?sEgug!fXIT{bnbI$uST|`T z1M2MYPGqw*Iq&Ii2g!v@6%yLB)#~qY3)93ARy-=diNKX$3ee7ACV8bZwJ)mHA?h&2 z*!F?HBv612+vlY63s7(6xr;7R-Cdi8a%4>dLjT-@@F)Tn4vc}{<$e3{oe?-<%tEmN zEqjVpbHd|vOkVA{E(O&pe=bsD$%>3u;tO)G{qwVQJw%|=zE4Hs8FEs+8b8L#?33#w z8yfu_agumPeU;rHjnNuaDex?FjLSHU|sSl7VIJmX#BLjtt1M9C!7Z>^oEp&zG71!tT~o2LMlh6;oe?6N?+ zdfS$+5?l1CRFmJ&uyI*a1CKmS&GzDv%|aO)t{{@XyV$;l7I}%MuOLOshD?N7KB{&A?tuSzix zVXizlIX4*hkP+HkM*N=7fQsUZUD+A*IrL)H3@=N`?f zP1c%x7mrh~Ap82IERhB8!1WXOiuntO&lnE?nd!PU+1-Yp`TgARjz(@s) z-gQJ;Z?^eb0E}@CijkMjti@icumt>88UcDKA2lj|c-MV)W;uOy;A@{9R_8~@XsP6c z(vWQ@>0dquuRxN#*l`9n4b1#B&XoZE3C*OPM|{v|0HIrPGb zQ_U;)4KTif)92$BJTro)lz3Tg^o=*QYyB2jiF7z*t7h^$LEPR!M;-IG&T@NdH+!xI z4h_wkMmn4{_(eWf&v`hD=jH

cc1A=>dnIKefDvz>s`Hx5l$@KOZbjzs&edwwDi2 zRAwG^JIV322;QsA*bC#+xpS@{i)QTcXx}LtwIGd(mNeWn$(y2aSjEd5wV4ss{OJkc z`E?V|UF(#T_v7Il*5&QcRUG-Q^hoVu0_mte?WX7Lv8*M+oq46^E3ZmcX=B1W%dzy` zKc+oa9!lyg+&Q3^(4&i9fmM%-9=0|8nWg>cQ|VHqZsOnJOpzhQa@wANx`mZuz`RNe)-lkoJl${U+%Rx~L7 zM|->`Z4Q^?Af}R3Zs$=qHCDAE!8919A9&OEJ5j#T8s8ylE+_0Iiz}!$dsUG7S1(XZ!GSZfGaIitgO?9$%hEp6e*r1Bc-TH z&+5EP{5>K^6|Q0wD{2;M^5ZT{ZOQfcHFtKFHtLiG+fItZtUfx@hRkCX9FPfveN%b>oA|-@~?U$dX^t)%9XVp*YEXcUc;x6WjI@gqfbSYvi@#g5ro zzmFrghM)`q>dXu~7@;m2z}EPy^SS6hfk8d*DJ30_YOLSSZgREPZ^d!4BKbep5EakY zIG~y@XD%fm*#T}}Sn(|*i!8PnF~`Hi8x6*dKdFGlbEjUDN#kV4>ETLs*>#V zpnLkybIm{B{My({9_9qD8$G1EwWez>*z;p$hGh^V^`*&8kSe7@mGU-D^qot8R~4EU z-72%?{=K&FMsVOHlPurOBY*Awe73@?Z)x^?Nn{A0$}&{+DSupBVi6I3ejSA#;$}}z z`&IbU7DJ_O=4ZFT-ZikUfW>S5Q`LFgmF{-y4o8?cfO3bV17*FOE(VCe;Q z@2@di7kw%Ul@8I|=#N>Ref5-6;hYaIa8+o|6@pGzH=Ww4f!wD&EhA$OcJCRy*z}=3 z+%G*C^`TPsioQ4@6>5f57`O5#G%saWi*fcmrHqJX97Vj;()R;aY)di`DB2A{)a2cvX;W@-Cm1I~Z7^ zE9t&z9yLJ;*Td4$IBFQ;utjx+wiV_dQz<*NANDqQE(S1?FJ`5kXw%U+?aL1x-E!-H z(c0u%FX|4SnHj|p7H0z)GYX^@;%N<7vt2wP{0A}r8Yv9tiECWxzWXJ2Dm*XAE5jOeU-zvV z4+BmJJF6Ad;gS&;7Ib|3#eiqE$ip2vBTj8))r7s`nc)xmiF&}PE9PVw>08>c+b_`2 z2ZO6F#*KxK2tDngIGGzaj&%9zQIltpbP{h`EWTIA2L_CaY2sxu(A8WR2nBM(*S$x0 zUAULm*ZxQ?!pLi(vvm8fBRvSJ!9>9F-MzGreh zUM%@@O6ozJu+i%d^nK_pcp6u^(!R#-?PIK}#ZLi^7ePJTWhPtNQE}M?lp`&7G>2f< qzb5su3~c_lu>YUGQ(+*EA>hmpzbHW7Sl5642V6C`Gkay?oB4mBaoKSI literal 0 HcmV?d00001 diff --git a/packages/game/render3d/testdata/golden/post3d_combined.png b/packages/game/render3d/testdata/golden/post3d_combined.png new file mode 100644 index 0000000000000000000000000000000000000000..6e54dab78e47c02da0ad2850bababc7e30263c49 GIT binary patch literal 6805 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 D>BI}! literal 0 HcmV?d00001 diff --git a/packages/game/render3d/testdata/golden/post3d_dof.png b/packages/game/render3d/testdata/golden/post3d_dof.png new file mode 100644 index 0000000000000000000000000000000000000000..e9e3ee0e9c4db1e209535a403105dfe55f6704c3 GIT binary patch literal 4800 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 F_%H3Jz|sH! literal 0 HcmV?d00001 From d95a6d27ee5d61dd61a6d2f4f3d5c16ca633ed97 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:12:26 +0900 Subject: [PATCH 2/9] refactor(render3d): use the shared RenderPassRecorder in post-processing --- .../2026-11-24-render3d-post-processing.md | 2 +- docs/en/render3d.md | 2 +- docs/zh/render3d.md | 2 +- packages/game/render3d/post3d.go | 35 ++++++------------- 4 files changed, 14 insertions(+), 27 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md b/.agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md index 12a66ccd..8797c167 100644 --- a/.agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-post-processing.md @@ -20,7 +20,7 @@ The existing 2D `game/effects` package fuses Kage fragment passes into a single - **Dedicated offscreen render targets and fixed stage order**: `PostStack3D` owns an offscreen color+depth scene target (`FormatRGBA16Float` + `FormatDepth32Float` by default, configurable to `FormatRGBA8Unorm` / `FormatDepth24Plus`) and two ping-pong color targets. Enabled passes run in order **SSAO -> Depth of Field -> Bloom** so ambient occlusion darkens crevices before optical blur and highlights bloom afterward. Each pass holds separate intermediate (`ColorFormat`) and output (`OutputFormat`) composite pipelines so the final enabled pass writes directly to the swapchain or destination texture without an extra copy pass. - **Portable fragment-only WGSL**: All passes use a shared 3-vertex retained fullscreen triangle buffer (`z = 0.0`, avoiding far-plane `z = 1.0` clipping and empty-VAO WebGL 2 quirks), explicit `textureSampleLevel`, `FilterNearest` depth samplers, precomputed 9-tap separable Gaussian weights (Bloom), algebraic bilateral depth weights `1 / (1 + (dz / thresh)^2)` (SSAO blur), and edge-preserving 4-neighbor depth-difference normal reconstruction with a deterministic 4×4 stratified rotation pattern (SSAO). Zero `exp`/`exp2`/`log2`, `dpdx`/`dpdy`, or compute shaders are used. - **Per-stage uniform buffers and bind-group caching**: Each sub-pass (`extract`, `horizBlur`, `vertBlur`, `composite`, `ssao`, `ssaoBlur`, `coc`, `bokeh`) owns its own uniform buffer so multi-pass submissions in one `gpu.Frame` or `gpu.Encoder` never clobber earlier passes' uniforms. External input bind groups are cached by texture handle and closed on change, `Resize`, or `Close` to avoid steady-state leaks. -- **Device-parameterized methods (`PostPassRecorder`)**: Following [textures and samplers](2026-11-24-render3d-textures-and-samplers.md), passes never cache `*gpu.Device`; `Apply`, `ComputeAO`, and `Resize` accept `dev *gpu.Device` explicitly and a `PostPassRecorder` interface satisfied by both `*gpu.Frame` and `*gpu.Encoder`, allowing `Retained: true` resources to survive device loss and restoration cleanly. +- **Device-parameterized methods (`RenderPassRecorder`)**: Following [textures and samplers](2026-11-24-render3d-textures-and-samplers.md), passes never cache `*gpu.Device`; `Apply`, `ComputeAO`, and `Resize` accept `dev *gpu.Device` explicitly and the package's existing `RenderPassRecorder` interface (shared with `DynamicResolutionTarget`) satisfied by both `*gpu.Frame` and `*gpu.Encoder`, allowing `Retained: true` resources to survive device loss and restoration cleanly. ## Alternatives considered diff --git a/docs/en/render3d.md b/docs/en/render3d.md index c3bfe981..748777fe 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -1165,7 +1165,7 @@ _ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> Depth of Field -> Bl frame.Submit() ``` -- **Composable order and standalone passes**: `PostStack3D` runs enabled stages in fixed order — **SSAO -> Depth of Field -> Bloom** — routing intermediate results through ping-pong offscreen targets and writing the final stage directly in `OutputFormat` (or blitting cleanly when all stages are disabled). Each pass (`SSAOPass`, `DepthOfFieldPass`, `BloomPass`) can also be constructed and applied standalone against any caller-owned `gpu.Texture` color and depth attachments via `PostPassRecorder` (satisfied by both `*gpu.Frame` and `*gpu.Encoder`). +- **Composable order and standalone passes**: `PostStack3D` runs enabled stages in fixed order — **SSAO -> Depth of Field -> Bloom** — routing intermediate results through ping-pong offscreen targets and writing the final stage directly in `OutputFormat` (or blitting cleanly when all stages are disabled). Each pass (`SSAOPass`, `DepthOfFieldPass`, `BloomPass`) can also be constructed and applied standalone against any caller-owned `gpu.Texture` color and depth attachments via `RenderPassRecorder` (satisfied by both `*gpu.Frame` and `*gpu.Encoder`). - **SSAO (`SSAOConfig`, `SSAOPass`)**: reconstructs view-space positions and edge-preserving normals from the 3D depth buffer, evaluates a deterministic 4–16-sample hemisphere kernel with stratified 4×4 tangent rotation, applies an optional depth-aware bilateral blur (`BlurRadius`, `DepthThreshold`), and multiplies ambient occlusion into the scene color (`AOTexture` exposes the AO map for inspection). - **Depth of Field (`DepthOfFieldConfig`, `DepthOfFieldPass`)**: linearizes perspective or orthographic `[0, 1]` depth to compute a signed Circle of Confusion around `FocusDistance` ± `FocusRange`, then gathers an 18-tap two-ring disc bokeh blur that prevents blurred background pixels from bleeding across sharp in-focus silhouettes. - **Bloom (`BloomConfig`, `BloomPass`)**: extracts bright LDR or HDR (`> 1.0`) pixels with a quadratic `Threshold` / `SoftKnee` curve, runs `BlurPasses` separable 9-tap Gaussian horizontal and vertical passes (optionally at half resolution via `HalfRes`), and composites the glow additively with `Intensity`. diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 4ca22855..93ea70c1 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -1165,7 +1165,7 @@ _ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> 景深 -> Bloom -> frame.Submit() ``` -- **可组合管线与独立通道**:`PostStack3D` 按固定顺序执行已启用的阶段——**SSAO → 景深 → Bloom**——中间结果在乒乓离屏渲染目标之间流转,最后一个阶段直接以 `OutputFormat` 输出(全部关闭时执行干净直通复制)。每个通道(`SSAOPass`、`DepthOfFieldPass`、`BloomPass`)也可独立创建,并通过 `PostPassRecorder`(`*gpu.Frame` 与 `*gpu.Encoder` 均已实现)作用于调用方自建的 `gpu.Texture` 颜色与深度附件。 +- **可组合管线与独立通道**:`PostStack3D` 按固定顺序执行已启用的阶段——**SSAO → 景深 → Bloom**——中间结果在乒乓离屏渲染目标之间流转,最后一个阶段直接以 `OutputFormat` 输出(全部关闭时执行干净直通复制)。每个通道(`SSAOPass`、`DepthOfFieldPass`、`BloomPass`)也可独立创建,并通过 `RenderPassRecorder`(`*gpu.Frame` 与 `*gpu.Encoder` 均已实现)作用于调用方自建的 `gpu.Texture` 颜色与深度附件。 - **SSAO(`SSAOConfig`、`SSAOPass`)**:从 3D 深度缓冲重建视空间位置与保边法线,使用带 4×4 分层切线旋转的确定性 4–16 采样半球核计算遮蔽,支持可选的深度感知双边模糊(`BlurRadius`、`DepthThreshold`),并将环境光遮蔽乘入场景颜色(可通过 `AOTexture` 获取 AO 纹理)。 - **景深(`DepthOfFieldConfig`、`DepthOfFieldPass`)**:支持透视与正交 `[0, 1]` 深度线性化,围绕 `FocusDistance` ± `FocusRange` 计算带符号弥散圆(CoC),并通过 18 采样双环圆盘散景模糊平滑虚化近景与远景,同时阻止背景模糊色溢入清晰的焦内轮廓。 - **泛光(`BloomConfig`、`BloomPass`)**:用二次软拐点阈值曲线(`Threshold`、`SoftKnee`)提取 LDR 或 HDR(`> 1.0`)高亮像素,执行 `BlurPasses` 轮可分离 9 采样高斯横纵模糊(可通过 `HalfRes` 启用半分辨率以获得更宽柔和光晕),再以 `Intensity` 加法混合回场景。 diff --git a/packages/game/render3d/post3d.go b/packages/game/render3d/post3d.go index b954741e..0067e3c8 100644 --- a/packages/game/render3d/post3d.go +++ b/packages/game/render3d/post3d.go @@ -19,19 +19,6 @@ import ( // [NewSSAOPass], [NewDepthOfFieldPass], and [NewPostStack3D]). var ErrInvalidPostProcess = errors.New("render3d: invalid post-processing configuration") -// PostPassRecorder is the minimal render-pass recording surface shared by -// [*gpu.Frame] (inside [gpu.View]'s OnFrame) and [*gpu.Encoder] (for headless -// or custom command encoding). -type PostPassRecorder interface { - BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass -} - -// Compile-time assertions that both *gpu.Frame and *gpu.Encoder implement PostPassRecorder. -var ( - _ PostPassRecorder = (*gpu.Frame)(nil) - _ PostPassRecorder = (*gpu.Encoder)(nil) -) - const ( postMaxBloomBlurPasses = 8 postMaxSSAOSamples = 16 @@ -513,7 +500,7 @@ func createPostPipeline( }) } -func drawPostFullscreen(rec PostPassRecorder, label string, dst *gpu.Texture, pipe *gpu.Pipeline, bg *gpu.BindGroup, vb *gpu.Buffer) { +func drawPostFullscreen(rec RenderPassRecorder, label string, dst *gpu.Texture, pipe *gpu.Pipeline, bg *gpu.BindGroup, vb *gpu.Buffer) { pass := rec.BeginRenderPass(gpu.RenderPassDesc{ Label: label, ColorAttachments: []gpu.ColorAttachment{{ @@ -1079,11 +1066,11 @@ func (p *BloomPass) Resize(dev *gpu.Device, width, height uint32) error { // Apply runs bright extraction, separable blur, and additive composite from srcColor // into dstColor (nil writes to the swapchain using OutputFormat). -func (p *BloomPass) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, dstColor *gpu.Texture) error { +func (p *BloomPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, dstColor *gpu.Texture) error { return p.applyWithOutput(dev, rec, srcColor, dstColor, dstColor == nil) } -func (p *BloomPass) applyWithOutput(dev *gpu.Device, rec PostPassRecorder, srcColor, dstColor *gpu.Texture, useOutputFormat bool) error { +func (p *BloomPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, srcColor, dstColor *gpu.Texture, useOutputFormat bool) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } @@ -1730,7 +1717,7 @@ func (p *SSAOPass) Resize(dev *gpu.Device, width, height uint32) error { // ComputeAO evaluates the SSAO hemisphere pass (and optional bilateral blur) from // depthTex and returns the resulting AO texture for inspection or custom compositing. -func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec PostPassRecorder, depthTex *gpu.Texture) (*gpu.Texture, error) { +func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec RenderPassRecorder, depthTex *gpu.Texture) (*gpu.Texture, error) { if dev == nil { return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } @@ -1825,11 +1812,11 @@ func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec PostPassRecorder, depthTex *gp // Apply computes SSAO from depthTex and multiplies it onto srcColor, writing to // dstColor (nil writes to the swapchain using OutputFormat). -func (p *SSAOPass) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { +func (p *SSAOPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { return p.applyWithOutput(dev, rec, srcColor, depthTex, dstColor, dstColor == nil) } -func (p *SSAOPass) applyWithOutput(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { +func (p *SSAOPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { if srcColor == nil || !srcColor.Valid() { return fmt.Errorf("%w: invalid source color texture", ErrInvalidPostProcess) } @@ -2293,11 +2280,11 @@ func (p *DepthOfFieldPass) Resize(dev *gpu.Device, width, height uint32) error { // Apply runs the CoC prepass and depth-aware disc bokeh gather from srcColor and // depthTex into dstColor (nil writes to the swapchain using OutputFormat). -func (p *DepthOfFieldPass) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { +func (p *DepthOfFieldPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { return p.applyWithOutput(dev, rec, srcColor, depthTex, dstColor, dstColor == nil) } -func (p *DepthOfFieldPass) applyWithOutput(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { +func (p *DepthOfFieldPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } @@ -2706,7 +2693,7 @@ func (s *PostStack3D) SceneTarget() *gpu.RenderTarget { // BeginScenePass begins a render pass targeting [PostStack3D.SceneTarget], clearing // color to clearColor and depth to 1.0 and storing both attachments for post-processing. -func (s *PostStack3D) BeginScenePass(rec PostPassRecorder, clearColor core.Color) *gpu.RenderPass { +func (s *PostStack3D) BeginScenePass(rec RenderPassRecorder, clearColor core.Color) *gpu.RenderPass { if s == nil || s.closed || rec == nil || !s.sceneRT.Valid() { return nil } @@ -2895,7 +2882,7 @@ func (s *PostStack3D) Resize(dev *gpu.Device, width, height uint32) error { // ApplyScene executes all enabled passes on [PostStack3D.SceneTarget]'s color // and depth attachments, writing the result into dstColor (nil targets the swapchain). -func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec PostPassRecorder, dstColor *gpu.Texture) error { +func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec RenderPassRecorder, dstColor *gpu.Texture) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } @@ -2910,7 +2897,7 @@ func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec PostPassRecorder, dstColor // into dstColor (nil writes to the swapchain using OutputFormat). If depthTex // is nil, depth-dependent passes (SSAO and Depth of Field) are skipped; if no // pass runs, srcColor is blitted cleanly to dstColor. -func (s *PostStack3D) Apply(dev *gpu.Device, rec PostPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { +func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } From 348b3796d92f25bb823876c058880de112931030 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:13:43 +0900 Subject: [PATCH 3/9] fix(render3d): pick post-processing pipelines by destination format and validate input sizes --- packages/game/render3d/post3d.go | 147 ++++++++++++++++++++++--------- 1 file changed, 103 insertions(+), 44 deletions(-) diff --git a/packages/game/render3d/post3d.go b/packages/game/render3d/post3d.go index 0067e3c8..acbcd4dd 100644 --- a/packages/game/render3d/post3d.go +++ b/packages/game/render3d/post3d.go @@ -566,6 +566,45 @@ func postValidateSize(w, h uint32) error { return nil } +// postDestFormat returns the format the final draw of a pass writes: OutputFormat for the swapchain (nil dst), otherwise dst's own format, which must be the pass's ColorFormat or OutputFormat because those are the only formats it has pipelines for. +func postDestFormat(dst *gpu.Texture, colorFmt, outFmt gpu.TextureFormat) (gpu.TextureFormat, error) { + if dst == nil { + return outFmt, nil + } + f := dst.Desc().Format + if f != colorFmt && f != outFmt { + return gpu.FormatUndefined, fmt.Errorf("%w: destination format %s is neither ColorFormat %s nor OutputFormat %s", ErrInvalidPostProcess, f, colorFmt, outFmt) + } + return f, nil +} + +// postPickPipeline returns the pipeline built for dstFmt: inter targets colorFmt, out (nil when OutputFormat equals ColorFormat) targets OutputFormat. +func postPickPipeline(dstFmt, colorFmt gpu.TextureFormat, inter, out *gpu.Pipeline) *gpu.Pipeline { + if dstFmt == colorFmt || out == nil { + return inter + } + return out +} + +// postCheckInputs rejects textures whose size differs from the pass size (texel steps and kernel radii are derived from it) and a destination that is also an input, which would read and write one texture in the same draw. +func postCheckInputs(w, h uint32, src, depth, dst *gpu.Texture) error { + for _, in := range [...]struct { + name string + tex *gpu.Texture + }{{"source color", src}, {"depth", depth}, {"destination", dst}} { + if in.tex == nil { + continue + } + if d := in.tex.Desc(); d.Width != w || d.Height != h { + return fmt.Errorf("%w: %s texture is %dx%d, pass is %dx%d", ErrInvalidPostProcess, in.name, d.Width, d.Height, w, h) + } + } + if dst != nil && (dst == src || dst == depth) { + return fmt.Errorf("%w: destination texture is also an input", ErrInvalidPostProcess) + } + return nil +} + func postCloseAll(closers ...interface{ Close() error }) error { var first error for _, c := range closers { @@ -1064,13 +1103,19 @@ func (p *BloomPass) Resize(dev *gpu.Device, width, height uint32) error { return p.allocTargets(dev) } -// Apply runs bright extraction, separable blur, and additive composite from srcColor -// into dstColor (nil writes to the swapchain using OutputFormat). +// Apply runs bright extraction, separable blur, and additive composite from srcColor into dstColor. A nil dstColor writes to the swapchain in OutputFormat, and a texture dstColor must be in ColorFormat or OutputFormat. Every texture must have the pass size and dstColor cannot also be an input; otherwise Apply returns an error wrapping [ErrInvalidPostProcess]. func (p *BloomPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, dstColor *gpu.Texture) error { - return p.applyWithOutput(dev, rec, srcColor, dstColor, dstColor == nil) + if p == nil || p.closed { + return fmt.Errorf("%w: bloom pass is not valid", ErrInvalidPostProcess) + } + dstFmt, err := postDestFormat(dstColor, p.colorFormat, p.outputFormat) + if err != nil { + return err + } + return p.applyTo(dev, rec, srcColor, dstColor, dstFmt) } -func (p *BloomPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, srcColor, dstColor *gpu.Texture, useOutputFormat bool) error { +func (p *BloomPass) applyTo(dev *gpu.Device, rec RenderPassRecorder, srcColor, dstColor *gpu.Texture, dstFmt gpu.TextureFormat) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } @@ -1086,6 +1131,9 @@ func (p *BloomPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, src if dstColor != nil && !dstColor.Valid() { return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) } + if err := postCheckInputs(p.width, p.height, srcColor, nil, dstColor); err != nil { + return err + } // Ensure half-res/full-res internal targets match current config. wantBW, wantBH := p.width, p.height if p.cfg.HalfRes { @@ -1168,10 +1216,7 @@ func (p *BloomPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, src } // 3. Additive composite -> dstColor (or swapchain). - pipe := p.compPipe - if useOutputFormat && p.compOutPipe != nil { - pipe = p.compOutPipe - } + pipe := postPickPipeline(dstFmt, p.colorFormat, p.compPipe, p.compOutPipe) drawPostFullscreen(rec, p.label+".composite", dstColor, pipe, p.cachedCompBG, p.vb) return nil } @@ -1730,6 +1775,9 @@ func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec RenderPassRecorder, depthTex * if depthTex == nil || !depthTex.Valid() { return nil, fmt.Errorf("%w: invalid depth texture", ErrInvalidPostProcess) } + if err := postCheckInputs(p.width, p.height, nil, depthTex, nil); err != nil { + return nil, err + } proj, invProj := p.cfg.resolveMatrices(p.width, p.height) kernel := buildSSAOKernel(p.cfg.SampleCount) @@ -1810,19 +1858,31 @@ func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec RenderPassRecorder, depthTex * return aoTex, nil } -// Apply computes SSAO from depthTex and multiplies it onto srcColor, writing to -// dstColor (nil writes to the swapchain using OutputFormat). +// Apply computes SSAO from depthTex and multiplies it onto srcColor, writing to dstColor. A nil dstColor writes to the swapchain in OutputFormat, and a texture dstColor must be in ColorFormat or OutputFormat. Every texture must have the pass size and dstColor cannot also be an input; otherwise Apply returns an error wrapping [ErrInvalidPostProcess]. func (p *SSAOPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { - return p.applyWithOutput(dev, rec, srcColor, depthTex, dstColor, dstColor == nil) + if p == nil || p.closed { + return fmt.Errorf("%w: ssao pass is not valid", ErrInvalidPostProcess) + } + dstFmt, err := postDestFormat(dstColor, p.colorFormat, p.outputFormat) + if err != nil { + return err + } + return p.applyTo(dev, rec, srcColor, depthTex, dstColor, dstFmt) } -func (p *SSAOPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { +func (p *SSAOPass) applyTo(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, dstFmt gpu.TextureFormat) error { + if p == nil || p.closed { + return fmt.Errorf("%w: ssao pass is not valid", ErrInvalidPostProcess) + } if srcColor == nil || !srcColor.Valid() { return fmt.Errorf("%w: invalid source color texture", ErrInvalidPostProcess) } if dstColor != nil && !dstColor.Valid() { return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) } + if err := postCheckInputs(p.width, p.height, srcColor, depthTex, dstColor); err != nil { + return err + } aoTex, err := p.ComputeAO(dev, rec, depthTex) if err != nil { return err @@ -1845,10 +1905,7 @@ func (p *SSAOPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, srcC p.cachedCompAO = aoTex p.cachedCompBG = bg } - pipe := p.compPipe - if useOutputFormat && p.compOutPipe != nil { - pipe = p.compOutPipe - } + pipe := postPickPipeline(dstFmt, p.colorFormat, p.compPipe, p.compOutPipe) drawPostFullscreen(rec, p.label+".composite", dstColor, pipe, p.cachedCompBG, p.vb) return nil } @@ -2278,13 +2335,19 @@ func (p *DepthOfFieldPass) Resize(dev *gpu.Device, width, height uint32) error { return p.allocTargets(dev) } -// Apply runs the CoC prepass and depth-aware disc bokeh gather from srcColor and -// depthTex into dstColor (nil writes to the swapchain using OutputFormat). +// Apply runs the CoC prepass and depth-aware disc bokeh gather from srcColor and depthTex into dstColor. A nil dstColor writes to the swapchain in OutputFormat, and a texture dstColor must be in ColorFormat or OutputFormat. Every texture must have the pass size and dstColor cannot also be an input; otherwise Apply returns an error wrapping [ErrInvalidPostProcess]. func (p *DepthOfFieldPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { - return p.applyWithOutput(dev, rec, srcColor, depthTex, dstColor, dstColor == nil) + if p == nil || p.closed { + return fmt.Errorf("%w: dof pass is not valid", ErrInvalidPostProcess) + } + dstFmt, err := postDestFormat(dstColor, p.colorFormat, p.outputFormat) + if err != nil { + return err + } + return p.applyTo(dev, rec, srcColor, depthTex, dstColor, dstFmt) } -func (p *DepthOfFieldPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, useOutputFormat bool) error { +func (p *DepthOfFieldPass) applyTo(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture, dstFmt gpu.TextureFormat) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } @@ -2303,6 +2366,9 @@ func (p *DepthOfFieldPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecord if dstColor != nil && !dstColor.Valid() { return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) } + if err := postCheckInputs(p.width, p.height, srcColor, depthTex, dstColor); err != nil { + return err + } var cocData [postDoFCoCUniformSize]byte postPutFloat32(cocData[:], 0, p.cfg.FocusDistance) @@ -2372,10 +2438,7 @@ func (p *DepthOfFieldPass) applyWithOutput(dev *gpu.Device, rec RenderPassRecord drawPostFullscreen(rec, p.label+".coc", p.cocRT.Color, p.cocPipe, p.cachedCoCBG, p.vb) // 2. Depth-aware disc bokeh gather -> dstColor (or swapchain). - pipe := p.bokehPipe - if useOutputFormat && p.bokehOutPipe != nil { - pipe = p.bokehOutPipe - } + pipe := postPickPipeline(dstFmt, p.colorFormat, p.bokehPipe, p.bokehOutPipe) drawPostFullscreen(rec, p.label+".bokeh", dstColor, pipe, p.cachedBokehBG, p.vb) return nil } @@ -2414,8 +2477,7 @@ type PostStack3DOptions struct { ColorFormat gpu.TextureFormat // DepthFormat is the scene render target's depth format. Defaults to [gpu.FormatDepth32Float] when zero. DepthFormat gpu.TextureFormat - // OutputFormat is the format of the final destination (swapchain or dstColor). - // Defaults to dev.SurfaceFormat() (or [gpu.FormatRGBA8Unorm]) when zero. + // OutputFormat is the swapchain format the final stage writes when dstColor is nil. A non-nil dstColor may be in OutputFormat or ColorFormat. Defaults to dev.SurfaceFormat() (or [gpu.FormatRGBA8Unorm]) when zero. OutputFormat gpu.TextureFormat // Retained opts offscreen targets, buffers, and samplers into automatic recreation after device loss. Retained bool @@ -2880,8 +2942,7 @@ func (s *PostStack3D) Resize(dev *gpu.Device, width, height uint32) error { return nil } -// ApplyScene executes all enabled passes on [PostStack3D.SceneTarget]'s color -// and depth attachments, writing the result into dstColor (nil targets the swapchain). +// ApplyScene executes all enabled passes on [PostStack3D.SceneTarget]'s color and depth attachments, writing the result into dstColor as [PostStack3D.Apply] does. func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec RenderPassRecorder, dstColor *gpu.Texture) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} @@ -2892,11 +2953,7 @@ func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec RenderPassRecorder, dstCol return s.Apply(dev, rec, s.sceneRT.Color, s.sceneRT.Depth, dstColor) } -// Apply executes all enabled passes in order (SSAO -> Depth of Field -> Bloom) -// on caller-provided srcColor and depthTex textures, writing the final result -// into dstColor (nil writes to the swapchain using OutputFormat). If depthTex -// is nil, depth-dependent passes (SSAO and Depth of Field) are skipped; if no -// pass runs, srcColor is blitted cleanly to dstColor. +// Apply executes all enabled passes in order (SSAO -> Depth of Field -> Bloom) on caller-provided srcColor and depthTex textures, writing the final result into dstColor. A nil dstColor writes to the swapchain in OutputFormat; a texture must have the stack size and either ColorFormat or OutputFormat. srcColor and depthTex must have the stack size too, and dstColor cannot be one of them; a mismatch returns an error wrapping [ErrInvalidPostProcess]. If depthTex is nil, depth-dependent passes (SSAO and Depth of Field) are skipped; if no pass runs, srcColor is blitted to dstColor. func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error { if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} @@ -2916,6 +2973,13 @@ func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, d if dstColor != nil && !dstColor.Valid() { return fmt.Errorf("%w: invalid destination texture", ErrInvalidPostProcess) } + if err := postCheckInputs(s.width, s.height, srcColor, depthTex, dstColor); err != nil { + return err + } + dstFmt, err := postDestFormat(dstColor, s.colorFormat, s.outputFormat) + if err != nil { + return err + } type stage uint8 const ( @@ -2938,8 +3002,6 @@ func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, d n++ } - useOutputFormat := dstColor == nil - if n == 0 { if s.cachedBlitSrc != srcColor || !s.cachedBlitBG.Valid() { bg, err := dev.CreateBindGroupDesc(s.cx, gpu.BindGroupDesc{ @@ -2957,10 +3019,7 @@ func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, d s.cachedBlitSrc = srcColor s.cachedBlitBG = bg } - pipe := s.blitPipe - if useOutputFormat && s.blitOutPipe != nil { - pipe = s.blitOutPipe - } + pipe := postPickPipeline(dstFmt, s.colorFormat, s.blitPipe, s.blitOutPipe) drawPostFullscreen(rec, s.label+".blit", dstColor, pipe, s.cachedBlitBG, s.vb) return nil } @@ -2970,10 +3029,10 @@ func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, d for i := range n { last := i == n-1 var target *gpu.Texture - targetUsesOutput := false + targetFmt := s.colorFormat if last { target = dstColor - targetUsesOutput = useOutputFormat + targetFmt = dstFmt } else { if pingNext { target = s.pingRT.Color @@ -2986,11 +3045,11 @@ func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, d var err error switch active[i] { case stageSSAO: - err = s.ssao.applyWithOutput(dev, rec, cur, depthTex, target, targetUsesOutput) + err = s.ssao.applyTo(dev, rec, cur, depthTex, target, targetFmt) case stageDoF: - err = s.dof.applyWithOutput(dev, rec, cur, depthTex, target, targetUsesOutput) + err = s.dof.applyTo(dev, rec, cur, depthTex, target, targetFmt) case stageBloom: - err = s.bloom.applyWithOutput(dev, rec, cur, target, targetUsesOutput) + err = s.bloom.applyTo(dev, rec, cur, target, targetFmt) } if err != nil { return err From 05e9da513f1e2b3f9dcf6f5c86101f832cd424be Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:14:00 +0900 Subject: [PATCH 4/9] fix(render3d): accept only filterable four-channel post-processing color formats --- packages/game/render3d/post3d.go | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/game/render3d/post3d.go b/packages/game/render3d/post3d.go index acbcd4dd..a610eace 100644 --- a/packages/game/render3d/post3d.go +++ b/packages/game/render3d/post3d.go @@ -526,14 +526,15 @@ func postPutMat4(dst []byte, off int, m math3d.Mat4) { } } +// postResolveColorFormat accepts only the intermediate formats every pass can render to and filter-sample on every backend: four filterable channels, because Depth of Field stores its Circle of Confusion in alpha. Integer formats do not match texture_2d, RGBA32Float is not filterable on WebGL 2, GLES 3.0 or baseline WebGPU, and R8/RG8/RG11B10 have no alpha. func postResolveColorFormat(f gpu.TextureFormat) (gpu.TextureFormat, error) { - if f == gpu.FormatUndefined { + switch f { + case gpu.FormatUndefined: return gpu.FormatRGBA16Float, nil + case gpu.FormatRGBA16Float, gpu.FormatRGBA8Unorm, gpu.FormatRGBA8UnormSRGB, gpu.FormatBGRA8Unorm, gpu.FormatBGRA8UnormSRGB: + return f, nil } - if f.IsDepthStencil() || f.IsCompressed() { - return gpu.FormatUndefined, fmt.Errorf("%w: unsupported color target format %s", ErrInvalidPostProcess, f) - } - return f, nil + return gpu.FormatUndefined, fmt.Errorf("%w: unsupported color format %s (want RGBA16Float, RGBA8Unorm, RGBA8UnormSRGB, BGRA8Unorm or BGRA8UnormSRGB)", ErrInvalidPostProcess, f) } func postResolveOutputFormat(dev *gpu.Device, f gpu.TextureFormat) (gpu.TextureFormat, error) { @@ -727,7 +728,7 @@ type BloomPassOptions struct { Label string Width uint32 Height uint32 - ColorFormat gpu.TextureFormat // internal blur target format; defaults to FormatRGBA16Float + ColorFormat gpu.TextureFormat // internal blur target format: RGBA16Float (the default), RGBA8Unorm, RGBA8UnormSRGB, BGRA8Unorm or BGRA8UnormSRGB OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm Retained bool Config BloomConfig @@ -1409,7 +1410,7 @@ type SSAOPassOptions struct { Label string Width uint32 Height uint32 - ColorFormat gpu.TextureFormat // intermediate color format; defaults to FormatRGBA16Float + ColorFormat gpu.TextureFormat // intermediate color format: RGBA16Float (the default), RGBA8Unorm, RGBA8UnormSRGB, BGRA8Unorm or BGRA8UnormSRGB OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm Retained bool Config SSAOConfig @@ -2035,7 +2036,7 @@ type DepthOfFieldPassOptions struct { Label string Width uint32 Height uint32 - ColorFormat gpu.TextureFormat // intermediate color/CoC format; defaults to FormatRGBA16Float + ColorFormat gpu.TextureFormat // intermediate color/CoC format: RGBA16Float (the default), RGBA8Unorm, RGBA8UnormSRGB, BGRA8Unorm or BGRA8UnormSRGB OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm Retained bool Config DepthOfFieldConfig @@ -2472,8 +2473,7 @@ type PostStack3DOptions struct { // Width and Height of the offscreen 3D scene and post-processing targets (must be > 0). Width uint32 Height uint32 - // ColorFormat is the scene and intermediate ping-pong color format. - // Defaults to [gpu.FormatRGBA16Float] when zero, preserving HDR highlights for Bloom. + // ColorFormat is the scene and intermediate ping-pong color format: [gpu.FormatRGBA16Float] (the default, preserving HDR highlights for Bloom), [gpu.FormatRGBA8Unorm], [gpu.FormatRGBA8UnormSRGB], [gpu.FormatBGRA8Unorm] or [gpu.FormatBGRA8UnormSRGB]. Any other format returns an error wrapping [ErrInvalidPostProcess]. ColorFormat gpu.TextureFormat // DepthFormat is the scene render target's depth format. Defaults to [gpu.FormatDepth32Float] when zero. DepthFormat gpu.TextureFormat From 5c5cb0ca178a9755248c25716a4cfcb16e6c8602 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:14:41 +0900 Subject: [PATCH 5/9] fix(render3d): linearize Depth of Field depth with the projection matrix and add PostStack3D.SetCamera --- packages/game/render3d/post3d.go | 69 +++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 18 deletions(-) diff --git a/packages/game/render3d/post3d.go b/packages/game/render3d/post3d.go index a610eace..f33032d5 100644 --- a/packages/game/render3d/post3d.go +++ b/packages/game/render3d/post3d.go @@ -1260,10 +1260,10 @@ type SSAOConfig struct { BlurRadius int // DepthThreshold is the view-space depth tolerance for bilateral blur edge preservation (> 0). Default: 0.2. DepthThreshold float32 - // Near and Far are fallback perspective clip planes used only when ProjMatrix is zero. + // Near and Far are fallback perspective clip planes used only when ProjMatrix is zero; the fallback projection also assumes a 60-degree vertical field of view and the pass's aspect ratio, so set ProjMatrix whenever the camera differs from that. Near float32 Far float32 - // ProjMatrix is the camera's [0, 1] NDC depth projection matrix (e.g. cam.ProjMatrix()). + // ProjMatrix is the camera's [0, 1] NDC depth projection matrix (e.g. cam.ProjMatrix()). It is captured when the config is set, so refresh it with [SSAOPass.SetConfig] or [PostStack3D.SetCamera] whenever the projection changes, such as after a resize changes the camera's aspect ratio. ProjMatrix math3d.Mat4 // InvProjMatrix optionally supplies ProjMatrix.Inverse(); when zero, it is computed from ProjMatrix. InvProjMatrix math3d.Mat4 @@ -1284,18 +1284,30 @@ func DefaultSSAOConfig() SSAOConfig { } } -// SSAOConfigFromCamera initializes an [SSAOConfig] using cam's projection matrix -// and clip planes combined with [DefaultSSAOConfig] quality settings. +// SSAOConfigFromCamera initializes an [SSAOConfig] using cam's projection matrix and the clip planes that matrix uses, combined with [DefaultSSAOConfig] quality settings. func SSAOConfigFromCamera(cam *scene3d.Camera) SSAOConfig { cfg := DefaultSSAOConfig() if cam != nil { cfg.ProjMatrix = cam.ProjMatrix() - cfg.Near = cam.Projection.Near - cfg.Far = cam.Projection.Far + if near, far, ortho := postClipPlanes(cfg.ProjMatrix); !ortho { + cfg.Near, cfg.Far = near, far + } } return cfg } +// postClipPlanes recovers the near and far planes and the projection kind from a [0, 1]-depth projection built by [math3d.Perspective] or [math3d.Ortho]. Reading them from the matrix, not from [scene3d.Projection]'s fields, keeps them equal to what the depth buffer holds when the projection fills in defaults for zero or out-of-range fields. +func postClipPlanes(m math3d.Mat4) (near, far float32, ortho bool) { + a, b := m[10], m[14] + if m[11] == 0 && m[15] == 1 { + // Orthographic: a = -1/(far-near), b = -near/(far-near). + near = b / a + return near, near - 1/a, true + } + // Perspective: a = -far/(far-near), b = -far*near/(far-near). + return b / a, b / (a + 1), false +} + // Validate checks that every field of c is finite and within its valid range. // Every error wraps [ErrInvalidPostProcess]. func (c SSAOConfig) Validate() error { @@ -1946,7 +1958,7 @@ type DepthOfFieldConfig struct { // MaxBlurRadius is the maximum bokeh disc radius in pixels at CoC = 1 (>= 0). // 0 leaves the scene unchanged. Default: 6.0. MaxBlurRadius float32 - // Near and Far are the camera clip planes used to linearize [0, 1] depth values (0 < Near < Far). + // Near and Far are the camera clip planes used to linearize [0, 1] depth values: Near < Far, and Near > 0 for a perspective projection. They must match the projection that wrote the depth buffer; [DepthOfFieldConfigFromCamera] and [PostStack3D.SetCamera] read them from the camera's projection matrix. Near float32 Far float32 // Orthographic selects linear orthographic depth reconstruction instead of perspective. @@ -1964,21 +1976,14 @@ func DefaultDepthOfFieldConfig() DepthOfFieldConfig { } } -// DepthOfFieldConfigFromCamera initializes a [DepthOfFieldConfig] with cam's clip -// planes and projection kind. +// DepthOfFieldConfigFromCamera initializes a [DepthOfFieldConfig] with the clip planes and projection kind of cam's projection matrix, so a projection whose fields [scene3d.Projection.Matrix] fills in with defaults still linearizes depth correctly. func DepthOfFieldConfigFromCamera(cam *scene3d.Camera, focusDistance, focusRange, maxBlurRadius float32) DepthOfFieldConfig { cfg := DefaultDepthOfFieldConfig() cfg.FocusDistance = focusDistance cfg.FocusRange = focusRange cfg.MaxBlurRadius = maxBlurRadius if cam != nil { - if cam.Projection.Near > 0 { - cfg.Near = cam.Projection.Near - } - if cam.Projection.Far > cfg.Near { - cfg.Far = cam.Projection.Far - } - cfg.Orthographic = cam.Projection.Kind == scene3d.ProjectionOrthographic + cfg.Near, cfg.Far, cfg.Orthographic = postClipPlanes(cam.ProjMatrix()) } return cfg } @@ -1995,8 +2000,11 @@ func (c DepthOfFieldConfig) Validate() error { if !finite(c.MaxBlurRadius) || c.MaxBlurRadius < 0 { return fmt.Errorf("%w: dof MaxBlurRadius %v must be finite and >= 0", ErrInvalidPostProcess, c.MaxBlurRadius) } - if !finite(c.Near) || !finite(c.Far) || c.Near <= 0 || c.Far <= c.Near { - return fmt.Errorf("%w: dof requires 0 < Near < Far (got Near=%v, Far=%v)", ErrInvalidPostProcess, c.Near, c.Far) + if !finite(c.Near) || !finite(c.Far) || c.Far <= c.Near { + return fmt.Errorf("%w: dof requires Near < Far (got Near=%v, Far=%v)", ErrInvalidPostProcess, c.Near, c.Far) + } + if !c.Orthographic && c.Near <= 0 { + return fmt.Errorf("%w: perspective dof requires Near > 0 (got %v)", ErrInvalidPostProcess, c.Near) } return nil } @@ -2836,6 +2844,31 @@ func (s *PostStack3D) SetBloom(enabled bool, cfg BloomConfig) error { return nil } +// SetCamera refreshes the projection SSAO reconstructs view-space positions with and the clip planes Depth of Field linearizes depth with from cam's projection matrix, keeping every other setting. Call it whenever the camera's projection changes, such as after a resize changes its aspect ratio or a zoom changes its field of view. +func (s *PostStack3D) SetCamera(cam *scene3d.Camera) error { + if s == nil || s.closed { + return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) + } + if cam == nil { + return fmt.Errorf("%w: nil camera", ErrInvalidPostProcess) + } + proj := cam.ProjMatrix() + ssao := s.ssao.Config() + ssao.ProjMatrix = proj + ssao.InvProjMatrix = math3d.Mat4{} + dof := s.dof.Config() + dof.Near, dof.Far, dof.Orthographic = postClipPlanes(proj) + if err := ssao.Validate(); err != nil { + return err + } + if err := dof.Validate(); err != nil { + return err + } + s.ssao.cfg = ssao.normalized() + s.dof.cfg = dof + return nil +} + // Width returns the stack's offscreen target width in pixels. func (s *PostStack3D) Width() uint32 { if s == nil { From 666cb5c774bcb1bc07bf31b6eab758f6387058a5 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:14:48 +0900 Subject: [PATCH 6/9] fix(render3d): let PostStack3D stage toggles keep the current config --- packages/game/render3d/post3d.go | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/game/render3d/post3d.go b/packages/game/render3d/post3d.go index f33032d5..3ab63e8f 100644 --- a/packages/game/render3d/post3d.go +++ b/packages/game/render3d/post3d.go @@ -2808,37 +2808,43 @@ func (s *PostStack3D) Bloom() *BloomPass { return s.bloom } -// SetSSAO enables or disables SSAO and updates its configuration. +// SetSSAO enables or disables SSAO and updates its configuration. A zero cfg keeps the current configuration, so SetSSAO(false, SSAOConfig{}) only turns the stage off. func (s *PostStack3D) SetSSAO(enabled bool, cfg SSAOConfig) error { if s == nil || s.closed { return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) } - if err := s.ssao.SetConfig(cfg); err != nil { - return err + if cfg != (SSAOConfig{}) { + if err := s.ssao.SetConfig(cfg); err != nil { + return err + } } s.enableSSAO = enabled return nil } -// SetDepthOfField enables or disables Depth of Field and updates its configuration. +// SetDepthOfField enables or disables Depth of Field and updates its configuration. A zero cfg keeps the current configuration, so SetDepthOfField(false, DepthOfFieldConfig{}) only turns the stage off. func (s *PostStack3D) SetDepthOfField(enabled bool, cfg DepthOfFieldConfig) error { if s == nil || s.closed { return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) } - if err := s.dof.SetConfig(cfg); err != nil { - return err + if cfg != (DepthOfFieldConfig{}) { + if err := s.dof.SetConfig(cfg); err != nil { + return err + } } s.enableDoF = enabled return nil } -// SetBloom enables or disables Bloom and updates its configuration. +// SetBloom enables or disables Bloom and updates its configuration. A zero cfg keeps the current configuration, so SetBloom(false, BloomConfig{}) only turns the stage off. func (s *PostStack3D) SetBloom(enabled bool, cfg BloomConfig) error { if s == nil || s.closed { return fmt.Errorf("%w: post stack is not valid", ErrInvalidPostProcess) } - if err := s.bloom.SetConfig(cfg); err != nil { - return err + if cfg != (BloomConfig{}) { + if err := s.bloom.SetConfig(cfg); err != nil { + return err + } } s.enableBloom = enabled return nil From c6b34c856c409166afe5de2e83e466b3cb9b2e9b Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:15:08 +0900 Subject: [PATCH 7/9] style(render3d): put each post-processing comment paragraph on one line --- packages/game/render3d/post3d.go | 77 ++++++++------------------- packages/game/render3d/post3d_test.go | 12 ++--- 2 files changed, 27 insertions(+), 62 deletions(-) diff --git a/packages/game/render3d/post3d.go b/packages/game/render3d/post3d.go index 3ab63e8f..1e8d9f0a 100644 --- a/packages/game/render3d/post3d.go +++ b/packages/game/render3d/post3d.go @@ -13,10 +13,7 @@ import ( "github.com/nsgo-dev/nsgo/gpu" ) -// ErrInvalidPostProcess is wrapped by every validation error returned by 3D -// post-processing configurations and constructors ([BloomConfig.Validate], -// [SSAOConfig.Validate], [DepthOfFieldConfig.Validate], [NewBloomPass], -// [NewSSAOPass], [NewDepthOfFieldPass], and [NewPostStack3D]). +// ErrInvalidPostProcess is wrapped by every validation error returned by 3D post-processing configurations and constructors ([BloomConfig.Validate], [SSAOConfig.Validate], [DepthOfFieldConfig.Validate], [NewBloomPass], [NewSSAOPass], [NewDepthOfFieldPass], and [NewPostStack3D]). var ErrInvalidPostProcess = errors.New("render3d: invalid post-processing configuration") const ( @@ -35,8 +32,7 @@ const ( postDoFBokehUniformSize = 16 + postDoFTapCount*16 // 304 bytes ) -// Shared fullscreen triangle vertex stage prepended to every post-processing WGSL module. -// Z is 0.0 (never 1.0) so fullscreen triangles never clip at the far depth plane. +// Shared fullscreen triangle vertex stage prepended to every post-processing WGSL module. Z is 0.0 (never 1.0) so fullscreen triangles never clip at the far depth plane. const postFullscreenVertexWGSL = ` struct PostVertexIn { @location(0) pos: vec2, @@ -664,22 +660,17 @@ func postCloseAll(closers ...interface{ Close() error }) error { // BloomConfig tunes the 3D bloom post-processing pass. type BloomConfig struct { - // Threshold is the minimum max-channel brightness that contributes to bloom (>= 0). - // Values above 1.0 target HDR emissive pixels in floating-point color targets. + // Threshold is the minimum max-channel brightness that contributes to bloom (>= 0). Values above 1.0 target HDR emissive pixels in floating-point color targets. Threshold float32 - // SoftKnee controls the smooth transition width around Threshold in [0, 1]. - // 0 produces a hard cutoff; 0.5 produces a gradual shoulder. + // SoftKnee controls the smooth transition width around Threshold in [0, 1]. 0 produces a hard cutoff; 0.5 produces a gradual shoulder. SoftKnee float32 - // Intensity scales the blurred glow added onto the scene color (>= 0). - // 0 leaves the scene unchanged. + // Intensity scales the blurred glow added onto the scene color (>= 0). 0 leaves the scene unchanged. Intensity float32 // Radius scales the separable Gaussian blur tap stride in texels (>= 0). Radius float32 - // BlurPasses is the number of horizontal+vertical separable Gaussian iterations in [1, 8]. - // 0 defaults to 2. + // BlurPasses is the number of horizontal+vertical separable Gaussian iterations in [1, 8]. 0 defaults to 2. BlurPasses int - // HalfRes runs bright extraction and Gaussian blur at half resolution (max(1, w/2) x max(1, h/2)) - // for wider soft halos at a quarter of the pixel cost. + // HalfRes runs bright extraction and Gaussian blur at half resolution (max(1, w/2) x max(1, h/2)) for wider soft halos at a quarter of the pixel cost. HalfRes bool } @@ -695,8 +686,7 @@ func DefaultBloomConfig() BloomConfig { } } -// Validate checks that every field of c is finite and within its valid range. -// Every error wraps [ErrInvalidPostProcess]. +// Validate checks that every field of c is finite and within its valid range. Every error wraps [ErrInvalidPostProcess]. func (c BloomConfig) Validate() error { if !finite(c.Threshold) || c.Threshold < 0 { return fmt.Errorf("%w: bloom Threshold %v must be finite and >= 0", ErrInvalidPostProcess, c.Threshold) @@ -734,9 +724,7 @@ type BloomPassOptions struct { Config BloomConfig } -// BloomPass executes bright-pixel extraction, separable 9-tap Gaussian blur -// across offscreen ping-pong render targets, and additive composition onto a -// destination target or swapchain. +// BloomPass executes bright-pixel extraction, separable 9-tap Gaussian blur across offscreen ping-pong render targets, and additive composition onto a destination target or swapchain. type BloomPass struct { cx *core.Scope label string @@ -1015,8 +1003,7 @@ func (p *BloomPass) Config() BloomConfig { return p.cfg } -// SetConfig validates and updates the bloom parameters. Changing [BloomConfig.HalfRes] -// takes effect on the next [BloomPass.Resize] or [BloomPass.Apply]. +// SetConfig validates and updates the bloom parameters. Changing [BloomConfig.HalfRes] takes effect on the next [BloomPass.Resize] or [BloomPass.Apply]. func (p *BloomPass) SetConfig(cfg BloomConfig) error { if p == nil || p.closed { return fmt.Errorf("%w: bloom pass is not valid", ErrInvalidPostProcess) @@ -1308,8 +1295,7 @@ func postClipPlanes(m math3d.Mat4) (near, far float32, ortho bool) { return b / a, b / (a + 1), false } -// Validate checks that every field of c is finite and within its valid range. -// Every error wraps [ErrInvalidPostProcess]. +// Validate checks that every field of c is finite and within its valid range. Every error wraps [ErrInvalidPostProcess]. func (c SSAOConfig) Validate() error { if !finite(c.Radius) || c.Radius <= 0 { return fmt.Errorf("%w: ssao Radius %v must be finite and > 0", ErrInvalidPostProcess, c.Radius) @@ -1385,8 +1371,7 @@ func (c SSAOConfig) resolveMatrices(w, h uint32) (proj, invProj math3d.Mat4) { return proj, invProj } -// buildSSAOKernel generates a deterministic low-discrepancy hemisphere sample kernel -// in tangent space (+Z along surface normal) with samples concentrated closer to the origin. +// buildSSAOKernel generates a deterministic low-discrepancy hemisphere sample kernel in tangent space (+Z along surface normal) with samples concentrated closer to the origin. func buildSSAOKernel(count int) [postMaxSSAOSamples][4]float32 { var out [postMaxSSAOSamples][4]float32 if count < 1 { @@ -1428,9 +1413,7 @@ type SSAOPassOptions struct { Config SSAOConfig } -// SSAOPass computes screen-space ambient occlusion from a 3D depth texture, -// optionally filters it with a depth-aware bilateral blur, and multiplies the -// resulting occlusion factor into a scene color texture. +// SSAOPass computes screen-space ambient occlusion from a 3D depth texture, optionally filters it with a depth-aware bilateral blur, and multiplies the resulting occlusion factor into a scene color texture. type SSAOPass struct { cx *core.Scope label string @@ -1721,8 +1704,7 @@ func (p *SSAOPass) Height() uint32 { return p.height } -// AOTexture returns the most recently computed ambient occlusion texture -// (blurred when BlurRadius > 0, raw otherwise). +// AOTexture returns the most recently computed ambient occlusion texture (blurred when BlurRadius > 0, raw otherwise). func (p *SSAOPass) AOTexture() *gpu.Texture { if p == nil || p.closed { return nil @@ -1773,8 +1755,7 @@ func (p *SSAOPass) Resize(dev *gpu.Device, width, height uint32) error { return p.allocTargets(dev) } -// ComputeAO evaluates the SSAO hemisphere pass (and optional bilateral blur) from -// depthTex and returns the resulting AO texture for inspection or custom compositing. +// ComputeAO evaluates the SSAO hemisphere pass (and optional bilateral blur) from depthTex and returns the resulting AO texture for inspection or custom compositing. func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec RenderPassRecorder, depthTex *gpu.Texture) (*gpu.Texture, error) { if dev == nil { return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} @@ -1952,11 +1933,9 @@ func (p *SSAOPass) Close() error { type DepthOfFieldConfig struct { // FocusDistance is the view-space distance from the camera that renders sharpest (> 0). Default: 5.0. FocusDistance float32 - // FocusRange is the half-width around FocusDistance over which the Circle of Confusion - // ramps from 0 (in focus) to 1 (maximum blur). Must be > 0. Default: 2.0. + // FocusRange is the half-width around FocusDistance over which the Circle of Confusion ramps from 0 (in focus) to 1 (maximum blur). Must be > 0. Default: 2.0. FocusRange float32 - // MaxBlurRadius is the maximum bokeh disc radius in pixels at CoC = 1 (>= 0). - // 0 leaves the scene unchanged. Default: 6.0. + // MaxBlurRadius is the maximum bokeh disc radius in pixels at CoC = 1 (>= 0). 0 leaves the scene unchanged. Default: 6.0. MaxBlurRadius float32 // Near and Far are the camera clip planes used to linearize [0, 1] depth values: Near < Far, and Near > 0 for a perspective projection. They must match the projection that wrote the depth buffer; [DepthOfFieldConfigFromCamera] and [PostStack3D.SetCamera] read them from the camera's projection matrix. Near float32 @@ -1988,8 +1967,7 @@ func DepthOfFieldConfigFromCamera(cam *scene3d.Camera, focusDistance, focusRange return cfg } -// Validate checks that every field of c is finite and within its valid range. -// Every error wraps [ErrInvalidPostProcess]. +// Validate checks that every field of c is finite and within its valid range. Every error wraps [ErrInvalidPostProcess]. func (c DepthOfFieldConfig) Validate() error { if !finite(c.FocusDistance) || c.FocusDistance <= 0 { return fmt.Errorf("%w: dof FocusDistance %v must be finite and > 0", ErrInvalidPostProcess, c.FocusDistance) @@ -2009,8 +1987,7 @@ func (c DepthOfFieldConfig) Validate() error { return nil } -// buildDoFDiscTaps returns 18 deterministic 2-ring disc bokeh offsets: -// 6 taps on the inner ring (r = 0.45) and 12 taps on the outer ring (r = 0.95). +// buildDoFDiscTaps returns 18 deterministic 2-ring disc bokeh offsets: 6 taps on the inner ring (r = 0.45) and 12 taps on the outer ring (r = 0.95). func buildDoFDiscTaps() [postDoFTapCount][4]float32 { var taps [postDoFTapCount][4]float32 idx := 0 @@ -2050,8 +2027,7 @@ type DepthOfFieldPassOptions struct { Config DepthOfFieldConfig } -// DepthOfFieldPass computes per-pixel signed Circle of Confusion from depth and -// gathers a depth-aware disc bokeh blur that keeps in-focus silhouettes sharp. +// DepthOfFieldPass computes per-pixel signed Circle of Confusion from depth and gathers a depth-aware disc bokeh blur that keeps in-focus silhouettes sharp. type DepthOfFieldPass struct { cx *core.Scope label string @@ -2501,15 +2477,9 @@ type PostStack3DOptions struct { Bloom BloomConfig } -// PostStack3D composes SSAO, Depth of Field, and Bloom over an offscreen 3D -// color+depth render target, routing enabled passes cleanly through ping-pong -// offscreen targets and writing the final result to the swapchain or a chosen -// destination texture. +// PostStack3D composes SSAO, Depth of Field, and Bloom over an offscreen 3D color+depth render target, routing enabled passes cleanly through ping-pong offscreen targets and writing the final result to the swapchain or a chosen destination texture. // -// Execution order is fixed to SSAO -> Depth of Field -> Bloom so ambient -// occlusion darkens crevices before bokeh blurring and highlights bloom after -// optical blur. All passes use portable WGSL compatible with both full and -// compute-free (WebGL 2 / OpenGL ES 3.0) NSGo GPU profiles. +// Execution order is fixed to SSAO -> Depth of Field -> Bloom so ambient occlusion darkens crevices before bokeh blurring and highlights bloom after optical blur. All passes use portable WGSL compatible with both full and compute-free (WebGL 2 / OpenGL ES 3.0) NSGo GPU profiles. type PostStack3D struct { cx *core.Scope label string @@ -2761,8 +2731,7 @@ func (s *PostStack3D) SceneTarget() *gpu.RenderTarget { return s.sceneRT } -// BeginScenePass begins a render pass targeting [PostStack3D.SceneTarget], clearing -// color to clearColor and depth to 1.0 and storing both attachments for post-processing. +// BeginScenePass begins a render pass targeting [PostStack3D.SceneTarget], clearing color to clearColor and depth to 1.0 and storing both attachments for post-processing. func (s *PostStack3D) BeginScenePass(rec RenderPassRecorder, clearColor core.Color) *gpu.RenderPass { if s == nil || s.closed || rec == nil || !s.sceneRT.Valid() { return nil diff --git a/packages/game/render3d/post3d_test.go b/packages/game/render3d/post3d_test.go index 0f6103ae..22e420d4 100644 --- a/packages/game/render3d/post3d_test.go +++ b/packages/game/render3d/post3d_test.go @@ -91,8 +91,7 @@ func post3dAppendBox(dst []float32, center, half math3d.Vec3, col [3]float32, mo return dst } -// post3dAppendCheckerPanel appends a front-facing (+Z) grid of alternating high-contrast tiles, -// ideal for measuring spatial sharpness vs Depth of Field blur. +// post3dAppendCheckerPanel appends a front-facing (+Z) grid of alternating high-contrast tiles, ideal for measuring spatial sharpness vs Depth of Field blur. func post3dAppendCheckerPanel(dst []float32, center math3d.Vec3, width, height float32, cols, rows int, colA, colB [3]float32) []float32 { n := math3d.Vec3{Z: 1} dx := width / float32(cols) @@ -238,8 +237,7 @@ func post3dRegionLumaMean(img *image.RGBA, x0, y0, x1, y1 int) float64 { return sum / float64(n) } -// post3dRegionContrast measures mean horizontal + vertical adjacent-pixel luminance gradient -// inside [x0, x1) x [y0, y1), which drops cleanly when a checkerboard blurs. +// post3dRegionContrast measures mean horizontal + vertical adjacent-pixel luminance gradient inside [x0, x1) x [y0, y1), which drops cleanly when a checkerboard blurs. func post3dRegionContrast(img *image.RGBA, x0, y0, x1, y1 int) float64 { var sum float64 n := 0 @@ -562,8 +560,7 @@ func TestPost3DDepthOfFieldMatchesReference(t *testing.T) { sp := newPost3dScenePipeline(t, nil, dev, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) defer func() { _ = sp.cam.Close() }() - // Three high-contrast checkerboard panels placed at near (dist=2.2), focus (dist=5.0), and far (dist=10.5), - // scaled proportionally to their distance so all three occupy similar screen regions side by side. + // Three high-contrast checkerboard panels placed at near (dist=2.2), focus (dist=5.0), and far (dist=10.5), scaled proportionally to their distance so all three occupy similar screen regions side by side. cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Z: 0}, math3d.DegToRad(50), float32(post3dWidth)/float32(post3dHeight), 0.5, 25.0) cam.LookAt(math3d.Vec3{Z: -5}, math3d.Vec3Up()) @@ -784,8 +781,7 @@ func TestPost3DStackCombinedResizeAndProfiles(t *testing.T) { t.Errorf("render after resize round-trip differed by %d", diff) } - // 2. Run inside mounted headless nsgotest gpu.View on both full and NoGPUCompute (WebGL 2 / GLES 3.0) profiles, - // including Retained device-loss recovery. + // 2. Run inside mounted headless nsgotest gpu.View on both full and NoGPUCompute (WebGL 2 / GLES 3.0) profiles, including Retained device-loss recovery. for _, tc := range []struct { name string opts []nsgotest.Option From 2c530164dbcd225c45f59a4fc98ecb1e5ad4045c Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:18:11 +0900 Subject: [PATCH 8/9] test(render3d): cover post-processing destinations, size checks, formats, toggles and orthographic DoF --- packages/game/render3d/post3d_edge_test.go | 553 +++++++++++++++++++++ packages/game/render3d/post3d_test.go | 50 +- 2 files changed, 557 insertions(+), 46 deletions(-) create mode 100644 packages/game/render3d/post3d_edge_test.go diff --git a/packages/game/render3d/post3d_edge_test.go b/packages/game/render3d/post3d_edge_test.go new file mode 100644 index 00000000..2e8f31aa --- /dev/null +++ b/packages/game/render3d/post3d_edge_test.go @@ -0,0 +1,553 @@ +package render3d_test + +import ( + "errors" + "image" + "math" + "testing" + + "github.com/nsgo-dev/game/packages/game/math3d" + "github.com/nsgo-dev/game/packages/game/render3d" + "github.com/nsgo-dev/game/packages/game/scene3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" +) + +const ( + post3dEdgeWidth = 64 + post3dEdgeHeight = 48 +) + +// post3dEdgeScene is a small lit scene (floor, matte block, HDR emissive box) drawn into a caller-chosen color+depth target. +type post3dEdgeScene struct { + sp *post3dScenePipeline + vb *gpu.Buffer + count uint32 + cam *scene3d.Camera +} + +func newPost3dEdgeScene(t *testing.T, dev *gpu.Device, cam *scene3d.Camera) *post3dEdgeScene { + t.Helper() + sp := newPost3dScenePipeline(t, nil, dev, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + t.Cleanup(func() { _ = sp.cam.Close() }) + var verts []float32 + verts = post3dAppendQuad(verts, + math3d.Vec3{X: -6, Y: 0, Z: 6}, math3d.Vec3{X: 6, Y: 0, Z: 6}, + math3d.Vec3{X: 6, Y: 0, Z: -8}, math3d.Vec3{X: -6, Y: 0, Z: -8}, + math3d.Vec3Up(), [3]float32{0.55, 0.57, 0.6}, 0.5) + verts = post3dAppendBox(verts, math3d.Vec3{X: -0.4, Y: 0.5, Z: -0.2}, math3d.Vec3{X: 0.5, Y: 0.5, Z: 0.5}, [3]float32{0.75, 0.72, 0.68}, 0.5) + verts = post3dAppendBox(verts, math3d.Vec3{X: 1.0, Y: 0.4, Z: -0.6}, math3d.Vec3{X: 0.3, Y: 0.4, Z: 0.3}, [3]float32{2.5, 1.4, 0.4}, 1.0) + vb, err := dev.CreateBuffer(nil, gpu.BufferDesc{Label: "post3d.edge.verts", Usage: gpu.UsageVertex, Data: post3dPackFloats(verts)}) + if err != nil { + t.Fatalf("CreateBuffer: %v", err) + } + t.Cleanup(func() { _ = vb.Close() }) + return &post3dEdgeScene{sp: sp, vb: vb, count: uint32(len(verts) / 10), cam: cam} +} + +func (s *post3dEdgeScene) draw(enc *gpu.Encoder, color, depth *gpu.Texture) { + s.sp.cam.WriteCamera(s.cam) + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{Texture: color, LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore, ClearColor: core.RGB(0x0c1018)}}, + DepthStencil: &gpu.DepthStencilAttachment{Texture: depth, DepthLoadOp: gpu.LoadClear, DepthStoreOp: gpu.StoreStore, ClearDepth: 1}, + }) + s.sp.draw(pass, s.vb, s.count) + pass.End() +} + +func newPost3dEdgeTarget(t *testing.T, dev *gpu.Device, w, h uint32, color, depth gpu.TextureFormat) *gpu.RenderTarget { + t.Helper() + rt, err := dev.CreateRenderTarget(nil, gpu.RenderTargetDesc{Width: w, Height: h, ColorFormat: color, DepthFormat: depth}) + if err != nil { + t.Fatalf("CreateRenderTarget %s: %v", color, err) + } + t.Cleanup(func() { _ = rt.Close() }) + return rt +} + +func post3dEdgeSubmit(t *testing.T, sr *gpu.SoftwareRenderer, enc *gpu.Encoder) { + t.Helper() + sr.Device().Submit(enc.Finish()) + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } +} + +func post3dEdgeCamera() *scene3d.Camera { + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 1.6, Y: 1.8, Z: 4.2}, math3d.DegToRad(50), float32(post3dEdgeWidth)/float32(post3dEdgeHeight), 0.2, 40) + cam.LookAt(math3d.Vec3{X: 0, Y: 0.4, Z: -0.4}, math3d.Vec3Up()) + return cam +} + +// A caller-owned destination texture is written with the pipeline built for its own format, so a stack whose ColorFormat is RGBA16Float renders into an RGBA8 texture exactly as it renders to an RGBA8 swapchain, and a destination in neither format is refused. +func TestPost3DApplyIntoCallerTexture(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dEdgeWidth, post3dEdgeHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + cam := post3dEdgeCamera() + scene := newPost3dEdgeScene(t, dev, cam) + + stack, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{ + Width: post3dEdgeWidth, + Height: post3dEdgeHeight, + ColorFormat: gpu.FormatRGBA16Float, + OutputFormat: gpu.FormatRGBA8Unorm, + EnableSSAO: true, + SSAO: render3d.SSAOConfigFromCamera(cam), + EnableDoF: true, + DoF: render3d.DepthOfFieldConfigFromCamera(cam, 4.5, 2, 3), + EnableBloom: true, + Bloom: render3d.DefaultBloomConfig(), + }) + if err != nil { + t.Fatalf("NewPostStack3D: %v", err) + } + defer func() { _ = stack.Close() }() + sceneRT := stack.SceneTarget() + + applyScene := func(dst *gpu.Texture) error { + enc := dev.BeginEncoder() + scene.draw(enc, sceneRT.Color, sceneRT.Depth) + err := stack.ApplyScene(dev, enc, dst) + post3dEdgeSubmit(t, sr, enc) + return err + } + + if err := applyScene(nil); err != nil { + t.Fatalf("ApplyScene(swapchain): %v", err) + } + swap := sr.Image() + + rgba8 := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatRGBA8Unorm, gpu.FormatUndefined) + if err := applyScene(rgba8.Color); err != nil { + t.Fatalf("ApplyScene(RGBA8 texture): %v", err) + } + if d := post3dMaxChannelDiff(swap, readTextureRGBA(t, dev, rgba8.Color)); d > 1 { + t.Errorf("RGBA8 destination differs from the RGBA8 swapchain by %d", d) + } + + hdr := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatRGBA16Float, gpu.FormatUndefined) + if err := applyScene(hdr.Color); err != nil { + t.Errorf("ApplyScene(ColorFormat texture): %v", err) + } + + bgra := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatBGRA8Unorm, gpu.FormatUndefined) + if err := applyScene(bgra.Color); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("ApplyScene(BGRA8 texture) = %v, want ErrInvalidPostProcess", err) + } + + // Every stage alone, and the passthrough blit, honour the destination format too. + for _, tc := range []struct { + name string + ssao, dof, bloom bool + }{ + {"ssao", true, false, false}, + {"dof", false, true, false}, + {"bloom", false, false, true}, + {"blit", false, false, false}, + } { + if err := stack.SetSSAO(tc.ssao, render3d.SSAOConfig{}); err != nil { + t.Fatalf("%s: SetSSAO: %v", tc.name, err) + } + if err := stack.SetDepthOfField(tc.dof, render3d.DepthOfFieldConfig{}); err != nil { + t.Fatalf("%s: SetDepthOfField: %v", tc.name, err) + } + if err := stack.SetBloom(tc.bloom, render3d.BloomConfig{}); err != nil { + t.Fatalf("%s: SetBloom: %v", tc.name, err) + } + if err := applyScene(nil); err != nil { + t.Fatalf("%s: ApplyScene(swapchain): %v", tc.name, err) + } + want := sr.Image() + if err := applyScene(rgba8.Color); err != nil { + t.Fatalf("%s: ApplyScene(RGBA8 texture): %v", tc.name, err) + } + if d := post3dMaxChannelDiff(want, readTextureRGBA(t, dev, rgba8.Color)); d > 1 { + t.Errorf("%s: RGBA8 destination differs from the swapchain by %d", tc.name, d) + } + if err := applyScene(bgra.Color); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("%s: ApplyScene(BGRA8 texture) = %v, want ErrInvalidPostProcess", tc.name, err) + } + } + + // The standalone passes pick their pipeline the same way. + src := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + bloom, err := render3d.NewBloomPass(nil, dev, render3d.BloomPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, OutputFormat: gpu.FormatRGBA8Unorm, Config: render3d.DefaultBloomConfig()}) + if err != nil { + t.Fatalf("NewBloomPass: %v", err) + } + defer func() { _ = bloom.Close() }() + ssao, err := render3d.NewSSAOPass(nil, dev, render3d.SSAOPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, OutputFormat: gpu.FormatRGBA8Unorm, Config: render3d.SSAOConfigFromCamera(cam)}) + if err != nil { + t.Fatalf("NewSSAOPass: %v", err) + } + defer func() { _ = ssao.Close() }() + dof, err := render3d.NewDepthOfFieldPass(nil, dev, render3d.DepthOfFieldPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, OutputFormat: gpu.FormatRGBA8Unorm, Config: render3d.DepthOfFieldConfigFromCamera(cam, 4.5, 2, 3)}) + if err != nil { + t.Fatalf("NewDepthOfFieldPass: %v", err) + } + defer func() { _ = dof.Close() }() + passes := []struct { + name string + apply func(enc *gpu.Encoder, dst *gpu.Texture) error + }{ + {"bloom", func(enc *gpu.Encoder, dst *gpu.Texture) error { return bloom.Apply(dev, enc, src.Color, dst) }}, + {"ssao", func(enc *gpu.Encoder, dst *gpu.Texture) error { return ssao.Apply(dev, enc, src.Color, src.Depth, dst) }}, + {"dof", func(enc *gpu.Encoder, dst *gpu.Texture) error { return dof.Apply(dev, enc, src.Color, src.Depth, dst) }}, + } + for _, p := range passes { + run := func(dst *gpu.Texture) error { + enc := dev.BeginEncoder() + scene.draw(enc, src.Color, src.Depth) + err := p.apply(enc, dst) + post3dEdgeSubmit(t, sr, enc) + return err + } + if err := run(nil); err != nil { + t.Fatalf("%s.Apply(swapchain): %v", p.name, err) + } + want := sr.Image() + if err := run(rgba8.Color); err != nil { + t.Fatalf("%s.Apply(RGBA8 texture): %v", p.name, err) + } + if d := post3dMaxChannelDiff(want, readTextureRGBA(t, dev, rgba8.Color)); d > 1 { + t.Errorf("%s: RGBA8 destination differs from the swapchain by %d", p.name, d) + } + if err := run(hdr.Color); err != nil { + t.Errorf("%s.Apply(ColorFormat texture): %v", p.name, err) + } + if err := run(bgra.Color); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("%s.Apply(BGRA8 texture) = %v, want ErrInvalidPostProcess", p.name, err) + } + } +} + +// Inputs and destinations whose size differs from the pass, and a destination that is also an input, are refused instead of being processed with texel steps for the wrong size. +func TestPost3DApplyRejectsMismatchedTextures(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dEdgeWidth, post3dEdgeHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + cam := post3dEdgeCamera() + + stack, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{ + Width: post3dEdgeWidth, Height: post3dEdgeHeight, OutputFormat: gpu.FormatRGBA8Unorm, + EnableSSAO: true, SSAO: render3d.SSAOConfigFromCamera(cam), + EnableBloom: true, Bloom: render3d.DefaultBloomConfig(), + }) + if err != nil { + t.Fatalf("NewPostStack3D: %v", err) + } + defer func() { _ = stack.Close() }() + ok := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + big := newPost3dEdgeTarget(t, dev, 2*post3dEdgeWidth, 2*post3dEdgeHeight, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + bigOut := newPost3dEdgeTarget(t, dev, 2*post3dEdgeWidth, 2*post3dEdgeHeight, gpu.FormatRGBA8Unorm, gpu.FormatUndefined) + + bloom, err := render3d.NewBloomPass(nil, dev, render3d.BloomPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, Config: render3d.DefaultBloomConfig()}) + if err != nil { + t.Fatalf("NewBloomPass: %v", err) + } + defer func() { _ = bloom.Close() }() + ssao, err := render3d.NewSSAOPass(nil, dev, render3d.SSAOPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, Config: render3d.SSAOConfigFromCamera(cam)}) + if err != nil { + t.Fatalf("NewSSAOPass: %v", err) + } + defer func() { _ = ssao.Close() }() + dof, err := render3d.NewDepthOfFieldPass(nil, dev, render3d.DepthOfFieldPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, Config: render3d.DepthOfFieldConfigFromCamera(cam, 4, 2, 3)}) + if err != nil { + t.Fatalf("NewDepthOfFieldPass: %v", err) + } + defer func() { _ = dof.Close() }() + + enc := dev.BeginEncoder() + for _, tc := range []struct { + name string + err error + }{ + {"stack big source", stack.Apply(dev, enc, big.Color, ok.Depth, nil)}, + {"stack big depth", stack.Apply(dev, enc, ok.Color, big.Depth, nil)}, + {"stack big destination", stack.Apply(dev, enc, ok.Color, ok.Depth, bigOut.Color)}, + {"stack destination is source", stack.Apply(dev, enc, ok.Color, ok.Depth, ok.Color)}, + {"stack scene into itself", stack.ApplyScene(dev, enc, stack.SceneTarget().Color)}, + {"bloom big source", bloom.Apply(dev, enc, big.Color, nil)}, + {"bloom big destination", bloom.Apply(dev, enc, ok.Color, big.Color)}, + {"bloom destination is source", bloom.Apply(dev, enc, ok.Color, ok.Color)}, + {"ssao big depth", ssao.Apply(dev, enc, ok.Color, big.Depth, nil)}, + {"ssao big source", ssao.Apply(dev, enc, big.Color, ok.Depth, nil)}, + {"ssao compute big depth", func() error { _, err := ssao.ComputeAO(dev, enc, big.Depth); return err }()}, + {"dof big depth", dof.Apply(dev, enc, ok.Color, big.Depth, nil)}, + {"dof destination is source", dof.Apply(dev, enc, ok.Color, ok.Depth, ok.Color)}, + } { + if !errors.Is(tc.err, render3d.ErrInvalidPostProcess) { + t.Errorf("%s = %v, want ErrInvalidPostProcess", tc.name, tc.err) + } + } + post3dEdgeSubmit(t, sr, enc) +} + +// ColorFormat accepts only filterable four-channel formats: Depth of Field keeps its Circle of Confusion in alpha and every pass filter-samples the intermediate targets. +func TestPost3DColorFormatValidation(t *testing.T) { + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + for _, f := range []gpu.TextureFormat{gpu.FormatR8Unorm, gpu.FormatRG8Unorm, gpu.FormatRGBA32Float, gpu.FormatR32Float, gpu.FormatRG11B10Float, gpu.FormatDepth32Float, gpu.FormatBC1RGBAUnorm} { + if _, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{Width: 16, Height: 16, ColorFormat: f}); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("NewPostStack3D(ColorFormat %s) = %v, want ErrInvalidPostProcess", f, err) + } + if _, err := render3d.NewBloomPass(nil, dev, render3d.BloomPassOptions{Width: 16, Height: 16, ColorFormat: f}); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("NewBloomPass(ColorFormat %s) = %v, want ErrInvalidPostProcess", f, err) + } + } + for _, f := range []gpu.TextureFormat{gpu.FormatRGBA16Float, gpu.FormatRGBA8Unorm, gpu.FormatRGBA8UnormSRGB, gpu.FormatBGRA8Unorm} { + s, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{Width: 16, Height: 16, ColorFormat: f}) + if err != nil { + t.Errorf("NewPostStack3D(ColorFormat %s): %v", f, err) + continue + } + _ = s.Close() + } +} + +// Turning a stage off with a zero config keeps the stage's current settings, and SetCamera refreshes the projection SSAO and Depth of Field depend on without touching anything else. +func TestPost3DStageTogglesAndSetCamera(t *testing.T) { + sr := gpu.NewSoftwareRenderer(32, 24, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + cam := post3dEdgeCamera() + ssaoCfg := render3d.SSAOConfigFromCamera(cam) + ssaoCfg.Radius = 0.9 + dofCfg := render3d.DepthOfFieldConfigFromCamera(cam, 4, 1.5, 3) + bloomCfg := render3d.DefaultBloomConfig() + bloomCfg.Intensity = 1.1 + stack, err := render3d.NewPostStack3D(nil, dev, render3d.PostStack3DOptions{ + Width: 32, Height: 24, EnableSSAO: true, SSAO: ssaoCfg, EnableDoF: true, DoF: dofCfg, EnableBloom: true, Bloom: bloomCfg, + }) + if err != nil { + t.Fatalf("NewPostStack3D: %v", err) + } + defer func() { _ = stack.Close() }() + + if err := stack.SetSSAO(false, render3d.SSAOConfig{}); err != nil { + t.Errorf("SetSSAO(false, zero): %v", err) + } + if err := stack.SetDepthOfField(false, render3d.DepthOfFieldConfig{}); err != nil { + t.Errorf("SetDepthOfField(false, zero): %v", err) + } + if err := stack.SetBloom(false, render3d.BloomConfig{}); err != nil { + t.Errorf("SetBloom(false, zero): %v", err) + } + if got := stack.SSAO().Config().Radius; got != 0.9 { + t.Errorf("SSAO Radius after toggle = %v, want 0.9", got) + } + if got := stack.DepthOfField().Config(); got != dofCfg { + t.Errorf("DoF config after toggle = %+v, want %+v", got, dofCfg) + } + if got := stack.Bloom().Config().Intensity; got != 1.1 { + t.Errorf("Bloom Intensity after toggle = %v, want 1.1", got) + } + if err := stack.SetSSAO(true, render3d.SSAOConfig{Radius: -1}); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("SetSSAO(invalid) = %v, want ErrInvalidPostProcess", err) + } + + // A resize that changes the aspect ratio and a zoom change the projection; SetCamera picks both up. + cam.SetViewport(48, 24) + cam.Projection.FOVY = math3d.DegToRad(35) + cam.Projection.Far = 0 // Matrix uses Near+1000. + if err := stack.SetCamera(cam); err != nil { + t.Fatalf("SetCamera: %v", err) + } + if got := stack.SSAO().Config(); got.ProjMatrix != cam.ProjMatrix() || got.Radius != 0.9 { + t.Errorf("SSAO after SetCamera: ProjMatrix %v Radius %v, want %v and 0.9", got.ProjMatrix, got.Radius, cam.ProjMatrix()) + } + dofGot := stack.DepthOfField().Config() + if !post3dNear(dofGot.Near, 0.2, 1e-4) || !post3dNear(dofGot.Far, 1000.2, 0.5) || dofGot.Orthographic || dofGot.FocusDistance != 4 { + t.Errorf("DoF after SetCamera = %+v, want Near 0.2, Far 1000.2, perspective, focus 4", dofGot) + } + if err := stack.SetCamera(nil); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("SetCamera(nil) = %v, want ErrInvalidPostProcess", err) + } +} + +func post3dNear(a, b, tol float32) bool { + return float32(math.Abs(float64(a-b))) <= tol +} + +// DepthOfFieldConfigFromCamera reads the clip planes from the projection matrix, so defaults the projection fills in and an orthographic camera whose near plane is behind it both linearize depth the way the depth buffer was written. +func TestPost3DDepthOfFieldCameraClipPlanes(t *testing.T) { + for _, tc := range []struct { + name string + proj scene3d.Projection + near, far float32 + ortho bool + }{ + {"perspective far defaulted", scene3d.PerspectiveProjection(math3d.DegToRad(60), 1, 0.5, 0), 0.5, 1000.5, false}, + {"perspective near defaulted", scene3d.PerspectiveProjection(math3d.DegToRad(60), 1, 0, 50), 0.1, 50, false}, + {"orthographic both zero", scene3d.OrthographicProjection(4, 1, 0, 0), 0.1, 1000, true}, + {"orthographic negative near", scene3d.OrthographicProjection(4, 1, -2, 30), -2, 30, true}, + } { + cam := &scene3d.Camera{Rot: math3d.QuatIdentity(), Projection: tc.proj} + cfg := render3d.DepthOfFieldConfigFromCamera(cam, 3, 1, 4) + tol := float32(1e-3) * max(1, float32(math.Abs(float64(tc.far)))) + if !post3dNear(cfg.Near, tc.near, 1e-3) || !post3dNear(cfg.Far, tc.far, tol) || cfg.Orthographic != tc.ortho { + t.Errorf("%s: Near %v Far %v Orthographic %v, want %v %v %v", tc.name, cfg.Near, cfg.Far, cfg.Orthographic, tc.near, tc.far, tc.ortho) + } + if err := cfg.Validate(); err != nil { + t.Errorf("%s: Validate: %v", tc.name, err) + } + } + persp := render3d.DefaultDepthOfFieldConfig() + persp.Near = -1 + if err := persp.Validate(); !errors.Is(err, render3d.ErrInvalidPostProcess) { + t.Errorf("perspective Near -1 Validate = %v, want ErrInvalidPostProcess", err) + } +} + +// An orthographic Depth of Field keeps the panel at the focus distance sharp and blurs the one behind it, with a near plane behind the camera that the old Near > 0 clamp would have replaced. +func TestPost3DDepthOfFieldOrthographic(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dEdgeWidth, post3dEdgeHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + sp := newPost3dScenePipeline(t, nil, dev, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + defer func() { _ = sp.cam.Close() }() + cam := &scene3d.Camera{Rot: math3d.QuatIdentity(), Projection: scene3d.OrthographicProjection(4, float32(post3dEdgeWidth)/float32(post3dEdgeHeight), -2, 30)} + + var verts []float32 + verts = post3dAppendCheckerPanel(verts, math3d.Vec3{X: -1.3, Z: -3}, 2.2, 3, 6, 8, [3]float32{0.95, 0.2, 0.2}, [3]float32{0.95, 0.95, 0.95}) + verts = post3dAppendCheckerPanel(verts, math3d.Vec3{X: 1.3, Z: -12}, 2.2, 3, 6, 8, [3]float32{0.2, 0.4, 0.95}, [3]float32{0.95, 0.95, 0.95}) + vb, err := dev.CreateBuffer(nil, gpu.BufferDesc{Usage: gpu.UsageVertex, Data: post3dPackFloats(verts)}) + if err != nil { + t.Fatalf("CreateBuffer: %v", err) + } + defer func() { _ = vb.Close() }() + scene := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + + cfg := render3d.DepthOfFieldConfigFromCamera(cam, 3, 1.5, 4) + if !cfg.Orthographic || !post3dNear(cfg.Near, -2, 1e-3) { + t.Fatalf("config from orthographic camera = %+v", cfg) + } + dof, err := render3d.NewDepthOfFieldPass(nil, dev, render3d.DepthOfFieldPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, OutputFormat: gpu.FormatRGBA8Unorm, Config: cfg}) + if err != nil { + t.Fatalf("NewDepthOfFieldPass: %v", err) + } + defer func() { _ = dof.Close() }() + + render := func(c render3d.DepthOfFieldConfig) *image.RGBA { + if err := dof.SetConfig(c); err != nil { + t.Fatalf("SetConfig: %v", err) + } + sp.cam.WriteCamera(cam) + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{Texture: scene.Color, LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore, ClearColor: core.RGB(0x141820)}}, + DepthStencil: &gpu.DepthStencilAttachment{Texture: scene.Depth, DepthLoadOp: gpu.LoadClear, DepthStoreOp: gpu.StoreStore, ClearDepth: 1}, + }) + sp.draw(pass, vb, uint32(len(verts)/10)) + pass.End() + if err := dof.Apply(dev, enc, scene.Color, scene.Depth, nil); err != nil { + t.Fatalf("Apply: %v", err) + } + post3dEdgeSubmit(t, sr, enc) + return sr.Image() + } + blurred := render(cfg) + sharpCfg := cfg + sharpCfg.MaxBlurRadius = 0 + sharp := render(sharpCfg) + + focusRaw := post3dRegionContrast(sharp, 6, 10, 26, 38) + focusDoF := post3dRegionContrast(blurred, 6, 10, 26, 38) + farRaw := post3dRegionContrast(sharp, 38, 10, 58, 38) + farDoF := post3dRegionContrast(blurred, 38, 10, 58, 38) + if focusRaw < 0.05 || focusDoF < focusRaw*0.9 { + t.Errorf("in-focus orthographic panel blurred: %.4f vs %.4f", focusDoF, focusRaw) + } + if farRaw < 0.05 || farDoF > farRaw*0.6 { + t.Errorf("far orthographic panel not blurred: %.4f vs %.4f", farDoF, farRaw) + } +} + +// With ProjMatrix left zero, SSAO falls back to a 60-degree perspective at the pass aspect ratio and the configured Near and Far, which matches a camera built that way. +func TestPost3DSSAOProjectionFallback(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dEdgeWidth, post3dEdgeHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 1.6, Y: 1.8, Z: 4.2}, math3d.DegToRad(60), float32(post3dEdgeWidth)/float32(post3dEdgeHeight), 0.2, 40) + cam.LookAt(math3d.Vec3{X: 0, Y: 0.4, Z: -0.4}, math3d.Vec3Up()) + scene := newPost3dEdgeScene(t, dev, cam) + rt := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + + withMatrix := render3d.SSAOConfigFromCamera(cam) + fallback := withMatrix + fallback.ProjMatrix = math3d.Mat4{} + fallback.Near, fallback.Far = 0.2, 40 + + ao := func(cfg render3d.SSAOConfig) *image.RGBA { + p, err := render3d.NewSSAOPass(nil, dev, render3d.SSAOPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, Config: cfg}) + if err != nil { + t.Fatalf("NewSSAOPass: %v", err) + } + defer func() { _ = p.Close() }() + enc := dev.BeginEncoder() + scene.draw(enc, rt.Color, rt.Depth) + tex, err := p.ComputeAO(dev, enc, rt.Depth) + if err != nil { + t.Fatalf("ComputeAO: %v", err) + } + post3dEdgeSubmit(t, sr, enc) + return readTextureRGBA(t, dev, tex) + } + a, b := ao(withMatrix), ao(fallback) + if d := post3dMaxChannelDiff(a, b); d > 2 { + t.Errorf("fallback projection AO differs from the 60-degree camera's by %d", d) + } + occluded := 0 + for y := range post3dEdgeHeight { + for x := range post3dEdgeWidth { + if a.RGBAAt(x, y).R < 230 { + occluded++ + } + } + } + if occluded == 0 { + t.Error("AO map is blank; the scene produced no occlusion to compare") + } +} + +// Toggling BloomConfig.HalfRes through SetConfig reallocates the blur targets inside Apply, and switching back reproduces the first image. +func TestPost3DBloomHalfResToggle(t *testing.T) { + sr := gpu.NewSoftwareRenderer(post3dEdgeWidth, post3dEdgeHeight, gpu.FormatDepth32Float) + defer sr.Close() + dev := sr.Device() + scene := newPost3dEdgeScene(t, dev, post3dEdgeCamera()) + rt := newPost3dEdgeTarget(t, dev, post3dEdgeWidth, post3dEdgeHeight, gpu.FormatRGBA16Float, gpu.FormatDepth32Float) + + full := render3d.DefaultBloomConfig() + full.HalfRes = false + bloom, err := render3d.NewBloomPass(nil, dev, render3d.BloomPassOptions{Width: post3dEdgeWidth, Height: post3dEdgeHeight, OutputFormat: gpu.FormatRGBA8Unorm, Config: full}) + if err != nil { + t.Fatalf("NewBloomPass: %v", err) + } + defer func() { _ = bloom.Close() }() + render := func(cfg render3d.BloomConfig) *image.RGBA { + if err := bloom.SetConfig(cfg); err != nil { + t.Fatalf("SetConfig: %v", err) + } + enc := dev.BeginEncoder() + scene.draw(enc, rt.Color, rt.Depth) + if err := bloom.Apply(dev, enc, rt.Color, nil); err != nil { + t.Fatalf("Apply: %v", err) + } + post3dEdgeSubmit(t, sr, enc) + return sr.Image() + } + half := full + half.HalfRes = true + first := render(full) + halfImg := render(half) + again := render(full) + if d := post3dMaxChannelDiff(first, halfImg); d == 0 { + t.Error("half-resolution bloom rendered the same image as full resolution") + } + if d := post3dMaxChannelDiff(first, again); d > 1 { + t.Errorf("full-resolution bloom after a HalfRes round trip differs by %d", d) + } +} diff --git a/packages/game/render3d/post3d_test.go b/packages/game/render3d/post3d_test.go index 22e420d4..17e0cc58 100644 --- a/packages/game/render3d/post3d_test.go +++ b/packages/game/render3d/post3d_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/nsgo-dev/game/packages/game/gametest" "github.com/nsgo-dev/game/packages/game/math3d" "github.com/nsgo-dev/game/packages/game/render3d" "github.com/nsgo-dev/game/packages/game/scene3d" @@ -176,47 +175,6 @@ func (sp *post3dScenePipeline) draw(pass *gpu.RenderPass, vb *gpu.Buffer, vertCo pass.Draw(vertCount, 0) } -func post3dAssertGolden(t *testing.T, name string, got *image.RGBA) { - t.Helper() - path := gametest.GoldenPath("", name) - if gametest.ShouldUpdateGolden() { - if err := gametest.WritePNG(path, got); err != nil { - t.Fatal(err) - } - return - } - want, err := gametest.ReadPNG(path) - if err != nil { - t.Fatalf("read reference %s: %v (UPDATE_GOLDEN=1 writes it)", path, err) - } - if !want.Bounds().Eq(got.Bounds()) { - t.Fatalf("%s: size %v, reference %v", name, got.Bounds(), want.Bounds()) - } - const channelTolerance = 3 - far := 0 - b := got.Bounds() - for y := b.Min.Y; y < b.Max.Y; y++ { - for x := b.Min.X; x < b.Max.X; x++ { - g := got.RGBAAt(x, y) - wr, wg, wb, wa := want.At(x, y).RGBA() - w := [4]int{int(wr >> 8), int(wg >> 8), int(wb >> 8), int(wa >> 8)} - for i, c := range [4]int{int(g.R), int(g.G), int(g.B), int(g.A)} { - if d := c - w[i]; d > channelTolerance || d < -channelTolerance { - far++ - break - } - } - } - } - if limit := b.Dx() * b.Dy() / 200; far > limit { - dir := t.TempDir() - diff, _ := gametest.DiffImage(got, want) - _ = gametest.WritePNG(dir+"/"+name+".got.png", got) - _ = gametest.WritePNG(dir+"/"+name+".diff.png", diff) - t.Fatalf("%s: %d pixels differ from reference (limit %d); got and diff written to %s", name, far, limit, dir) - } -} - func post3dLuma(img *image.RGBA, x, y int) float64 { c := img.RGBAAt(x, y) return (0.2126*float64(c.R) + 0.7152*float64(c.G) + 0.0722*float64(c.B)) / 255.0 @@ -366,7 +324,7 @@ func TestPost3DBloomMatchesReference(t *testing.T) { } bloomImg := renderFrame(bloom.Config()) - post3dAssertGolden(t, "post3d_bloom", bloomImg) + assertReference(t, "post3d_bloom", bloomImg) noIntensity := bloom.Config() noIntensity.Intensity = 0 @@ -509,7 +467,7 @@ func TestPost3DSSAOMatchesReference(t *testing.T) { } ssaoImg := renderFrame(cfg) - post3dAssertGolden(t, "post3d_ssao", ssaoImg) + assertReference(t, "post3d_ssao", ssaoImg) if ssao.AOTexture() == nil || !ssao.AOTexture().Valid() { t.Error("AOTexture() invalid after Apply") @@ -624,7 +582,7 @@ func TestPost3DDepthOfFieldMatchesReference(t *testing.T) { } dofImg := renderFrame(dofCfg) - post3dAssertGolden(t, "post3d_dof", dofImg) + assertReference(t, "post3d_dof", dofImg) sharpCfg := dofCfg sharpCfg.MaxBlurRadius = 0 @@ -739,7 +697,7 @@ func TestPost3DStackCombinedResizeAndProfiles(t *testing.T) { } combinedImg := renderCombined() - post3dAssertGolden(t, "post3d_combined", combinedImg) + assertReference(t, "post3d_combined", combinedImg) // Passthrough blit when all passes are disabled must differ cleanly from combined post-processed output. if err := stack.SetSSAO(false, ssaoCfg); err != nil { From 27c75bf67460a06e4499f3e5ccac0ce0ebac1f61 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Wed, 25 Nov 2026 03:18:33 +0900 Subject: [PATCH 9/9] docs(render3d): document post-processing formats, destinations, toggles and SetCamera --- docs/en/render3d.md | 9 ++++++++- docs/zh/render3d.md | 9 ++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/en/render3d.md b/docs/en/render3d.md index 748777fe..5ffff73f 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -1163,9 +1163,16 @@ pass := stack.BeginScenePass(frame, core.RGB(0x0c1018)) pass.End() _ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> Depth of Field -> Bloom -> swapchain frame.Submit() + +// When the view resizes (or the camera zooms), refresh the projection SSAO and DoF depend on: +_ = stack.Resize(dev, uint32(w), uint32(h)) +cam.SetViewport(float32(w), float32(h)) +_ = stack.SetCamera(cam) ``` -- **Composable order and standalone passes**: `PostStack3D` runs enabled stages in fixed order — **SSAO -> Depth of Field -> Bloom** — routing intermediate results through ping-pong offscreen targets and writing the final stage directly in `OutputFormat` (or blitting cleanly when all stages are disabled). Each pass (`SSAOPass`, `DepthOfFieldPass`, `BloomPass`) can also be constructed and applied standalone against any caller-owned `gpu.Texture` color and depth attachments via `RenderPassRecorder` (satisfied by both `*gpu.Frame` and `*gpu.Encoder`). +- **Composable order and standalone passes**: `PostStack3D` runs enabled stages in fixed order — **SSAO -> Depth of Field -> Bloom** — routing intermediate results through ping-pong offscreen targets and writing the final stage directly in `OutputFormat` (or blitting cleanly when all stages are disabled). `SetSSAO`, `SetDepthOfField` and `SetBloom` toggle a stage; a zero config keeps its current settings, so `stack.SetSSAO(false, render3d.SSAOConfig{})` only turns SSAO off. Each pass (`SSAOPass`, `DepthOfFieldPass`, `BloomPass`) can also be constructed and applied standalone against any caller-owned `gpu.Texture` color and depth attachments via `RenderPassRecorder` (satisfied by both `*gpu.Frame` and `*gpu.Encoder`). +- **Formats and destinations**: `ColorFormat` (scene and intermediate targets) is `FormatRGBA16Float` (default), `FormatRGBA8Unorm`, `FormatRGBA8UnormSRGB`, `FormatBGRA8Unorm` or `FormatBGRA8UnormSRGB`: four filterable channels, because Depth of Field stores its Circle of Confusion in alpha. A nil destination writes to the swapchain in `OutputFormat`; a destination texture must be in `ColorFormat` or `OutputFormat`, and the last stage draws with the pipeline built for that format. Every input and destination must have the pass or stack size, and the destination cannot also be an input; otherwise `Apply` returns `ErrInvalidPostProcess`. +- **Camera projection**: `SSAOConfigFromCamera` captures `cam.ProjMatrix()` and `DepthOfFieldConfigFromCamera` reads the near and far planes and projection kind from that matrix, so the defaults `scene3d.Projection` fills in for zero fields (and an orthographic near plane at or behind the camera) match the depth buffer. Both are captured once; call `PostStack3D.SetCamera` (or `SetConfig` on a standalone pass) whenever the projection changes. With a zero `ProjMatrix`, SSAO falls back to a 60° perspective at the pass aspect ratio with the config's `Near` and `Far`. - **SSAO (`SSAOConfig`, `SSAOPass`)**: reconstructs view-space positions and edge-preserving normals from the 3D depth buffer, evaluates a deterministic 4–16-sample hemisphere kernel with stratified 4×4 tangent rotation, applies an optional depth-aware bilateral blur (`BlurRadius`, `DepthThreshold`), and multiplies ambient occlusion into the scene color (`AOTexture` exposes the AO map for inspection). - **Depth of Field (`DepthOfFieldConfig`, `DepthOfFieldPass`)**: linearizes perspective or orthographic `[0, 1]` depth to compute a signed Circle of Confusion around `FocusDistance` ± `FocusRange`, then gathers an 18-tap two-ring disc bokeh blur that prevents blurred background pixels from bleeding across sharp in-focus silhouettes. - **Bloom (`BloomConfig`, `BloomPass`)**: extracts bright LDR or HDR (`> 1.0`) pixels with a quadratic `Threshold` / `SoftKnee` curve, runs `BlurPasses` separable 9-tap Gaussian horizontal and vertical passes (optionally at half resolution via `HalfRes`), and composites the glow additively with `Intensity`. diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 93ea70c1..28ea7d55 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -1163,9 +1163,16 @@ pass := stack.BeginScenePass(frame, core.RGB(0x0c1018)) pass.End() _ = stack.ApplyScene(frame.Device(), frame, nil) // SSAO -> 景深 -> Bloom -> 交换链 frame.Submit() + +// 视图尺寸变化(或相机缩放)时,刷新 SSAO 与景深所依赖的投影: +_ = stack.Resize(dev, uint32(w), uint32(h)) +cam.SetViewport(float32(w), float32(h)) +_ = stack.SetCamera(cam) ``` -- **可组合管线与独立通道**:`PostStack3D` 按固定顺序执行已启用的阶段——**SSAO → 景深 → Bloom**——中间结果在乒乓离屏渲染目标之间流转,最后一个阶段直接以 `OutputFormat` 输出(全部关闭时执行干净直通复制)。每个通道(`SSAOPass`、`DepthOfFieldPass`、`BloomPass`)也可独立创建,并通过 `RenderPassRecorder`(`*gpu.Frame` 与 `*gpu.Encoder` 均已实现)作用于调用方自建的 `gpu.Texture` 颜色与深度附件。 +- **可组合管线与独立通道**:`PostStack3D` 按固定顺序执行已启用的阶段——**SSAO → 景深 → Bloom**——中间结果在乒乓离屏渲染目标之间流转,最后一个阶段直接以 `OutputFormat` 输出(全部关闭时执行干净直通复制)。`SetSSAO`、`SetDepthOfField` 与 `SetBloom` 用于开关单个阶段;传入零值配置时保留当前设置,因此 `stack.SetSSAO(false, render3d.SSAOConfig{})` 只会关闭 SSAO。每个通道(`SSAOPass`、`DepthOfFieldPass`、`BloomPass`)也可独立创建,并通过 `RenderPassRecorder`(`*gpu.Frame` 与 `*gpu.Encoder` 均已实现)作用于调用方自建的 `gpu.Texture` 颜色与深度附件。 +- **格式与输出目标**:`ColorFormat`(场景与中间渲染目标)可取 `FormatRGBA16Float`(默认)、`FormatRGBA8Unorm`、`FormatRGBA8UnormSRGB`、`FormatBGRA8Unorm` 或 `FormatBGRA8UnormSRGB`,即可过滤采样的四通道格式,因为景深把弥散圆存放在 alpha 通道中。目标为 nil 时以 `OutputFormat` 写入交换链;目标纹理必须是 `ColorFormat` 或 `OutputFormat`,最后一个阶段使用为该格式构建的管线绘制。所有输入与目标纹理的尺寸都必须与通道或后处理栈一致,且目标不能同时是输入,否则 `Apply` 返回 `ErrInvalidPostProcess`。 +- **相机投影**:`SSAOConfigFromCamera` 记录 `cam.ProjMatrix()`,`DepthOfFieldConfigFromCamera` 从该矩阵读取近、远裁剪面与投影类型,因此 `scene3d.Projection` 为零值字段填入的默认值(以及位于相机处或其后方的正交近裁剪面)都与深度缓冲一致。两者只在创建配置时记录一次;投影变化时请调用 `PostStack3D.SetCamera`(独立通道则调用 `SetConfig`)。`ProjMatrix` 为零时,SSAO 回退为按通道宽高比、使用配置中 `Near` 与 `Far` 的 60° 透视投影。 - **SSAO(`SSAOConfig`、`SSAOPass`)**:从 3D 深度缓冲重建视空间位置与保边法线,使用带 4×4 分层切线旋转的确定性 4–16 采样半球核计算遮蔽,支持可选的深度感知双边模糊(`BlurRadius`、`DepthThreshold`),并将环境光遮蔽乘入场景颜色(可通过 `AOTexture` 获取 AO 纹理)。 - **景深(`DepthOfFieldConfig`、`DepthOfFieldPass`)**:支持透视与正交 `[0, 1]` 深度线性化,围绕 `FocusDistance` ± `FocusRange` 计算带符号弥散圆(CoC),并通过 18 采样双环圆盘散景模糊平滑虚化近景与远景,同时阻止背景模糊色溢入清晰的焦内轮廓。 - **泛光(`BloomConfig`、`BloomPass`)**:用二次软拐点阈值曲线(`Threshold`、`SoftKnee`)提取 LDR 或 HDR(`> 1.0`)高亮像素,执行 `BlurPasses` 轮可分离 9 采样高斯横纵模糊(可通过 `HalfRes` 启用半分辨率以获得更宽柔和光晕),再以 `Intensity` 加法混合回场景。