From 7c935e763782ba2e08cfacb734c788f31b8f3170 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 24 Nov 2026 19:17:23 +0900 Subject: [PATCH 1/3] feat(render3d): add point and spot light shadow maps --- .../2026-11-24-render3d-local-shadows.md | 48 + changelog.d/render3d-local-shadows-255.md | 3 + docs/en/render3d.md | 41 + docs/zh/render3d.md | 41 + packages/game/render3d/local_shadows.go | 1917 +++++++++++++++++ packages/game/render3d/local_shadows_test.go | 1214 +++++++++++ .../testdata/golden/local_shadow_point.png | Bin 0 -> 9776 bytes .../testdata/golden/local_shadow_spot.png | Bin 0 -> 7758 bytes 8 files changed, 3264 insertions(+) create mode 100644 .agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md create mode 100644 changelog.d/render3d-local-shadows-255.md create mode 100644 packages/game/render3d/local_shadows.go create mode 100644 packages/game/render3d/local_shadows_test.go create mode 100644 packages/game/render3d/testdata/golden/local_shadow_point.png create mode 100644 packages/game/render3d/testdata/golden/local_shadow_spot.png diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md b/.agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md new file mode 100644 index 00000000..fb6c8954 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md @@ -0,0 +1,48 @@ +# Agent Note: Point and Spot Light Shadow Maps in render3d + +Status: implemented + +## Problem + +Issue #255 (part of #251) requires real-time shadow maps for local 3D lights—perspective 2D shadows for spot lights and omnidirectional shadows for point lights—whose rendered shadows match analytic and golden references across every NSGo GPU backend (Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software GPU renderer). + +Implementing local shadows directly on top of NSGo v0.3.0's `gpu.Device` exposes four cross-backend constraints that callers should not have to rediscover: + +1. **No layered depth attachments**: `gpu.DepthStencilAttachment` targets a 2D `*gpu.Texture` without an `ArrayLayer` selector, so rendering six cube faces directly into a `DimCube` depth texture is not expressible through the portable render-pass API. +2. **Uniform control flow and software VM limits**: WebGPU restricts `textureSampleCompare` to uniform control flow (rejecting calls inside `if` bounds checks), and NSGo v0.3.0's software GPU VM does not implement `exp`, `exp2`, or `log2`. +3. **Multi-caster uniform aliasing inside one pass**: Calling `Device.WriteBuffer` repeatedly to offset 0 of a single caster uniform buffer inside one `RenderPass` overwrites earlier casters' model matrices before `Submit` executes the pass. +4. **Device-loss restoration**: As recorded in [3D GPU Textures and Samplers](2026-11-24-render3d-textures-and-samplers.md), caching a `*gpu.Device` pointer on a retained resource wrapper becomes stale after `TriggerGPUDeviceLost` + `RestoreGPUDevice`. + +## Decision + +`packages/game/render3d/local_shadows.go` implements `SpotShadowMap` and `PointShadowMap` as dedicated, self-contained files (`local_shadows.go`, `local_shadows_test.go`, and golden PNGs under `testdata/golden/local_shadow_*.png`) to avoid symbol or file collisions with parallel directional/CSM/spotlight work: + +- **3×2 2D `FormatDepth32Float` atlas for point lights (`PointShadowMap`)**: All six 90° cube faces (`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`) are packed into a single `(3 * FaceResolution) × (2 * FaceResolution)` depth-only `gpu.RenderTarget`. `BeginFacePass(rec, face)` clears the entire atlas on `face == 0` (`LoadClear`), preserves previous tiles on `face` 1..5 (`LoadLoad`), and locks both `SetViewport` and `SetScissor` to that face's tile so geometry cannot bleed into neighboring faces. +- **Analytic perspective depth without a depth fragment shader**: Both spot and point shadow passes use a vertex-only depth pipeline (`vs_local_shadow_depth`) writing standard `[0, 1]` perspective depth. In `PointShadowWGSL`, `sample_point_shadow` selects the dominant cube face from `worldPos + worldNormal * normalBias - lightPos`, projects `(xView, yView, axisDist)` directly into tile-local UV, computes the exact NDC depth `(far/(far-near)) * (1 - near/axisDist)` without uploading six `mat4x4`s to the fragment shader, and clamps every tap inside `[0.51/faceRes, 1 - 0.51/faceRes]` so linear comparison and 3×3 PCF taps never sample across tile boundaries. +- **Portable WGSL and `textureSampleCompareLevel`**: `SpotShadowWGSL` and `PointShadowWGSL` avoid `exp`/`exp2`/`log2` completely (using algebraic windowed inverse-square attenuation and smooth cubic cone falloff) and call `textureSampleCompareLevel` so bounds checks and filter branches remain valid under WebGPU's strict uniformity analysis as well as WebGL 2, GLES 3.0, and the software renderer. +- **256-byte dynamic-offset caster uniform slots**: Both shadow maps allocate a `casterBuf` sized to `MaxCasters * 256` bytes and bind it with `HasDynamicOffset: true`. Each `DrawCaster(dev, pass, mesh, model)` writes `(lightViewProj, model)` to the next aligned slot and binds its dynamic offset before `mesh.Draw(pass)`, allowing multiple casters with distinct transforms in a single pass (or across all six point-light faces in one encoder/frame). +- **Recorder-agnostic passes and explicit live `*gpu.Device`**: `BeginShadowPass` and `BeginFacePass` accept `LocalShadowPassRecorder` (satisfied by both `*gpu.Encoder` and `*gpu.Frame`), and `Update` / `DrawCaster` accept `dev *gpu.Device` explicitly so `Retained: true` shadow maps survive device loss and restore cleanly. +- **Pure-Go CPU reference evaluators**: `EvaluateSpotShadow`, `EvaluateSpotLighting`, `PointShadowSelectFace`, `EvaluatePointShadow`, and `EvaluatePointLighting` mirror the WGSL math (including nearest vs linear depth comparison and clamped 3×3 PCF) for deterministic GPU-vs-CPU verification in `local_shadows_test.go`. + +## Alternatives considered + +### Render point shadows into a `DimCube` depth texture with `texture_depth_cube` + +A native cubemap depth texture lets hardware select faces and filter seamlessly across cube edges in a single `textureSampleCompare` call. It was rejected because NSGo v0.3.0's `gpu.DepthStencilAttachment` has no `ArrayLayer` field to attach individual cube faces, and cubemap depth attachments plus seamless cubemap PCF have backend-specific caveats on WebGL 2 and OpenGL ES 3.0. Packing the six faces into a `3×2` `FormatDepth32Float` 2D render target with per-tile scissor and UV clamping works identically across all six NSGo backends and the software GPU renderer. + +### Write linear distance via `@builtin(frag_depth)` in a fragment shader for point shadows + +Writing `length(worldPos - lightPos) / range` to `@builtin(frag_depth)` simplifies depth bias to a uniform world-space offset across all distances. It was rejected because writing `frag_depth` disables hardware early-Z optimization on every backend and requires fragment-shader execution during shadow passes, whereas analytic perspective NDC depth `(far/(far-near)) * (1 - near/axisDist)` matches the vertex-only hardware depth buffer exactly while keeping world-space `NormalBias` for grazing-angle acne suppression. + +### Use one static caster uniform buffer overwritten per `DrawCaster` + +A single 128-byte uniform buffer avoids sizing a `MaxCasters * 256` slot buffer. It was rejected because `Device.WriteBuffer` executes before the submitted command buffer runs, so drawing two or more casters in the same shadow pass (or across six faces in one command encoder) would silently overwrite earlier casters' transforms with the last caster's matrix. + +## Consequences + +- **Benefits**: + - Perspective spot-light and omnidirectional 6-face point-light shadows work identically on full GPU profiles and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0), with zero-allocation uniform encoding (`SpotShadowUniform.Encode`, `PointShadowUniform.Encode`), multi-caster dynamic offsets, `Retained` device-loss restoration, and exact `ByteSize()` budget reporting. + - Verified by `local_shadows_test.go` against both pure-Go CPU reference evaluators (`EvaluateSpotLighting`, `EvaluatePointLighting`) and golden reference PNGs (`local_shadow_spot.png`, `local_shadow_point.png`). +- **Costs**: + - `PointShadowMap`'s `3×2` atlas clamps PCF taps inside each tile boundary rather than filtering across cube-face seams, which can leave a subtle 1-texel softness discontinuity right along a cube diagonal edge; increasing `FaceResolution` minimizes it. + - `DrawCaster` caps draws per shadow submission at `MaxCasters` (default 256 for spot, 1024 for point) and silently skips excess draws rather than resizing GPU buffers mid-pass; callers with larger caster counts should raise `MaxCasters` in the config. diff --git a/changelog.d/render3d-local-shadows-255.md b/changelog.d/render3d-local-shadows-255.md new file mode 100644 index 00000000..f02cee81 --- /dev/null +++ b/changelog.d/render3d-local-shadows-255.md @@ -0,0 +1,3 @@ +### Added + +- `game/render3d`: perspective 2D spot-light shadow maps (`SpotShadowMap`, `SpotShadowConfig`, `SpotShadowLight`, `SpotShadowWGSL`, `NewSpotShadowLitPipeline`) and omnidirectional 3×2 depth-atlas point-light shadow maps (`PointShadowMap`, `PointShadowConfig`, `PointShadowLight`, `PointShadowWGSL`, `NewPointShadowLitPipeline`) with hard and 3×3 PCF filtering, normal/depth biasing, dynamic-offset multi-caster drawing, `Retained` device-loss restoration, and pure-Go CPU reference evaluators (`EvaluateSpotShadow`, `EvaluatePointShadow`) (#255). diff --git a/docs/en/render3d.md b/docs/en/render3d.md index 05312c09..ca9f4fe4 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -1092,3 +1092,44 @@ _ = renderer.Draw(pass, camBuf, lmMesh, worldMat, mat) - **Atlas transform**: `LightmapRef.UVScale` / `UVOffset` are the authoritative atlas transform; `LightmapRef.Texture` carries no scale or offset, so do not also apply it with `TransformTexCoords`. See [Baked lightmaps](3d-models-blender.md#baked-lightmaps) for where the values come from. - **Texture streaming**: `BeginFrame` drops cached bind groups of lightmap and albedo textures that have been closed, so streaming levels or hot-reloading lightmaps does not grow the cache. - **Scope**: `LightmapRenderer` is a standalone path, albedo times (baked irradiance plus one Lambertian light). It has no metallic-roughness, normal, occlusion or emissive maps and does not read a `LightRig`. Feeding lightmaps into the PBR material path as its indirect term is tracked in [#752](https://github.com/nsgo-dev/game/issues/752). + +## Point and spot light shadows (`SpotShadowMap`, `PointShadowMap`) + +`SpotShadowMap` and `PointShadowMap` render depth-only `FormatDepth32Float` shadow maps for local lights and expose them alongside comparison samplers and WGSL helpers (`SpotShadowWGSL`, `PointShadowWGSL`) that run portably across Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software GPU renderer (`nsgotest.NoGPUCompute` included): + +- **Spot light shadows (`SpotShadowMap`)**: builds a square `[0, 1]`-depth perspective projection matching `SpotShadowLight.Position`, `Direction`, `OuterConeAngle` (`fovY = 2 * OuterConeAngle`), `Near`, and `Range`. `BeginShadowPass` clears depth and binds the depth-only caster pipeline; `DrawCaster` writes each caster's `(lightViewProj, model)` transform into a 256-byte dynamic-offset uniform slot so any number of casters (up to `MaxCasters`) draw in one pass without overwriting earlier transforms. +- **Omnidirectional point light shadows (`PointShadowMap`)**: packs all six 90° cube faces (`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`) into a single `3×2` `FormatDepth32Float` 2D depth atlas of size `(3 * FaceResolution) × (2 * FaceResolution)`. Calling `BeginFacePass(rec, face)` for `face` `0..5` clears the atlas on face 0, preserves earlier tiles on faces 1..5 (`LoadLoad`), and locks viewport and scissor to each face's tile. In `PointShadowWGSL`, `sample_point_shadow` selects the dominant cube face, computes analytic perspective NDC depth `(far/(far-near))*(1 - near/axisDist)` without uploading six matrices to the fragment shader, and clamps every tap inside `[0.51/faceRes, 1 - 0.51/faceRes]` so 3×3 PCF never bleeds across adjacent atlas tiles. +- **Filtering, biasing, and ready-made pipelines**: choose `LocalShadowFilterHard` (single nearest comparison tap) or `LocalShadowFilterPCF3x3` (9 linear comparison taps) with configurable `DepthBias` and `NormalBias`. `BeginShadowPass` and `BeginFacePass` accept both `*gpu.Encoder` and `*gpu.Frame` (`LocalShadowPassRecorder`). Use `NewSpotShadowLitPipeline` or `NewPointShadowLitPipeline` for quick shadowed lighting with `CameraGroup` (0) and `LocalShadowGroup` (1), or prepend `CameraWGSL` + `SpotShadowWGSL` / `PointShadowWGSL` to custom fragment shaders. +- **Device-loss recovery and CPU reference**: setting `Retained: true` recreates the depth render target, comparison sampler, uniform buffers, bind groups, and depth pipeline automatically after a device loss (`Update` and `DrawCaster` take the live `*gpu.Device` explicitly). Pure-Go evaluators `EvaluateSpotShadow`, `EvaluateSpotLighting`, `PointShadowSelectFace`, `EvaluatePointShadow`, and `EvaluatePointLighting` mirror the WGSL shaders for analytic verification, alongside golden reference renders `render3d/testdata/golden/local_shadow_spot.png` and `local_shadow_point.png` (`UPDATE_GOLDEN=1` rewrites them). + +```go +spot, err := render3d.NewSpotShadowMap(cx, dev, render3d.DefaultSpotShadowConfig()) +litPipe, err := render3d.NewSpotShadowLitPipeline(cx, dev, camBuf.Layout(), spot.Layout(), render3d.LocalShadowLitPipelineOptions{ + DepthFormat: gpu.FormatDepth24Plus, + CullMode: gpu.CullBack, +}) + +// Each frame in OnFrame: +_ = spot.Update(dev, spotLight) +sp := spot.BeginShadowPass(frame) +spot.DrawCaster(dev, sp, pillarMesh, pillarModel) +sp.End() + +mp := frame.BeginRenderPass(gpu.RenderPassDesc{}) +mp.SetPipeline(litPipe) +mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) +mp.SetBindGroup(render3d.LocalShadowGroup, spot.BindGroup()) +sceneMesh.Draw(mp) +mp.End() +``` + +For an omnidirectional point light, loop `face` from `0` to `render3d.PointShadowFaceCount-1`: + +```go +_ = point.Update(dev, pointLight) +for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { + fp := point.BeginFacePass(frame, face) + point.DrawCaster(dev, fp, blockerMesh, blockerModel) + fp.End() +} +``` diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 5321b79f..16986e1f 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -1092,3 +1092,44 @@ _ = renderer.Draw(pass, camBuf, lmMesh, worldMat, mat) - **图集变换**:`LightmapRef.UVScale` / `UVOffset` 是唯一生效的图集变换;`LightmapRef.Texture` 不携带 scale 与 offset,因此不要再用 `TransformTexCoords` 对它应用一次。数值来源见[烘焙光照贴图](3d-models-blender.md#烘焙光照贴图)。 - **纹理流式加载**:`BeginFrame` 会丢弃已关闭的光照贴图与反照率纹理对应的缓存绑定组,因此流式加载关卡或热重载光照贴图不会让缓存无限增长。 - **适用范围**:`LightmapRenderer` 是独立的渲染路径,结果为反照率乘以(烘焙光照加一盏 Lambert 光源)。它不支持金属度-粗糙度、法线、遮蔽或自发光贴图,也不读取 `LightRig`。把光照贴图作为间接光项接入 PBR 材质路径的工作见 [#752](https://github.com/nsgo-dev/game/issues/752)。 + +## 点光源与聚光灯阴影(`SpotShadowMap`、`PointShadowMap`) + +`SpotShadowMap` 与 `PointShadowMap` 为局部光源渲染纯深度 `FormatDepth32Float` 阴影贴图,并提供比较采样器与可移植 WGSL 辅助代码(`SpotShadowWGSL`、`PointShadowWGSL`),可在 Metal、Direct3D 11、OpenGL 3.3、WebGPU、WebGL 2、OpenGL ES 3.0 及软件 GPU 渲染器(包括 `nsgotest.NoGPUCompute`)上一致运行: + +- **聚光灯阴影(`SpotShadowMap`)**:根据 `SpotShadowLight.Position`、`Direction`、`OuterConeAngle`(`fovY = 2 * OuterConeAngle`)、`Near` 与 `Range` 构建正方形 `[0, 1]` 深度透视投影。`BeginShadowPass` 清除深度并绑定纯深度投射管线;`DrawCaster` 将每个投射体的 `(lightViewProj, model)` 写入 256 字节对齐的动态偏移 uniform 槽位,使单次通道内可连续绘制多个投射体(上限 `MaxCasters`)而不互相覆盖。 +- **全向点光源阴影(`PointShadowMap`)**:将 6 个 90° 立方体贴图面(`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`)打包进一张尺寸为 `(3 * FaceResolution) × (2 * FaceResolution)` 的 `3×2` `FormatDepth32Float` 2D 深度图集。对 `face` `0..5` 调用 `BeginFacePass(rec, face)` 时,第 0 面清除整个图集,第 1..5 面通过 `LoadLoad` 保留已渲染的瓦片,并将视口与裁剪矩形严格锁定到当前面瓦片内。在 `PointShadowWGSL` 中,`sample_point_shadow` 选取主轴方向面,以解析公式 `(far/(far-near))*(1 - near/axisDist)` 计算透视 NDC 深度(无需向片元着色器上传 6 个矩阵),并将每次采样钳制在 `[0.51/faceRes, 1 - 0.51/faceRes]` 内,确保 3×3 PCF 不会跨瓦片渗色。 +- **滤波、偏移与开箱即用管线**:支持 `LocalShadowFilterHard`(单次最近邻比较采样)与 `LocalShadowFilterPCF3x3`(9 次线性比较采样),并可配置 `DepthBias` 与 `NormalBias`。`BeginShadowPass` 与 `BeginFacePass` 同时接受 `*gpu.Encoder` 与 `*gpu.Frame`(`LocalShadowPassRecorder`)。可直接用 `NewSpotShadowLitPipeline` / `NewPointShadowLitPipeline` 搭配 `CameraGroup`(0)和 `LocalShadowGroup`(1)渲染带阴影光照,或在自定义片元着色器前拼接 `CameraWGSL` 与 `SpotShadowWGSL` / `PointShadowWGSL`。 +- **设备丢失恢复与 CPU 参考实现**:开启 `Retained: true` 后,设备丢失恢复时 NSGo 会自动重建深度渲染目标、比较采样器、uniform 缓冲、绑定组与深度管线(`Update` 与 `DrawCaster` 显式接收存活的 `*gpu.Device`)。纯 Go 评估函数 `EvaluateSpotShadow`、`EvaluateSpotLighting`、`PointShadowSelectFace`、`EvaluatePointShadow` 与 `EvaluatePointLighting` 与 WGSL 着色器逐项对应,便于解析校验,并附带参考渲染图 `render3d/testdata/golden/local_shadow_spot.png` 与 `local_shadow_point.png`(`UPDATE_GOLDEN=1` 可重写)。 + +```go +spot, err := render3d.NewSpotShadowMap(cx, dev, render3d.DefaultSpotShadowConfig()) +litPipe, err := render3d.NewSpotShadowLitPipeline(cx, dev, camBuf.Layout(), spot.Layout(), render3d.LocalShadowLitPipelineOptions{ + DepthFormat: gpu.FormatDepth24Plus, + CullMode: gpu.CullBack, +}) + +// 每帧在 OnFrame 中: +_ = spot.Update(dev, spotLight) +sp := spot.BeginShadowPass(frame) +spot.DrawCaster(dev, sp, pillarMesh, pillarModel) +sp.End() + +mp := frame.BeginRenderPass(gpu.RenderPassDesc{}) +mp.SetPipeline(litPipe) +mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) +mp.SetBindGroup(render3d.LocalShadowGroup, spot.BindGroup()) +sceneMesh.Draw(mp) +mp.End() +``` + +对于全向点光源,遍历 `face` 从 `0` 到 `render3d.PointShadowFaceCount-1`: + +```go +_ = point.Update(dev, pointLight) +for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { + fp := point.BeginFacePass(frame, face) + point.DrawCaster(dev, fp, blockerMesh, blockerModel) + fp.End() +} +``` diff --git a/packages/game/render3d/local_shadows.go b/packages/game/render3d/local_shadows.go new file mode 100644 index 00000000..cf05baba --- /dev/null +++ b/packages/game/render3d/local_shadows.go @@ -0,0 +1,1917 @@ +package render3d + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + + "github.com/nsgo-dev/game/packages/game/math3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" +) + +// ErrInvalidLocalShadow is wrapped by every validation error returned for spot +// or point light shadow maps and light configurations. +var ErrInvalidLocalShadow = errors.New("render3d: invalid local shadow") + +// LocalShadowGroup is the bind group index used by [SpotShadowWGSL], +// [PointShadowWGSL], [NewSpotShadowLitPipeline], and [NewPointShadowLitPipeline] +// (paired with [CameraGroup] at slot 0). Callers building custom pipelines may +// place [SpotShadowMap.Layout] or [PointShadowMap.Layout] at any group index. +const LocalShadowGroup = 1 + +// LocalShadowFilter selects how a local shadow map samples its depth texture. +type LocalShadowFilter uint8 + +const ( + // LocalShadowFilterHard performs a single nearest-neighbor depth comparison tap. + LocalShadowFilterHard LocalShadowFilter = iota + // LocalShadowFilterPCF3x3 performs a 3x3 percentage-closer filter using + // linear comparison taps clamped inside the shadow map or cube face tile. + LocalShadowFilterPCF3x3 +) + +// String returns the canonical filter name. +func (f LocalShadowFilter) String() string { + switch f { + case LocalShadowFilterHard: + return "hard" + case LocalShadowFilterPCF3x3: + return "pcf3x3" + default: + return fmt.Sprintf("LocalShadowFilter(%d)", f) + } +} + +const ( + // PointShadowFaceCount is the number of cube faces rendered for a point light. + PointShadowFaceCount = 6 + // PointShadowAtlasCols is the horizontal tile count of the 3x2 point shadow atlas. + PointShadowAtlasCols = 3 + // PointShadowAtlasRows is the vertical tile count of the 3x2 point shadow atlas. + PointShadowAtlasRows = 2 + + // SpotShadowUniformSize is the byte size of [SpotShadowUniform.Encode] and + // the WGSL SpotShadow uniform block (144 bytes, 16-byte aligned). + SpotShadowUniformSize = 64 + 5*16 + + // PointShadowUniformSize is the byte size of [PointShadowUniform.Encode] and + // the WGSL PointShadow uniform block (64 bytes, 16-byte aligned). + PointShadowUniformSize = 4 * 16 + + localShadowCasterSlotStride = 256 // WebGPU / Metal / D3D11 MinUniformBufferAlignment + localShadowCasterDataSize = 128 // light_view_proj (64) + model (64) + + defaultSpotShadowResolution = 1024 + defaultPointShadowResolution = 512 + defaultLocalShadowDepthBias = 0.0015 + defaultLocalShadowNormalBias = 0.02 + defaultSpotMaxCasters = 256 + defaultPointMaxCasters = 1024 +) + +// localShadowDepthWGSL renders shadow caster geometry into a Depth32Float +// shadow map or atlas tile without a fragment stage. +const localShadowDepthWGSL = `struct LocalShadowCaster { + light_view_proj: mat4x4, + model: mat4x4, +} + +@group(0) @binding(0) var caster: LocalShadowCaster; + +struct VertexIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +} + +@vertex +fn vs_local_shadow_depth(in: VertexIn) -> @builtin(position) vec4 { + let world = caster.model * vec4(in.pos, 1.0); + return caster.light_view_proj * world; +} +` + +// SpotShadowWGSL declares the spot-light shadow uniform block, depth map, and +// comparison sampler at @group(1) bindings 0..2 together with portable WGSL +// helpers sample_spot_shadow and evaluate_spot_lighting. +// +// Prepend [CameraWGSL] and SpotShadowWGSL to a 3D fragment shader. The shader +// avoids exp/exp2/log2 and uses textureSampleCompareLevel so it runs identically +// across Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and +// NSGo's software GPU renderer. +const SpotShadowWGSL = `struct SpotShadow { + view_proj: mat4x4, + position_range: vec4, + direction_inner: vec4, + color_outer: vec4, + params: vec4, + ambient_near: vec4, +} + +@group(1) @binding(0) var spot_shadow: SpotShadow; +@group(1) @binding(1) var spot_shadow_map: texture_depth_2d; +@group(1) @binding(2) var spot_shadow_sampler: sampler_comparison; + +fn sample_spot_shadow(world_pos: vec3, world_normal: vec3) -> f32 { + let biased_pos = world_pos + world_normal * spot_shadow.params.y; + let clip = spot_shadow.view_proj * vec4(biased_pos, 1.0); + if (clip.w <= 0.00001) { + return 1.0; + } + let ndc = clip.xyz / clip.w; + let uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || ndc.z < 0.0 || ndc.z > 1.0) { + return 1.0; + } + let ref_depth = clamp(ndc.z - spot_shadow.params.x, 0.0, 1.0); + let inv_res = spot_shadow.params.z; + let pad = 0.51 * inv_res; + let uv_min = vec2(pad, pad); + let uv_max = vec2(1.0 - pad, 1.0 - pad); + if (spot_shadow.params.w < 0.5) { + return textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv, uv_min, uv_max), ref_depth); + } + var sum: f32 = 0.0; + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(-inv_res, -inv_res), uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(0.0, -inv_res), uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(inv_res, -inv_res), uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(-inv_res, 0.0), uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv, uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(inv_res, 0.0), uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(-inv_res, inv_res), uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(0.0, inv_res), uv_min, uv_max), ref_depth); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(inv_res, inv_res), uv_min, uv_max), ref_depth); + return sum / 9.0; +} + +fn evaluate_spot_lighting(world_pos: vec3, world_normal: vec3, albedo: vec3) -> vec3 { + let n = normalize(world_normal); + let to_light = spot_shadow.position_range.xyz - world_pos; + let dist = length(to_light); + let light_range = spot_shadow.position_range.w; + let ambient = albedo * spot_shadow.ambient_near.xyz; + if (dist <= 0.0001 || dist >= light_range) { + return ambient; + } + let l_dir = to_light / dist; + let ndl = max(dot(n, l_dir), 0.0); + if (ndl <= 0.0) { + return ambient; + } + let cos_theta = dot(-l_dir, spot_shadow.direction_inner.xyz); + let cos_outer = spot_shadow.color_outer.w; + let cos_inner = spot_shadow.direction_inner.w; + let cone_t = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 0.0001), 0.0, 1.0); + let cone = cone_t * cone_t * (3.0 - 2.0 * cone_t); + if (cone <= 0.0) { + return ambient; + } + let ratio = dist / light_range; + let r2 = ratio * ratio; + let win = clamp(1.0 - r2 * r2, 0.0, 1.0); + let atten = (win * win) / max(dist * dist, 0.01); + let vis = sample_spot_shadow(world_pos, n); + return ambient + albedo * spot_shadow.color_outer.xyz * (ndl * cone * atten * vis); +} +` + +// PointShadowWGSL declares the omnidirectional point-light shadow uniform block, +// 3x2 2D depth atlas, and comparison sampler at @group(1) bindings 0..2 together +// with portable WGSL helpers sample_point_shadow and evaluate_point_lighting. +// +// Prepend [CameraWGSL] and PointShadowWGSL to a 3D fragment shader. Because all +// six 90-degree cube faces live in a single 3x2 texture_depth_2d atlas with +// per-tile UV clamping, sampling and 3x3 PCF work portably across Metal, +// Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and NSGo's software +// GPU renderer without cubemap depth-attachment limitations. +const PointShadowWGSL = `struct PointShadow { + position_range: vec4, + color_near: vec4, + params: vec4, + ambient_pad: vec4, +} + +@group(1) @binding(0) var point_shadow: PointShadow; +@group(1) @binding(1) var point_shadow_map: texture_depth_2d; +@group(1) @binding(2) var point_shadow_sampler: sampler_comparison; + +fn point_shadow_tile_tap(col: f32, row: f32, local_uv: vec2, offset: vec2, pad: f32, ref_depth: f32) -> f32 { + let clamped = clamp(local_uv + offset, vec2(pad, pad), vec2(1.0 - pad, 1.0 - pad)); + let atlas_uv = vec2((col + clamped.x) / 3.0, (row + clamped.y) / 2.0); + return textureSampleCompareLevel(point_shadow_map, point_shadow_sampler, atlas_uv, ref_depth); +} + +fn sample_point_shadow(world_pos: vec3, world_normal: vec3) -> f32 { + let biased_pos = world_pos + world_normal * point_shadow.params.y; + let v = biased_pos - point_shadow.position_range.xyz; + let av = abs(v); + var col: f32 = 0.0; + var row: f32 = 0.0; + var x_view: f32 = 0.0; + var y_view: f32 = 0.0; + var axis_dist: f32 = 0.0; + if (av.x >= av.y && av.x >= av.z) { + if (v.x >= 0.0) { + col = 0.0; row = 0.0; + x_view = v.z; y_view = v.y; axis_dist = v.x; + } else { + col = 1.0; row = 0.0; + x_view = -v.z; y_view = v.y; axis_dist = -v.x; + } + } else if (av.y >= av.x && av.y >= av.z) { + if (v.y >= 0.0) { + col = 2.0; row = 0.0; + x_view = v.x; y_view = v.z; axis_dist = v.y; + } else { + col = 0.0; row = 1.0; + x_view = v.x; y_view = -v.z; axis_dist = -v.y; + } + } else { + if (v.z >= 0.0) { + col = 1.0; row = 1.0; + x_view = -v.x; y_view = v.y; axis_dist = v.z; + } else { + col = 2.0; row = 1.0; + x_view = v.x; y_view = v.y; axis_dist = -v.z; + } + } + let near_p = point_shadow.color_near.w; + let far_p = point_shadow.position_range.w; + if (axis_dist <= near_p || axis_dist >= far_p) { + return 1.0; + } + let local_uv = vec2((x_view / axis_dist) * 0.5 + 0.5, 0.5 - (y_view / axis_dist) * 0.5); + let ndc_z = (far_p / (far_p - near_p)) * (1.0 - near_p / axis_dist); + let ref_depth = clamp(ndc_z - point_shadow.params.x, 0.0, 1.0); + let inv_res = point_shadow.params.z; + let pad = 0.51 * inv_res; + if (point_shadow.params.w < 0.5) { + return point_shadow_tile_tap(col, row, local_uv, vec2(0.0, 0.0), pad, ref_depth); + } + var sum: f32 = 0.0; + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(-inv_res, -inv_res), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(0.0, -inv_res), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(inv_res, -inv_res), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(-inv_res, 0.0), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(0.0, 0.0), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(inv_res, 0.0), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(-inv_res, inv_res), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(0.0, inv_res), pad, ref_depth); + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(inv_res, inv_res), pad, ref_depth); + return sum / 9.0; +} + +fn evaluate_point_lighting(world_pos: vec3, world_normal: vec3, albedo: vec3) -> vec3 { + let n = normalize(world_normal); + let to_light = point_shadow.position_range.xyz - world_pos; + let dist = length(to_light); + let light_range = point_shadow.position_range.w; + let ambient = albedo * point_shadow.ambient_pad.xyz; + if (dist <= 0.0001 || dist >= light_range) { + return ambient; + } + let l_dir = to_light / dist; + let ndl = max(dot(n, l_dir), 0.0); + if (ndl <= 0.0) { + return ambient; + } + let ratio = dist / light_range; + let r2 = ratio * ratio; + let win = clamp(1.0 - r2 * r2, 0.0, 1.0); + let atten = (win * win) / max(dist * dist, 0.01); + let vis = sample_point_shadow(world_pos, n); + return ambient + albedo * point_shadow.color_near.xyz * (ndl * atten * vis); +} +` + +const spotShadowLitShaderWGSL = CameraWGSL + "\n" + SpotShadowWGSL + ` +struct VertexIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +} + +struct VertexOut { + @builtin(position) clip: vec4, + @location(0) world_pos: vec3, + @location(1) world_normal: vec3, +} + +@vertex +fn vs_spot_lit(in: VertexIn) -> VertexOut { + var out: VertexOut; + out.clip = camera.view_proj * vec4(in.pos, 1.0); + out.world_pos = in.pos; + out.world_normal = in.normal; + return out; +} + +@fragment +fn fs_spot_lit(in: VertexOut) -> @location(0) vec4 { + let color = evaluate_spot_lighting(in.world_pos, in.world_normal, vec3(0.85, 0.85, 0.85)); + return vec4(clamp(color, vec3(0.0), vec3(1.0)), 1.0); +} +` + +const pointShadowLitShaderWGSL = CameraWGSL + "\n" + PointShadowWGSL + ` +struct VertexIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +} + +struct VertexOut { + @builtin(position) clip: vec4, + @location(0) world_pos: vec3, + @location(1) world_normal: vec3, +} + +@vertex +fn vs_point_lit(in: VertexIn) -> VertexOut { + var out: VertexOut; + out.clip = camera.view_proj * vec4(in.pos, 1.0); + out.world_pos = in.pos; + out.world_normal = in.normal; + return out; +} + +@fragment +fn fs_point_lit(in: VertexOut) -> @location(0) vec4 { + let color = evaluate_point_lighting(in.world_pos, in.world_normal, vec3(0.85, 0.85, 0.85)); + return vec4(clamp(color, vec3(0.0), vec3(1.0)), 1.0); +} +` + +// SpotShadowConfig configures a perspective 2D [SpotShadowMap]. +type SpotShadowConfig struct { + // Resolution is the width and height of the square depth shadow map in texels. + // Zero defaults to 1024. + Resolution uint32 + // DepthBias subtracts a constant NDC [0, 1] bias during depth comparison to + // avoid shadow acne. Zero defaults to 0.0015 when using DefaultSpotShadowConfig; + // explicit zero disables constant depth bias. + DepthBias float32 + // NormalBias offsets the shaded world position along its surface normal before + // projecting into light space. + NormalBias float32 + // Filter selects hard single-tap or 3x3 PCF comparison sampling. + Filter LocalShadowFilter + // CullMode sets face culling for the shadow caster pass (default gpu.CullNone). + CullMode gpu.CullMode + // MaxCasters is the maximum number of DrawCaster calls per shadow pass. + // Zero defaults to 256. + MaxCasters uint32 + // Label names GPU resources in capture tools. + Label string + // Retained keeps resources across GPU device loss and restore. + Retained bool +} + +// DefaultSpotShadowConfig returns a ready-to-use 1024x1024 PCF 3x3 spot shadow configuration. +func DefaultSpotShadowConfig() SpotShadowConfig { + return SpotShadowConfig{ + Resolution: defaultSpotShadowResolution, + DepthBias: defaultLocalShadowDepthBias, + NormalBias: defaultLocalShadowNormalBias, + Filter: LocalShadowFilterPCF3x3, + CullMode: gpu.CullNone, + MaxCasters: defaultSpotMaxCasters, + } +} + +// Normalized returns a copy of c with zero Resolution and MaxCasters filled with defaults. +func (c SpotShadowConfig) Normalized() SpotShadowConfig { + if c.Resolution == 0 { + c.Resolution = defaultSpotShadowResolution + } + if c.MaxCasters == 0 { + c.MaxCasters = defaultSpotMaxCasters + } + return c +} + +// Validate checks that c's resolution, biases, filter, and cull mode are valid. +// Every error wraps [ErrInvalidLocalShadow]. +func (c SpotShadowConfig) Validate() error { + n := c.Normalized() + if !finite(n.DepthBias) || n.DepthBias < 0 { + return fmt.Errorf("%w: spot DepthBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.DepthBias) + } + if !finite(n.NormalBias) || n.NormalBias < 0 { + return fmt.Errorf("%w: spot NormalBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.NormalBias) + } + if !localShadowValidFilter(n.Filter) { + return fmt.Errorf("%w: invalid spot Filter %d", ErrInvalidLocalShadow, n.Filter) + } + if !localShadowValidCull(n.CullMode) { + return fmt.Errorf("%w: invalid spot CullMode %d", ErrInvalidLocalShadow, n.CullMode) + } + return nil +} + +// SpotShadowLight defines the spot light parameters used to build the perspective +// shadow projection and evaluate direct shadowed spot lighting. +type SpotShadowLight struct { + Position math3d.Vec3 + Direction math3d.Vec3 + Color math3d.Vec3 + Intensity float32 + Near float32 + Range float32 + InnerConeAngle float32 // half-angle in radians, 0 <= InnerConeAngle <= OuterConeAngle + OuterConeAngle float32 // half-angle in radians, 0 < OuterConeAngle < pi/2 + Ambient math3d.Vec3 +} + +// Validate checks that every vector and scalar is finite and within valid physical +// and perspective-projection bounds. Every error wraps [ErrInvalidLocalShadow]. +func (l SpotShadowLight) Validate() error { + if !finite3(l.Position) { + return fmt.Errorf("%w: spot Position is not finite", ErrInvalidLocalShadow) + } + if !finite3(l.Direction) || l.Direction.LenSq() < 1e-12 { + return fmt.Errorf("%w: spot Direction must be finite and non-zero", ErrInvalidLocalShadow) + } + if !finite3(l.Color) || l.Color.X < 0 || l.Color.Y < 0 || l.Color.Z < 0 { + return fmt.Errorf("%w: spot Color must be finite and non-negative", ErrInvalidLocalShadow) + } + if !finite3(l.Ambient) || l.Ambient.X < 0 || l.Ambient.Y < 0 || l.Ambient.Z < 0 { + return fmt.Errorf("%w: spot Ambient must be finite and non-negative", ErrInvalidLocalShadow) + } + if !finite(l.Intensity) || l.Intensity < 0 { + return fmt.Errorf("%w: spot Intensity %v must be finite and non-negative", ErrInvalidLocalShadow, l.Intensity) + } + if !finite(l.Near) || l.Near <= 0 { + return fmt.Errorf("%w: spot Near %v must be finite and positive", ErrInvalidLocalShadow, l.Near) + } + if !finite(l.Range) || l.Range <= l.Near { + return fmt.Errorf("%w: spot Range %v must be finite and greater than Near %v", ErrInvalidLocalShadow, l.Range, l.Near) + } + const maxOuter = float32(math.Pi/2 - 1e-3) + if !finite(l.OuterConeAngle) || l.OuterConeAngle <= 0 || l.OuterConeAngle >= maxOuter { + return fmt.Errorf("%w: spot OuterConeAngle %v must be in (0, pi/2)", ErrInvalidLocalShadow, l.OuterConeAngle) + } + if !finite(l.InnerConeAngle) || l.InnerConeAngle < 0 || l.InnerConeAngle > l.OuterConeAngle { + return fmt.Errorf("%w: spot InnerConeAngle %v must be in [0, OuterConeAngle %v]", ErrInvalidLocalShadow, l.InnerConeAngle, l.OuterConeAngle) + } + return nil +} + +// ViewMatrix returns the right-handed shadow view matrix looking from l.Position +// along l.Direction. +func (l SpotShadowLight) ViewMatrix() math3d.Mat4 { + dir := l.Direction.Norm() + up := math3d.Vec3Up() + if localShadowAbs(dir.Y) > 0.99 { + up = math3d.Vec3{Z: 1} + } + return math3d.LookAt(l.Position, l.Position.Add(dir), up) +} + +// ProjMatrix returns the [0, 1] NDC depth perspective projection matching +// fovY = 2 * l.OuterConeAngle, aspect = 1, near = l.Near, and far = l.Range. +func (l SpotShadowLight) ProjMatrix() math3d.Mat4 { + return math3d.Perspective(2*l.OuterConeAngle, 1.0, l.Near, l.Range) +} + +// ViewProj returns ProjMatrix().Mul(ViewMatrix()). +func (l SpotShadowLight) ViewProj() math3d.Mat4 { + return l.ProjMatrix().Mul(l.ViewMatrix()) +} + +// SpotShadowUniform is the packed uniform data matching the WGSL SpotShadow block +// declared by [SpotShadowWGSL]. +type SpotShadowUniform struct { + ViewProj math3d.Mat4 + Position math3d.Vec3 + Range float32 + Direction math3d.Vec3 + CosInner float32 + ColorIntensity math3d.Vec3 + CosOuter float32 + DepthBias float32 + NormalBias float32 + InvResolution float32 + FilterMode float32 + Ambient math3d.Vec3 + Near float32 +} + +// NewSpotShadowUniform computes the uniform data for light and cfg. +func NewSpotShadowUniform(light SpotShadowLight, cfg SpotShadowConfig) SpotShadowUniform { + n := cfg.Normalized() + dir := light.Direction.Norm() + filterMode := float32(0) + if n.Filter == LocalShadowFilterPCF3x3 { + filterMode = 1 + } + return SpotShadowUniform{ + ViewProj: light.ViewProj(), + Position: light.Position, + Range: light.Range, + Direction: dir, + CosInner: float32(math.Cos(float64(light.InnerConeAngle))), + ColorIntensity: light.Color.Scale(light.Intensity), + CosOuter: float32(math.Cos(float64(light.OuterConeAngle))), + DepthBias: n.DepthBias, + NormalBias: n.NormalBias, + InvResolution: 1.0 / float32(n.Resolution), + FilterMode: filterMode, + Ambient: light.Ambient, + Near: light.Near, + } +} + +// Encode writes u into dst in the little-endian layout declared by [SpotShadowWGSL] +// and returns dst[:SpotShadowUniformSize]. It allocates nothing and panics if +// len(dst) < SpotShadowUniformSize. +func (u *SpotShadowUniform) Encode(dst []byte) []byte { + if len(dst) < SpotShadowUniformSize { + panic("render3d: SpotShadowUniform.Encode: dst shorter than SpotShadowUniformSize") + } + dst = dst[:SpotShadowUniformSize] + off := 0 + putF := func(v float32) { + binary.LittleEndian.PutUint32(dst[off:], math.Float32bits(v)) + off += 4 + } + for _, f := range u.ViewProj { + putF(f) + } + putF(u.Position.X) + putF(u.Position.Y) + putF(u.Position.Z) + putF(u.Range) + putF(u.Direction.X) + putF(u.Direction.Y) + putF(u.Direction.Z) + putF(u.CosInner) + putF(u.ColorIntensity.X) + putF(u.ColorIntensity.Y) + putF(u.ColorIntensity.Z) + putF(u.CosOuter) + putF(u.DepthBias) + putF(u.NormalBias) + putF(u.InvResolution) + putF(u.FilterMode) + putF(u.Ambient.X) + putF(u.Ambient.Y) + putF(u.Ambient.Z) + putF(u.Near) + return dst +} + +// SpotShadowMap manages a depth-only perspective 2D shadow map, its depth caster +// pipeline, and its sampling bind group for a spot light on a [gpu.Device]. +type SpotShadowMap struct { + cfg SpotShadowConfig + rt *gpu.RenderTarget + sampler *gpu.Sampler + uniformBuf *gpu.Buffer + casterBuf *gpu.Buffer + layout *gpu.BindGroupLayout + bindGroup *gpu.BindGroup + casterLayout *gpu.BindGroupLayout + casterGroup *gpu.BindGroup + depthPipe *gpu.Pipeline + uniforms SpotShadowUniform + casterSlot uint32 + uniformBytes [SpotShadowUniformSize]byte + casterScratch [localShadowCasterDataSize]byte +} + +// NewSpotShadowMap creates a depth-only perspective spot shadow map and its GPU +// resources scoped to cx. Invalid configuration returns an error wrapping +// [ErrInvalidLocalShadow]; device errors are returned as [gpu.Error]. +func NewSpotShadowMap(cx *core.Scope, dev *gpu.Device, cfg SpotShadowConfig) (*SpotShadowMap, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + n := cfg.Normalized() + maxDim := dev.Limits().MaxTextureDimension2D + if maxDim > 0 && n.Resolution > maxDim { + return nil, fmt.Errorf("%w: spot resolution %d exceeds MaxTextureDimension2D %d", ErrInvalidLocalShadow, n.Resolution, maxDim) + } + + label := n.Label + if label == "" { + label = "render3d.spot_shadow" + } + + var closers []interface{ Close() error } + fail := func(err error) (*SpotShadowMap, error) { + for i := len(closers) - 1; i >= 0; i-- { + if closers[i] != nil { + _ = closers[i].Close() + } + } + return nil, err + } + + rt, err := dev.CreateRenderTarget(cx, gpu.RenderTargetDesc{ + Label: label + ".depth", + Width: n.Resolution, + Height: n.Resolution, + DepthFormat: gpu.FormatDepth32Float, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, rt) + + filterMode := gpu.FilterNearest + if n.Filter == LocalShadowFilterPCF3x3 { + filterMode = gpu.FilterLinear + } + samp, err := dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".sampler", + MinFilter: filterMode, + MagFilter: filterMode, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Compare: gpu.CompareLessEqual, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, samp) + + uniformBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".uniform", + Size: SpotShadowUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, uniformBuf) + + casterBufSize := uint64(n.MaxCasters) * localShadowCasterSlotStride + casterBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".casters", + Size: casterBufSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, casterBuf) + + layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + ".layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex | gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingComparisonSampler}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, layout) + + bindGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + ".bind_group", + Layout: layout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: uniformBuf, Size: SpotShadowUniformSize}, + {Binding: 1, Texture: rt.Depth}, + {Binding: 2, Sampler: samp}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, bindGroup) + + casterLayout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + ".caster_layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex, Type: gpu.BindingUniform, HasDynamicOffset: true}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, casterLayout) + + casterGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + ".caster_group", + Layout: casterLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: casterBuf, Offset: 0, Size: localShadowCasterDataSize}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, casterGroup) + + depthMod, err := gpu.CompileWGSL(localShadowDepthWGSL) + if err != nil { + return fail(err) + } + depthPipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ + Label: label + ".depth_pipe", + Vertex: gpu.ShaderStage{Module: depthMod, EntryPoint: "vs_local_shadow_depth"}, + Layouts: []*gpu.BindGroupLayout{casterLayout}, + VertexBuffers: []gpu.VertexBufferLayout{MeshVertexLayout()}, + Primitive: gpu.PrimitiveState{ + Topology: gpu.TopologyTriangleList, + FrontFace: gpu.FrontCCW, + CullMode: n.CullMode, + }, + DepthStencil: &gpu.DepthStencilState{ + Format: gpu.FormatDepth32Float, + DepthWrite: true, + DepthCompare: gpu.CompareLess, + }, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + + return &SpotShadowMap{ + cfg: n, + rt: rt, + sampler: samp, + uniformBuf: uniformBuf, + casterBuf: casterBuf, + layout: layout, + bindGroup: bindGroup, + casterLayout: casterLayout, + casterGroup: casterGroup, + depthPipe: depthPipe, + }, nil +} + +// Update validates light, updates the spot shadow projection and uniforms, and +// writes the uniform buffer on dev without heap allocations. +func (s *SpotShadowMap) Update(dev *gpu.Device, light SpotShadowLight) error { + if s == nil || !s.Valid() { + return fmt.Errorf("%w: spot shadow map is not valid", ErrInvalidLocalShadow) + } + if err := light.Validate(); err != nil { + return err + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + s.uniforms = NewSpotShadowUniform(light, s.cfg) + dev.WriteBuffer(s.uniformBuf, 0, s.uniforms.Encode(s.uniformBytes[:])) + return nil +} + +// Uniforms returns the last spot shadow uniform data written via [SpotShadowMap.Update]. +func (s *SpotShadowMap) Uniforms() SpotShadowUniform { + if s == nil { + return SpotShadowUniform{} + } + return s.uniforms +} + +// ViewProj returns the spot light's perspective view-projection matrix. +func (s *SpotShadowMap) ViewProj() math3d.Mat4 { + if s == nil { + return math3d.Mat4Identity() + } + return s.uniforms.ViewProj +} + +// Config returns the normalized [SpotShadowConfig]. +func (s *SpotShadowMap) Config() SpotShadowConfig { + if s == nil { + return SpotShadowConfig{} + } + return s.cfg +} + +// RenderTarget returns the underlying depth-only [gpu.RenderTarget]. +func (s *SpotShadowMap) RenderTarget() *gpu.RenderTarget { + if s == nil { + return nil + } + return s.rt +} + +// DepthTexture returns the underlying Depth32Float [gpu.Texture]. +func (s *SpotShadowMap) DepthTexture() *gpu.Texture { + if s == nil || s.rt == nil { + return nil + } + return s.rt.Depth +} + +// Sampler returns the comparison [gpu.Sampler] bound in [SpotShadowMap.BindGroup]. +func (s *SpotShadowMap) Sampler() *gpu.Sampler { + if s == nil { + return nil + } + return s.sampler +} + +// Layout returns the bind group layout for sampling this spot shadow map +// (binding 0: SpotShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison). +func (s *SpotShadowMap) Layout() *gpu.BindGroupLayout { + if s == nil { + return nil + } + return s.layout +} + +// BindGroup returns the bind group to set at [LocalShadowGroup] (or any group slot +// matching [SpotShadowMap.Layout]) during the lit render pass. +func (s *SpotShadowMap) BindGroup() *gpu.BindGroup { + if s == nil { + return nil + } + return s.bindGroup +} + +// ByteSize returns the GPU memory held by the depth texture and uniform buffers. +func (s *SpotShadowMap) ByteSize() uint64 { + if s == nil { + return 0 + } + depthBytes := uint64(s.cfg.Resolution) * uint64(s.cfg.Resolution) * 4 + return depthBytes + s.uniformBuf.Size() + s.casterBuf.Size() +} + +// Valid reports whether all underlying GPU resources are open and live. +func (s *SpotShadowMap) Valid() bool { + return s != nil && + s.rt != nil && s.rt.Valid() && + s.sampler != nil && s.sampler.Valid() && + s.uniformBuf != nil && s.uniformBuf.Valid() && + s.casterBuf != nil && s.casterBuf.Valid() && + s.layout != nil && s.layout.Valid() && + s.bindGroup != nil && s.bindGroup.Valid() && + s.casterLayout != nil && s.casterLayout.Valid() && + s.casterGroup != nil && s.casterGroup.Valid() && + s.depthPipe != nil && s.depthPipe.Valid() +} + +// LocalShadowPassRecorder is satisfied by both [*gpu.Encoder] and [*gpu.Frame], +// allowing [SpotShadowMap.BeginShadowPass] and [PointShadowMap.BeginFacePass] +// to record shadow passes both inside [gpu.ViewProps.OnFrame] and on standalone +// command encoders. +type LocalShadowPassRecorder interface { + BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass +} + +// BeginShadowPass begins a depth-only render pass targeting the spot shadow map, +// clears depth to 1.0, sets the full viewport/scissor, binds the depth pipeline, +// and resets the caster dynamic-offset slot counter. +func (s *SpotShadowMap) BeginShadowPass(rec LocalShadowPassRecorder) *gpu.RenderPass { + if s == nil || rec == nil || !s.Valid() { + return nil + } + s.casterSlot = 0 + pass := rec.BeginRenderPass(gpu.RenderPassDesc{ + Label: s.cfg.Label + ".pass", + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: s.rt.Depth, + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) + res := s.cfg.Resolution + pass.SetViewport(0, 0, float32(res), float32(res), 0, 1) + pass.SetScissor(0, 0, int32(res), int32(res)) + pass.SetPipeline(s.depthPipe) + return pass +} + +// DrawCaster records a shadow caster draw for mesh transformed by model inside +// a pass started by [SpotShadowMap.BeginShadowPass]. Each call uses a distinct +// 256-byte aligned dynamic-offset uniform slot so multiple casters can be drawn +// in one pass without overwriting earlier transforms. +func (s *SpotShadowMap) DrawCaster(dev *gpu.Device, pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) { + if s == nil || dev == nil || pass == nil || !s.Valid() || !mesh.Valid() { + return + } + if s.casterSlot >= s.cfg.MaxCasters { + return + } + offset := uint64(s.casterSlot) * localShadowCasterSlotStride + s.casterSlot++ + encodeLocalShadowCaster(s.casterScratch[:], s.uniforms.ViewProj, model) + dev.WriteBuffer(s.casterBuf, offset, s.casterScratch[:]) + pass.SetBindGroup(0, s.casterGroup, uint32(offset)) + mesh.Draw(pass) +} + +// Close releases all GPU resources owned by s. It is safe to call on a nil +// receiver or more than once. +func (s *SpotShadowMap) Close() error { + if s == nil { + return nil + } + var err error + for _, c := range []interface{ Close() error }{ + s.depthPipe, + s.casterGroup, + s.casterLayout, + s.bindGroup, + s.layout, + s.casterBuf, + s.uniformBuf, + s.sampler, + s.rt, + } { + if c != nil { + err = errors.Join(err, c.Close()) + } + } + return err +} + +// PointShadowConfig configures an omnidirectional 3x2 depth-atlas [PointShadowMap]. +type PointShadowConfig struct { + // FaceResolution is the width and height of one cube face tile in texels. + // The 3x2 depth atlas has size (3 * FaceResolution) x (2 * FaceResolution). + // Zero defaults to 512. + FaceResolution uint32 + // DepthBias subtracts a constant NDC [0, 1] bias during depth comparison. + DepthBias float32 + // NormalBias offsets the shaded world position along its surface normal before + // selecting the cube face and comparing depth. + NormalBias float32 + // Filter selects hard single-tap or 3x3 PCF comparison sampling. + Filter LocalShadowFilter + // CullMode sets face culling for the shadow caster passes (default gpu.CullNone). + CullMode gpu.CullMode + // MaxCasters is the total maximum DrawCaster calls across all 6 faces per frame. + // Zero defaults to 1024. + MaxCasters uint32 + // Label names GPU resources in capture tools. + Label string + // Retained keeps resources across GPU device loss and restore. + Retained bool +} + +// DefaultPointShadowConfig returns a ready-to-use 512x512-per-face PCF 3x3 point +// shadow configuration. +func DefaultPointShadowConfig() PointShadowConfig { + return PointShadowConfig{ + FaceResolution: defaultPointShadowResolution, + DepthBias: defaultLocalShadowDepthBias, + NormalBias: defaultLocalShadowNormalBias, + Filter: LocalShadowFilterPCF3x3, + CullMode: gpu.CullNone, + MaxCasters: defaultPointMaxCasters, + } +} + +// Normalized returns a copy of c with zero FaceResolution and MaxCasters filled +// with defaults. +func (c PointShadowConfig) Normalized() PointShadowConfig { + if c.FaceResolution == 0 { + c.FaceResolution = defaultPointShadowResolution + } + if c.MaxCasters == 0 { + c.MaxCasters = defaultPointMaxCasters + } + return c +} + +// AtlasSize returns the width and height in texels of the 3x2 2D depth atlas. +func (c PointShadowConfig) AtlasSize() (width, height uint32) { + n := c.Normalized() + return n.FaceResolution * PointShadowAtlasCols, n.FaceResolution * PointShadowAtlasRows +} + +// Validate checks that c's resolution, biases, filter, and cull mode are valid. +// Every error wraps [ErrInvalidLocalShadow]. +func (c PointShadowConfig) Validate() error { + n := c.Normalized() + if uint64(n.FaceResolution)*PointShadowAtlasCols > math.MaxUint32 { + return fmt.Errorf("%w: point FaceResolution %d overflows atlas dimensions", ErrInvalidLocalShadow, n.FaceResolution) + } + if !finite(n.DepthBias) || n.DepthBias < 0 { + return fmt.Errorf("%w: point DepthBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.DepthBias) + } + if !finite(n.NormalBias) || n.NormalBias < 0 { + return fmt.Errorf("%w: point NormalBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.NormalBias) + } + if !localShadowValidFilter(n.Filter) { + return fmt.Errorf("%w: invalid point Filter %d", ErrInvalidLocalShadow, n.Filter) + } + if !localShadowValidCull(n.CullMode) { + return fmt.Errorf("%w: invalid point CullMode %d", ErrInvalidLocalShadow, n.CullMode) + } + return nil +} + +// PointShadowLight defines the point light parameters used to build the six +// 90-degree cube-face shadow projections and evaluate omnidirectional lighting. +type PointShadowLight struct { + Position math3d.Vec3 + Color math3d.Vec3 + Intensity float32 + Near float32 + Range float32 + Ambient math3d.Vec3 +} + +// Validate checks that all fields are finite and within valid projection bounds. +// Every error wraps [ErrInvalidLocalShadow]. +func (l PointShadowLight) Validate() error { + if !finite3(l.Position) { + return fmt.Errorf("%w: point Position is not finite", ErrInvalidLocalShadow) + } + if !finite3(l.Color) || l.Color.X < 0 || l.Color.Y < 0 || l.Color.Z < 0 { + return fmt.Errorf("%w: point Color must be finite and non-negative", ErrInvalidLocalShadow) + } + if !finite3(l.Ambient) || l.Ambient.X < 0 || l.Ambient.Y < 0 || l.Ambient.Z < 0 { + return fmt.Errorf("%w: point Ambient must be finite and non-negative", ErrInvalidLocalShadow) + } + if !finite(l.Intensity) || l.Intensity < 0 { + return fmt.Errorf("%w: point Intensity %v must be finite and non-negative", ErrInvalidLocalShadow, l.Intensity) + } + if !finite(l.Near) || l.Near <= 0 { + return fmt.Errorf("%w: point Near %v must be finite and positive", ErrInvalidLocalShadow, l.Near) + } + if !finite(l.Range) || l.Range <= l.Near { + return fmt.Errorf("%w: point Range %v must be finite and greater than Near %v", ErrInvalidLocalShadow, l.Range, l.Near) + } + return nil +} + +// pointFaceBasis holds the canonical right-handed forward and up vectors for +// cube faces 0..5 matching [gpu.CubeFacePosX]..[gpu.CubeFaceNegZ] and +// [PointShadowWGSL]. +var pointFaceBasis = [PointShadowFaceCount]struct { + forward math3d.Vec3 + up math3d.Vec3 +}{ + gpu.CubeFacePosX: {forward: math3d.Vec3{X: 1}, up: math3d.Vec3{Y: 1}}, + gpu.CubeFaceNegX: {forward: math3d.Vec3{X: -1}, up: math3d.Vec3{Y: 1}}, + gpu.CubeFacePosY: {forward: math3d.Vec3{Y: 1}, up: math3d.Vec3{Z: 1}}, + gpu.CubeFaceNegY: {forward: math3d.Vec3{Y: -1}, up: math3d.Vec3{Z: -1}}, + gpu.CubeFacePosZ: {forward: math3d.Vec3{Z: 1}, up: math3d.Vec3{Y: 1}}, + gpu.CubeFaceNegZ: {forward: math3d.Vec3{Z: -1}, up: math3d.Vec3{Y: 1}}, +} + +// FaceViewMatrix returns the right-handed view matrix for cube face (0..5). +// Out-of-range face indices clamp to [gpu.CubeFacePosX]. +func (l PointShadowLight) FaceViewMatrix(face gpu.CubeFace) math3d.Mat4 { + if face >= PointShadowFaceCount { + face = gpu.CubeFacePosX + } + b := pointFaceBasis[face] + return math3d.LookAt(l.Position, l.Position.Add(b.forward), b.up) +} + +// FaceProjMatrix returns the 90-degree square [0, 1] depth perspective projection +// shared by all six cube faces of the point light. +func (l PointShadowLight) FaceProjMatrix() math3d.Mat4 { + return math3d.Perspective(math.Pi/2, 1.0, l.Near, l.Range) +} + +// FaceViewProj returns FaceProjMatrix().Mul(FaceViewMatrix(face)). +func (l PointShadowLight) FaceViewProj(face gpu.CubeFace) math3d.Mat4 { + return l.FaceProjMatrix().Mul(l.FaceViewMatrix(face)) +} + +// PointShadowUniform is the packed uniform data matching the WGSL PointShadow +// block declared by [PointShadowWGSL]. +type PointShadowUniform struct { + Position math3d.Vec3 + Range float32 + ColorIntensity math3d.Vec3 + Near float32 + DepthBias float32 + NormalBias float32 + InvFaceResolution float32 + FilterMode float32 + Ambient math3d.Vec3 +} + +// NewPointShadowUniform computes the uniform data for light and cfg. +func NewPointShadowUniform(light PointShadowLight, cfg PointShadowConfig) PointShadowUniform { + n := cfg.Normalized() + filterMode := float32(0) + if n.Filter == LocalShadowFilterPCF3x3 { + filterMode = 1 + } + return PointShadowUniform{ + Position: light.Position, + Range: light.Range, + ColorIntensity: light.Color.Scale(light.Intensity), + Near: light.Near, + DepthBias: n.DepthBias, + NormalBias: n.NormalBias, + InvFaceResolution: 1.0 / float32(n.FaceResolution), + FilterMode: filterMode, + Ambient: light.Ambient, + } +} + +// Encode writes u into dst in the little-endian layout declared by [PointShadowWGSL] +// and returns dst[:PointShadowUniformSize]. It allocates nothing and panics if +// len(dst) < PointShadowUniformSize. +func (u *PointShadowUniform) Encode(dst []byte) []byte { + if len(dst) < PointShadowUniformSize { + panic("render3d: PointShadowUniform.Encode: dst shorter than PointShadowUniformSize") + } + dst = dst[:PointShadowUniformSize] + off := 0 + putF := func(v float32) { + binary.LittleEndian.PutUint32(dst[off:], math.Float32bits(v)) + off += 4 + } + putF(u.Position.X) + putF(u.Position.Y) + putF(u.Position.Z) + putF(u.Range) + putF(u.ColorIntensity.X) + putF(u.ColorIntensity.Y) + putF(u.ColorIntensity.Z) + putF(u.Near) + putF(u.DepthBias) + putF(u.NormalBias) + putF(u.InvFaceResolution) + putF(u.FilterMode) + putF(u.Ambient.X) + putF(u.Ambient.Y) + putF(u.Ambient.Z) + putF(0) + return dst +} + +// PointShadowMap manages a 3x2 2D depth-atlas omnidirectional shadow map, its +// caster pipeline, and its sampling bind group for a point light on a [gpu.Device]. +type PointShadowMap struct { + cfg PointShadowConfig + atlasW uint32 + atlasH uint32 + rt *gpu.RenderTarget + sampler *gpu.Sampler + uniformBuf *gpu.Buffer + casterBuf *gpu.Buffer + layout *gpu.BindGroupLayout + bindGroup *gpu.BindGroup + casterLayout *gpu.BindGroupLayout + casterGroup *gpu.BindGroup + depthPipe *gpu.Pipeline + uniforms PointShadowUniform + faceViewProj [PointShadowFaceCount]math3d.Mat4 + activeFace gpu.CubeFace + casterSlot uint32 + uniformBytes [PointShadowUniformSize]byte + casterScratch [localShadowCasterDataSize]byte +} + +// NewPointShadowMap creates a 3x2 Depth32Float atlas point shadow map and its +// GPU resources scoped to cx. Invalid configuration returns an error wrapping +// [ErrInvalidLocalShadow]; device errors are returned as [gpu.Error]. +func NewPointShadowMap(cx *core.Scope, dev *gpu.Device, cfg PointShadowConfig) (*PointShadowMap, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + n := cfg.Normalized() + atlasW, atlasH := n.AtlasSize() + maxDim := dev.Limits().MaxTextureDimension2D + if maxDim > 0 && (atlasW > maxDim || atlasH > maxDim) { + return nil, fmt.Errorf("%w: point shadow atlas %dx%d exceeds MaxTextureDimension2D %d", ErrInvalidLocalShadow, atlasW, atlasH, maxDim) + } + + label := n.Label + if label == "" { + label = "render3d.point_shadow" + } + + var closers []interface{ Close() error } + fail := func(err error) (*PointShadowMap, error) { + for i := len(closers) - 1; i >= 0; i-- { + if closers[i] != nil { + _ = closers[i].Close() + } + } + return nil, err + } + + rt, err := dev.CreateRenderTarget(cx, gpu.RenderTargetDesc{ + Label: label + ".atlas", + Width: atlasW, + Height: atlasH, + DepthFormat: gpu.FormatDepth32Float, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, rt) + + filterMode := gpu.FilterNearest + if n.Filter == LocalShadowFilterPCF3x3 { + filterMode = gpu.FilterLinear + } + samp, err := dev.CreateSampler(cx, gpu.SamplerDesc{ + Label: label + ".sampler", + MinFilter: filterMode, + MagFilter: filterMode, + AddressU: gpu.AddressClampToEdge, + AddressV: gpu.AddressClampToEdge, + AddressW: gpu.AddressClampToEdge, + Compare: gpu.CompareLessEqual, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, samp) + + uniformBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".uniform", + Size: PointShadowUniformSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, uniformBuf) + + casterBufSize := uint64(n.MaxCasters) * localShadowCasterSlotStride + casterBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + ".casters", + Size: casterBufSize, + Usage: gpu.UsageUniform | gpu.UsageCopyDst, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + closers = append(closers, casterBuf) + + layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + ".layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex | gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingComparisonSampler}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, layout) + + bindGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + ".bind_group", + Layout: layout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: uniformBuf, Size: PointShadowUniformSize}, + {Binding: 1, Texture: rt.Depth}, + {Binding: 2, Sampler: samp}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, bindGroup) + + casterLayout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + Label: label + ".caster_layout", + Entries: []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex, Type: gpu.BindingUniform, HasDynamicOffset: true}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, casterLayout) + + casterGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + Label: label + ".caster_group", + Layout: casterLayout, + Entries: []gpu.BindGroupEntry{ + {Binding: 0, Buffer: casterBuf, Offset: 0, Size: localShadowCasterDataSize}, + }, + }) + if err != nil { + return fail(err) + } + closers = append(closers, casterGroup) + + depthMod, err := gpu.CompileWGSL(localShadowDepthWGSL) + if err != nil { + return fail(err) + } + depthPipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ + Label: label + ".depth_pipe", + Vertex: gpu.ShaderStage{Module: depthMod, EntryPoint: "vs_local_shadow_depth"}, + Layouts: []*gpu.BindGroupLayout{casterLayout}, + VertexBuffers: []gpu.VertexBufferLayout{MeshVertexLayout()}, + Primitive: gpu.PrimitiveState{ + Topology: gpu.TopologyTriangleList, + FrontFace: gpu.FrontCCW, + CullMode: n.CullMode, + }, + DepthStencil: &gpu.DepthStencilState{ + Format: gpu.FormatDepth32Float, + DepthWrite: true, + DepthCompare: gpu.CompareLess, + }, + Retained: n.Retained, + }) + if err != nil { + return fail(err) + } + + return &PointShadowMap{ + cfg: n, + atlasW: atlasW, + atlasH: atlasH, + rt: rt, + sampler: samp, + uniformBuf: uniformBuf, + casterBuf: casterBuf, + layout: layout, + bindGroup: bindGroup, + casterLayout: casterLayout, + casterGroup: casterGroup, + depthPipe: depthPipe, + }, nil +} + +// Update validates light, computes all six cube-face view-projection matrices, +// and uploads the point shadow uniform buffer on dev without heap allocations. +func (p *PointShadowMap) Update(dev *gpu.Device, light PointShadowLight) error { + if p == nil || !p.Valid() { + return fmt.Errorf("%w: point shadow map is not valid", ErrInvalidLocalShadow) + } + if err := light.Validate(); err != nil { + return err + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + proj := light.FaceProjMatrix() + for face := range gpu.CubeFace(PointShadowFaceCount) { + p.faceViewProj[face] = proj.Mul(light.FaceViewMatrix(face)) + } + p.uniforms = NewPointShadowUniform(light, p.cfg) + dev.WriteBuffer(p.uniformBuf, 0, p.uniforms.Encode(p.uniformBytes[:])) + return nil +} + +// Uniforms returns the last point shadow uniform data written via [PointShadowMap.Update]. +func (p *PointShadowMap) Uniforms() PointShadowUniform { + if p == nil { + return PointShadowUniform{} + } + return p.uniforms +} + +// FaceViewProj returns the 90-degree perspective view-projection matrix for cube +// face (0..5). Returns identity for a nil receiver or out-of-range face. +func (p *PointShadowMap) FaceViewProj(face gpu.CubeFace) math3d.Mat4 { + if p == nil || face >= PointShadowFaceCount { + return math3d.Mat4Identity() + } + return p.faceViewProj[face] +} + +// FaceViewport returns the pixel rectangle (x, y, width, height) inside the 3x2 +// depth atlas assigned to cube face (0..5). +func (p *PointShadowMap) FaceViewport(face gpu.CubeFace) (x, y, width, height uint32) { + if p == nil || face >= PointShadowFaceCount { + return 0, 0, 0, 0 + } + col := face % PointShadowAtlasCols + row := face / PointShadowAtlasCols + res := p.cfg.FaceResolution + return col * res, row * res, res, res +} + +// Config returns the normalized [PointShadowConfig]. +func (p *PointShadowMap) Config() PointShadowConfig { + if p == nil { + return PointShadowConfig{} + } + return p.cfg +} + +// AtlasWidth returns the full width of the 3x2 depth atlas (3 * FaceResolution). +func (p *PointShadowMap) AtlasWidth() uint32 { + if p == nil { + return 0 + } + return p.atlasW +} + +// AtlasHeight returns the full height of the 3x2 depth atlas (2 * FaceResolution). +func (p *PointShadowMap) AtlasHeight() uint32 { + if p == nil { + return 0 + } + return p.atlasH +} + +// RenderTarget returns the underlying depth-only 3x2 atlas [gpu.RenderTarget]. +func (p *PointShadowMap) RenderTarget() *gpu.RenderTarget { + if p == nil { + return nil + } + return p.rt +} + +// DepthTexture returns the underlying Depth32Float 3x2 atlas [gpu.Texture]. +func (p *PointShadowMap) DepthTexture() *gpu.Texture { + if p == nil || p.rt == nil { + return nil + } + return p.rt.Depth +} + +// Sampler returns the comparison [gpu.Sampler] bound in [PointShadowMap.BindGroup]. +func (p *PointShadowMap) Sampler() *gpu.Sampler { + if p == nil { + return nil + } + return p.sampler +} + +// Layout returns the bind group layout for sampling this point shadow map +// (binding 0: PointShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison). +func (p *PointShadowMap) Layout() *gpu.BindGroupLayout { + if p == nil { + return nil + } + return p.layout +} + +// BindGroup returns the bind group to set at [LocalShadowGroup] (or any group slot +// matching [PointShadowMap.Layout]) during the lit render pass. +func (p *PointShadowMap) BindGroup() *gpu.BindGroup { + if p == nil { + return nil + } + return p.bindGroup +} + +// ByteSize returns the GPU memory held by the 3x2 depth atlas and uniform buffers. +func (p *PointShadowMap) ByteSize() uint64 { + if p == nil { + return 0 + } + depthBytes := uint64(p.atlasW) * uint64(p.atlasH) * 4 + return depthBytes + p.uniformBuf.Size() + p.casterBuf.Size() +} + +// Valid reports whether all underlying GPU resources are open and live. +func (p *PointShadowMap) Valid() bool { + return p != nil && + p.rt != nil && p.rt.Valid() && + p.sampler != nil && p.sampler.Valid() && + p.uniformBuf != nil && p.uniformBuf.Valid() && + p.casterBuf != nil && p.casterBuf.Valid() && + p.layout != nil && p.layout.Valid() && + p.bindGroup != nil && p.bindGroup.Valid() && + p.casterLayout != nil && p.casterLayout.Valid() && + p.casterGroup != nil && p.casterGroup.Valid() && + p.depthPipe != nil && p.depthPipe.Valid() +} + +// BeginFacePass begins a depth-only render pass targeting cube face (0..5) in the +// 3x2 depth atlas. Calling with face == 0 clears the entire atlas depth buffer to +// 1.0 and resets the caster dynamic-offset slot counter; faces 1..5 preserve +// previously rendered tiles using [gpu.LoadLoad]. Viewport and scissor are locked +// to the face's tile so geometry cannot bleed into neighboring faces. +func (p *PointShadowMap) BeginFacePass(rec LocalShadowPassRecorder, face gpu.CubeFace) *gpu.RenderPass { + if p == nil || rec == nil || !p.Valid() || face >= PointShadowFaceCount { + return nil + } + loadOp := gpu.LoadLoad + if face == 0 { + loadOp = gpu.LoadClear + p.casterSlot = 0 + } + p.activeFace = face + pass := rec.BeginRenderPass(gpu.RenderPassDesc{ + Label: fmt.Sprintf("%s.face%d", p.cfg.Label, face), + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: p.rt.Depth, + DepthLoadOp: loadOp, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) + vx, vy, vw, vh := p.FaceViewport(face) + pass.SetViewport(float32(vx), float32(vy), float32(vw), float32(vh), 0, 1) + pass.SetScissor(int32(vx), int32(vy), int32(vw), int32(vh)) + pass.SetPipeline(p.depthPipe) + return pass +} + +// DrawCaster records a shadow caster draw for mesh transformed by model into the +// currently active cube face pass started by [PointShadowMap.BeginFacePass]. +func (p *PointShadowMap) DrawCaster(dev *gpu.Device, pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) { + if p == nil || dev == nil || pass == nil || !p.Valid() || !mesh.Valid() { + return + } + if p.casterSlot >= p.cfg.MaxCasters { + return + } + offset := uint64(p.casterSlot) * localShadowCasterSlotStride + p.casterSlot++ + encodeLocalShadowCaster(p.casterScratch[:], p.faceViewProj[p.activeFace], model) + dev.WriteBuffer(p.casterBuf, offset, p.casterScratch[:]) + pass.SetBindGroup(0, p.casterGroup, uint32(offset)) + mesh.Draw(pass) +} + +// Close releases all GPU resources owned by p. It is safe to call on a nil +// receiver or more than once. +func (p *PointShadowMap) Close() error { + if p == nil { + return nil + } + var err error + for _, c := range []interface{ Close() error }{ + p.depthPipe, + p.casterGroup, + p.casterLayout, + p.bindGroup, + p.layout, + p.casterBuf, + p.uniformBuf, + p.sampler, + p.rt, + } { + if c != nil { + err = errors.Join(err, c.Close()) + } + } + return err +} + +// LocalShadowLitPipelineOptions configures [NewSpotShadowLitPipeline] and +// [NewPointShadowLitPipeline]. +type LocalShadowLitPipelineOptions struct { + Label string + ColorFormat gpu.TextureFormat // defaults to dev.SurfaceFormat() + DepthFormat gpu.TextureFormat // optional; when non-zero enables depth testing with CompareLess + CullMode gpu.CullMode // default gpu.CullNone + Retained bool +} + +// NewSpotShadowLitPipeline compiles [SpotShadowWGSL] with [CameraWGSL] and +// builds a ready-to-use shadowed spot-lighting pipeline consuming +// [MeshVertexLayout] with cameraLayout at [CameraGroup] (0) and spotLayout at +// [LocalShadowGroup] (1). +func NewSpotShadowLitPipeline(cx *core.Scope, dev *gpu.Device, cameraLayout, spotLayout *gpu.BindGroupLayout, opts LocalShadowLitPipelineOptions) (*gpu.Pipeline, error) { + return newLocalShadowLitPipeline(cx, dev, cameraLayout, spotLayout, opts, spotShadowLitShaderWGSL, "vs_spot_lit", "fs_spot_lit", "render3d.spot_shadow_lit") +} + +// NewPointShadowLitPipeline compiles [PointShadowWGSL] with [CameraWGSL] and +// builds a ready-to-use shadowed omnidirectional point-lighting pipeline +// consuming [MeshVertexLayout] with cameraLayout at [CameraGroup] (0) and +// pointLayout at [LocalShadowGroup] (1). +func NewPointShadowLitPipeline(cx *core.Scope, dev *gpu.Device, cameraLayout, pointLayout *gpu.BindGroupLayout, opts LocalShadowLitPipelineOptions) (*gpu.Pipeline, error) { + return newLocalShadowLitPipeline(cx, dev, cameraLayout, pointLayout, opts, pointShadowLitShaderWGSL, "vs_point_lit", "fs_point_lit", "render3d.point_shadow_lit") +} + +func newLocalShadowLitPipeline( + cx *core.Scope, + dev *gpu.Device, + cameraLayout, shadowLayout *gpu.BindGroupLayout, + opts LocalShadowLitPipelineOptions, + wgslSrc, vsEntry, fsEntry, defaultLabel string, +) (*gpu.Pipeline, error) { + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if cameraLayout == nil || !cameraLayout.Valid() || shadowLayout == nil || !shadowLayout.Valid() { + return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: invalid bind group layout"} + } + if !localShadowValidCull(opts.CullMode) { + return nil, fmt.Errorf("%w: invalid CullMode %d", ErrInvalidLocalShadow, opts.CullMode) + } + mod, err := gpu.CompileWGSL(wgslSrc) + if err != nil { + return nil, err + } + colorFmt := opts.ColorFormat + if colorFmt == gpu.FormatUndefined { + colorFmt = dev.SurfaceFormat() + } + label := opts.Label + if label == "" { + label = defaultLabel + } + desc := gpu.PipelineDesc{ + Label: label, + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: vsEntry}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: fsEntry}, + Layouts: []*gpu.BindGroupLayout{cameraLayout, shadowLayout}, + VertexBuffers: []gpu.VertexBufferLayout{MeshVertexLayout()}, + Primitive: gpu.PrimitiveState{ + Topology: gpu.TopologyTriangleList, + FrontFace: gpu.FrontCCW, + CullMode: opts.CullMode, + }, + Targets: []gpu.ColorTargetState{{Format: colorFmt, WriteMask: gpu.ColorWriteAll}}, + Retained: opts.Retained, + } + if opts.DepthFormat != gpu.FormatUndefined { + desc.DepthStencil = &gpu.DepthStencilState{ + Format: opts.DepthFormat, + DepthWrite: true, + DepthCompare: gpu.CompareLess, + } + } + return dev.CreatePipeline(cx, desc) +} + +// DecodeDepth32Float decodes tightly packed little-endian float32 depth texels +// returned by [gpu.Device.ReadTexture] on a [gpu.FormatDepth32Float] texture. +func DecodeDepth32Float(raw []byte) []float32 { + n := len(raw) / 4 + out := make([]float32, n) + for i := range n { + out[i] = math.Float32frombits(binary.LittleEndian.Uint32(raw[i*4:])) + } + return out +} + +// EvaluateSpotShadow evaluates the CPU reference shadow visibility in [0, 1] +// matching sample_spot_shadow in [SpotShadowWGSL] against a row-major +// res x res Depth32Float buffer. +func EvaluateSpotShadow(u SpotShadowUniform, depth []float32, res uint32, worldPos, worldNormal math3d.Vec3) float32 { + if res == 0 || len(depth) < int(res)*int(res) { + return 1 + } + n := worldNormal + if n.LenSq() > 1e-12 { + n = n.Norm() + } + biased := worldPos.Add(n.Scale(u.NormalBias)) + clip := u.ViewProj.MulVec4(biased.Vec4(1)) + if clip.W <= 1e-5 { + return 1 + } + invW := 1 / clip.W + ndcX, ndcY, ndcZ := clip.X*invW, clip.Y*invW, clip.Z*invW + uvX := ndcX*0.5 + 0.5 + uvY := 0.5 - ndcY*0.5 + if uvX < 0 || uvX > 1 || uvY < 0 || uvY > 1 || ndcZ < 0 || ndcZ > 1 { + return 1 + } + refDepth := localShadowClamp(ndcZ-u.DepthBias, 0, 1) + invRes := u.InvResolution + if invRes <= 0 { + invRes = 1 / float32(res) + } + pad := 0.51 * invRes + w, h := int(res), int(res) + if u.FilterMode < 0.5 { + cu := localShadowClamp(uvX, pad, 1-pad) + cv := localShadowClamp(uvY, pad, 1-pad) + return localShadowCompareDepth2D(depth, w, h, cu, cv, refDepth, false) + } + var sum float32 + for dy := -1; dy <= 1; dy++ { + for dx := -1; dx <= 1; dx++ { + cu := localShadowClamp(uvX+float32(dx)*invRes, pad, 1-pad) + cv := localShadowClamp(uvY+float32(dy)*invRes, pad, 1-pad) + sum += localShadowCompareDepth2D(depth, w, h, cu, cv, refDepth, true) + } + } + return sum / 9.0 +} + +// EvaluateSpotLighting evaluates the CPU reference shadowed spot lighting color +// matching evaluate_spot_lighting in [SpotShadowWGSL]. +func EvaluateSpotLighting(u SpotShadowUniform, depth []float32, res uint32, worldPos, worldNormal, albedo math3d.Vec3) math3d.Vec3 { + n := worldNormal.Norm() + toLight := u.Position.Sub(worldPos) + dist := toLight.Len() + ambient := math3d.Vec3{X: albedo.X * u.Ambient.X, Y: albedo.Y * u.Ambient.Y, Z: albedo.Z * u.Ambient.Z} + if dist <= 1e-4 || dist >= u.Range { + return ambient + } + lDir := toLight.Scale(1 / dist) + ndl := max(n.Dot(lDir), float32(0)) + if ndl <= 0 { + return ambient + } + cosTheta := lDir.Neg().Dot(u.Direction) + coneT := localShadowClamp((cosTheta-u.CosOuter)/max(u.CosInner-u.CosOuter, float32(1e-4)), 0, 1) + cone := coneT * coneT * (3 - 2*coneT) + if cone <= 0 { + return ambient + } + ratio := dist / u.Range + r2 := ratio * ratio + win := localShadowClamp(1-r2*r2, 0, 1) + atten := (win * win) / max(dist*dist, float32(0.01)) + vis := EvaluateSpotShadow(u, depth, res, worldPos, n) + k := ndl * cone * atten * vis + return math3d.Vec3{ + X: ambient.X + albedo.X*u.ColorIntensity.X*k, + Y: ambient.Y + albedo.Y*u.ColorIntensity.Y*k, + Z: ambient.Z + albedo.Z*u.ColorIntensity.Z*k, + } +} + +// PointShadowSelectFace projects light-to-fragment vector v onto the dominant +// cube face (0..5) and returns the face index, face-local UV in [0, 1]^2, and +// positive major-axis distance matching [PointShadowWGSL]. +func PointShadowSelectFace(v math3d.Vec3) (face gpu.CubeFace, localU, localV, axisDist float32) { + ax, ay, az := localShadowAbs(v.X), localShadowAbs(v.Y), localShadowAbs(v.Z) + var xView, yView float32 + switch { + case ax >= ay && ax >= az: + if v.X >= 0 { + face = gpu.CubeFacePosX + xView, yView, axisDist = v.Z, v.Y, v.X + } else { + face = gpu.CubeFaceNegX + xView, yView, axisDist = -v.Z, v.Y, -v.X + } + case ay >= ax && ay >= az: + if v.Y >= 0 { + face = gpu.CubeFacePosY + xView, yView, axisDist = v.X, v.Z, v.Y + } else { + face = gpu.CubeFaceNegY + xView, yView, axisDist = v.X, -v.Z, -v.Y + } + default: + if v.Z >= 0 { + face = gpu.CubeFacePosZ + xView, yView, axisDist = -v.X, v.Y, v.Z + } else { + face = gpu.CubeFaceNegZ + xView, yView, axisDist = v.X, v.Y, -v.Z + } + } + if axisDist <= 1e-12 { + return face, 0.5, 0.5, 0 + } + localU = (xView/axisDist)*0.5 + 0.5 + localV = 0.5 - (yView/axisDist)*0.5 + return face, localU, localV, axisDist +} + +// EvaluatePointShadow evaluates the CPU reference omnidirectional shadow +// visibility in [0, 1] matching sample_point_shadow in [PointShadowWGSL] against +// a row-major (3*faceRes) x (2*faceRes) Depth32Float atlas buffer. +func EvaluatePointShadow(u PointShadowUniform, atlasDepth []float32, faceRes uint32, worldPos, worldNormal math3d.Vec3) float32 { + atlasW := int(faceRes * PointShadowAtlasCols) + atlasH := int(faceRes * PointShadowAtlasRows) + if faceRes == 0 || len(atlasDepth) < atlasW*atlasH { + return 1 + } + n := worldNormal + if n.LenSq() > 1e-12 { + n = n.Norm() + } + biased := worldPos.Add(n.Scale(u.NormalBias)) + v := biased.Sub(u.Position) + face, localU, localV, axisDist := PointShadowSelectFace(v) + if axisDist <= u.Near || axisDist >= u.Range { + return 1 + } + ndcZ := (u.Range / (u.Range - u.Near)) * (1.0 - u.Near/axisDist) + refDepth := localShadowClamp(ndcZ-u.DepthBias, 0, 1) + invRes := u.InvFaceResolution + if invRes <= 0 { + invRes = 1 / float32(faceRes) + } + pad := 0.51 * invRes + col := float32(face % PointShadowAtlasCols) + row := float32(face / PointShadowAtlasCols) + + tap := func(du, dv float32, linear bool) float32 { + cu := localShadowClamp(localU+du, pad, 1-pad) + cv := localShadowClamp(localV+dv, pad, 1-pad) + au := (col + cu) / float32(PointShadowAtlasCols) + av := (row + cv) / float32(PointShadowAtlasRows) + return localShadowCompareDepth2D(atlasDepth, atlasW, atlasH, au, av, refDepth, linear) + } + + if u.FilterMode < 0.5 { + return tap(0, 0, false) + } + var sum float32 + for dy := -1; dy <= 1; dy++ { + for dx := -1; dx <= 1; dx++ { + sum += tap(float32(dx)*invRes, float32(dy)*invRes, true) + } + } + return sum / 9.0 +} + +// EvaluatePointLighting evaluates the CPU reference shadowed point lighting color +// matching evaluate_point_lighting in [PointShadowWGSL]. +func EvaluatePointLighting(u PointShadowUniform, atlasDepth []float32, faceRes uint32, worldPos, worldNormal, albedo math3d.Vec3) math3d.Vec3 { + n := worldNormal.Norm() + toLight := u.Position.Sub(worldPos) + dist := toLight.Len() + ambient := math3d.Vec3{X: albedo.X * u.Ambient.X, Y: albedo.Y * u.Ambient.Y, Z: albedo.Z * u.Ambient.Z} + if dist <= 1e-4 || dist >= u.Range { + return ambient + } + lDir := toLight.Scale(1 / dist) + ndl := max(n.Dot(lDir), float32(0)) + if ndl <= 0 { + return ambient + } + ratio := dist / u.Range + r2 := ratio * ratio + win := localShadowClamp(1-r2*r2, 0, 1) + atten := (win * win) / max(dist*dist, float32(0.01)) + vis := EvaluatePointShadow(u, atlasDepth, faceRes, worldPos, n) + k := ndl * atten * vis + return math3d.Vec3{ + X: ambient.X + albedo.X*u.ColorIntensity.X*k, + Y: ambient.Y + albedo.Y*u.ColorIntensity.Y*k, + Z: ambient.Z + albedo.Z*u.ColorIntensity.Z*k, + } +} + +func localShadowCompareDepth2D(depth []float32, w, h int, u, v, refDepth float32, linear bool) float32 { + u = localShadowClamp(u, 0, 1) + v = localShadowClamp(v, 0, 1) + cmpTexel := func(x, y int) float32 { + x = min(max(x, 0), w-1) + y = min(max(y, 0), h-1) + if refDepth <= depth[y*w+x] { + return 1 + } + return 0 + } + if !linear { + ix := int(math.Floor(float64(u * float32(w)))) + iy := int(math.Floor(float64(v * float32(h)))) + return cmpTexel(ix, iy) + } + fx := u*float32(w) - 0.5 + fy := v*float32(h) - 0.5 + x0 := int(math.Floor(float64(fx))) + y0 := int(math.Floor(float64(fy))) + tx := fx - float32(x0) + ty := fy - float32(y0) + c00 := cmpTexel(x0, y0) + c10 := cmpTexel(x0+1, y0) + c01 := cmpTexel(x0, y0+1) + c11 := cmpTexel(x0+1, y0+1) + top := c00*(1-tx) + c10*tx + bot := c01*(1-tx) + c11*tx + return top*(1-ty) + bot*ty +} + +func encodeLocalShadowCaster(dst []byte, lightVP, model math3d.Mat4) { + off := 0 + for _, m := range [...]*math3d.Mat4{&lightVP, &model} { + for _, f := range m { + binary.LittleEndian.PutUint32(dst[off:], math.Float32bits(f)) + off += 4 + } + } +} + +func localShadowValidFilter(f LocalShadowFilter) bool { + return f == LocalShadowFilterHard || f == LocalShadowFilterPCF3x3 +} + +func localShadowValidCull(c gpu.CullMode) bool { + return c == gpu.CullNone || c == gpu.CullFront || c == gpu.CullBack +} + +func localShadowAbs(v float32) float32 { + if v < 0 { + return -v + } + return v +} + +func localShadowClamp(v, lo, hi float32) float32 { + if v < lo { + return lo + } + if v > hi { + return hi + } + return v +} diff --git a/packages/game/render3d/local_shadows_test.go b/packages/game/render3d/local_shadows_test.go new file mode 100644 index 00000000..decc3457 --- /dev/null +++ b/packages/game/render3d/local_shadows_test.go @@ -0,0 +1,1214 @@ +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 ( + localShadowTestWidth = 128 + localShadowTestHeight = 96 +) + +var ( + localShadowTestClear = core.RGB(0x0c1018) + localShadowTestAlbedo = math3d.Vec3{X: 0.85, Y: 0.85, Z: 0.85} +) + +// localShadowTestSubdividedQuad builds a grid of subdivisions x subdivisions +// triangles spanning center +/- uAxis*halfU +/- vAxis*halfV with outward normal. +// Subdividing large floors and walls ensures triangles never straddle w <= 0 of +// a point light's cube-face frustum in the software rasterizer. +func localShadowTestSubdividedQuad(center, uAxis, vAxis, normal math3d.Vec3, halfU, halfV float32, subdiv int) render3d.Mesh { + var m render3d.Mesh + n := normal.Norm() + for iy := range subdiv { + v0 := -halfV + 2*halfV*float32(iy)/float32(subdiv) + v1 := -halfV + 2*halfV*float32(iy+1)/float32(subdiv) + for ix := range subdiv { + u0 := -halfU + 2*halfU*float32(ix)/float32(subdiv) + u1 := -halfU + 2*halfU*float32(ix+1)/float32(subdiv) + p00 := center.Add(uAxis.Scale(u0)).Add(vAxis.Scale(v0)) + p10 := center.Add(uAxis.Scale(u1)).Add(vAxis.Scale(v0)) + p11 := center.Add(uAxis.Scale(u1)).Add(vAxis.Scale(v1)) + p01 := center.Add(uAxis.Scale(u0)).Add(vAxis.Scale(v1)) + base := uint32(len(m.Positions)) + m.Positions = append(m.Positions, p00, p10, p11, p01) + m.Normals = append(m.Normals, n, n, n, n) + m.UVs = append(m.UVs, + math3d.Vec2{X: 0, Y: 0}, + math3d.Vec2{X: 1, Y: 0}, + math3d.Vec2{X: 1, Y: 1}, + math3d.Vec2{X: 0, Y: 1}, + ) + m.Indices = append(m.Indices, base, base+1, base+2, base, base+2, base+3) + } + } + return m +} + +// localShadowTestBoxMesh builds a CCW outward-facing box mesh centered at center +// with half extents half. +func localShadowTestBoxMesh(center, half math3d.Vec3) render3d.Mesh { + type face struct{ n, u, v math3d.Vec3 } + faces := [...]face{ + {math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}, math3d.Vec3{Y: 1}}, + {math3d.Vec3{X: -1}, math3d.Vec3{Z: 1}, math3d.Vec3{Y: 1}}, + {math3d.Vec3{Y: 1}, math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}}, + {math3d.Vec3{Y: -1}, math3d.Vec3{X: 1}, math3d.Vec3{Z: 1}}, + {math3d.Vec3{Z: 1}, math3d.Vec3{X: 1}, math3d.Vec3{Y: 1}}, + {math3d.Vec3{Z: -1}, math3d.Vec3{X: -1}, math3d.Vec3{Y: 1}}, + } + var m render3d.Mesh + for _, f := range faces { + base := uint32(len(m.Positions)) + c := center.Add(math3d.Vec3{X: f.n.X * half.X, Y: f.n.Y * half.Y, Z: f.n.Z * half.Z}) + u := math3d.Vec3{X: f.u.X * half.X, Y: f.u.Y * half.Y, Z: f.u.Z * half.Z} + v := math3d.Vec3{X: f.v.X * half.X, Y: f.v.Y * half.Y, Z: f.v.Z * half.Z} + m.Positions = append(m.Positions, + c.Sub(u).Sub(v), + c.Add(u).Sub(v), + c.Add(u).Add(v), + c.Sub(u).Add(v), + ) + m.Normals = append(m.Normals, f.n, f.n, f.n, f.n) + m.UVs = append(m.UVs, + math3d.Vec2{X: 0, Y: 1}, + math3d.Vec2{X: 1, Y: 1}, + math3d.Vec2{X: 1, Y: 0}, + math3d.Vec2{X: 0, Y: 0}, + ) + m.Indices = append(m.Indices, base, base+1, base+2, base, base+2, base+3) + } + return m +} + +func localShadowTestMergeMeshes(meshes ...render3d.Mesh) render3d.Mesh { + var out render3d.Mesh + for _, m := range meshes { + base := uint32(len(out.Positions)) + out.Positions = append(out.Positions, m.Positions...) + out.Normals = append(out.Normals, m.Normals...) + out.UVs = append(out.UVs, m.UVs...) + for _, idx := range m.Indices { + out.Indices = append(out.Indices, base+idx) + } + } + return out +} + +func localShadowTestReadDepth(t *testing.T, dev *gpu.Device, tex *gpu.Texture, w, h uint32) []float32 { + t.Helper() + var raw []byte + dev.ReadTexture(tex, gpu.TextureRegion{Width: w, Height: h}, func(b []byte, err error) { + if err != nil { + t.Fatalf("ReadTexture depth: %v", err) + } + raw = append([]byte(nil), b...) + }) + if len(raw) != int(w*h*4) { + t.Fatalf("depth readback len = %d, want %d", len(raw), w*h*4) + } + return render3d.DecodeDepth32Float(raw) +} + +func localShadowTestColorToRGB8(c math3d.Vec3) [3]uint8 { + conv := func(v float32) uint8 { + if v <= 0 { + return 0 + } + if v >= 1 { + return 255 + } + return uint8(v*255.0 + 0.5) + } + return [3]uint8{conv(c.X), conv(c.Y), conv(c.Z)} +} + +func localShadowTestAssertGolden(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 golden %s: %v (UPDATE_GOLDEN=1 writes it)", path, err) + } + if !want.Bounds().Eq(got.Bounds()) { + t.Fatalf("%s: bounds %v, want %v", name, got.Bounds(), want.Bounds()) + } + const channelTol = 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 > channelTol || d < -channelTol { + 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 golden (limit %d); wrote got & diff to %s", name, far, limit, dir) + } +} + +func localShadowTestSamplePixel(img *image.RGBA, cam *scene3d.Camera, world math3d.Vec3) ([3]uint8, int, int, bool) { + b := img.Bounds() + s, _, ok := cam.WorldToScreen(world, float32(b.Dx()), float32(b.Dy())) + if !ok { + return [3]uint8{}, 0, 0, false + } + x, y := int(s.X), int(s.Y) + if x < 0 || x >= b.Dx() || y < 0 || y >= b.Dy() { + return [3]uint8{}, x, y, false + } + c := img.RGBAAt(x, y) + return [3]uint8{c.R, c.G, c.B}, x, y, true +} + +func localShadowTestRGBDiff(a, b [3]uint8) int { + maxD := 0 + for i := range 3 { + d := int(a[i]) - int(b[i]) + if d < 0 { + d = -d + } + if d > maxD { + maxD = d + } + } + return maxD +} + +func TestSpotShadowConfigAndLightValidation(t *testing.T) { + def := render3d.DefaultSpotShadowConfig() + if err := def.Validate(); err != nil { + t.Fatalf("DefaultSpotShadowConfig.Validate: %v", err) + } + if def.Resolution != 1024 || def.Filter != render3d.LocalShadowFilterPCF3x3 { + t.Fatalf("unexpected default spot config: %+v", def) + } + if render3d.LocalShadowFilterHard.String() != "hard" || render3d.LocalShadowFilterPCF3x3.String() != "pcf3x3" { + t.Fatalf("unexpected filter string names") + } + + badConfigs := []render3d.SpotShadowConfig{ + {DepthBias: -0.01}, + {DepthBias: float32(math.NaN())}, + {NormalBias: -0.1}, + {NormalBias: float32(math.Inf(1))}, + {Filter: render3d.LocalShadowFilter(99)}, + {CullMode: gpu.CullMode(99)}, + } + for i, cfg := range badConfigs { + if err := cfg.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Errorf("badConfigs[%d] = %v, want ErrInvalidLocalShadow", i, err) + } + } + + if _, err := render3d.NewSpotShadowMap(nil, nil, def); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("nil device error = %v, want gpu.ErrDeviceLost", err) + } + + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + if _, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{ + Resolution: dev.Limits().MaxTextureDimension2D + 1, + }); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("oversized spot resolution error = %v, want ErrInvalidLocalShadow", err) + } + + validLight := render3d.SpotShadowLight{ + Position: math3d.Vec3{Y: 4}, + Direction: math3d.Vec3{Y: -1}, + Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, + Intensity: 10, + Near: 0.1, + Range: 12, + InnerConeAngle: math3d.DegToRad(20), + OuterConeAngle: math3d.DegToRad(35), + } + if err := validLight.Validate(); err != nil { + t.Fatalf("valid spot light failed: %v", err) + } + + badLights := []render3d.SpotShadowLight{ + {Position: math3d.Vec3{X: float32(math.NaN())}, Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, + {Direction: math3d.Vec3Zero(), Near: 0.1, Range: 10, OuterConeAngle: 0.5}, + {Direction: math3d.Vec3{Y: -1}, Color: math3d.Vec3{X: -1}, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, + {Direction: math3d.Vec3{Y: -1}, Ambient: math3d.Vec3{Y: -0.1}, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, + {Direction: math3d.Vec3{Y: -1}, Intensity: -1, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, + {Direction: math3d.Vec3{Y: -1}, Near: 0, Range: 10, OuterConeAngle: 0.5}, + {Direction: math3d.Vec3{Y: -1}, Near: 5, Range: 5, OuterConeAngle: 0.5}, + {Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, OuterConeAngle: 0}, + {Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, OuterConeAngle: math.Pi / 2}, + {Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, InnerConeAngle: 0.6, OuterConeAngle: 0.5}, + } + for i, l := range badLights { + if err := l.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Errorf("badLights[%d] = %v, want ErrInvalidLocalShadow", i, err) + } + } +} + +func TestPointShadowConfigAndLightValidation(t *testing.T) { + def := render3d.DefaultPointShadowConfig() + if err := def.Validate(); err != nil { + t.Fatalf("DefaultPointShadowConfig.Validate: %v", err) + } + aw, ah := def.AtlasSize() + if aw != 3*512 || ah != 2*512 { + t.Fatalf("default atlas size = %dx%d, want %dx%d", aw, ah, 3*512, 2*512) + } + + badConfigs := []render3d.PointShadowConfig{ + {DepthBias: -0.01}, + {NormalBias: float32(math.NaN())}, + {Filter: render3d.LocalShadowFilter(42)}, + {CullMode: gpu.CullMode(42)}, + } + for i, cfg := range badConfigs { + if err := cfg.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Errorf("badConfigs[%d] = %v, want ErrInvalidLocalShadow", i, err) + } + } + + if _, err := render3d.NewPointShadowMap(nil, nil, def); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("nil device error = %v, want gpu.ErrDeviceLost", err) + } + + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + if _, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{ + FaceResolution: dev.Limits().MaxTextureDimension2D/3 + 1, + }); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("oversized point atlas error = %v, want ErrInvalidLocalShadow", err) + } + + badLights := []render3d.PointShadowLight{ + {Position: math3d.Vec3{Z: float32(math.Inf(-1))}, Near: 0.1, Range: 10}, + {Color: math3d.Vec3{Z: -1}, Near: 0.1, Range: 10}, + {Ambient: math3d.Vec3{X: -0.2}, Near: 0.1, Range: 10}, + {Intensity: -2, Near: 0.1, Range: 10}, + {Near: 0, Range: 10}, + {Near: 4, Range: 2}, + } + for i, l := range badLights { + if err := l.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Errorf("badPointLights[%d] = %v, want ErrInvalidLocalShadow", i, err) + } + } +} + +func TestSpotShadowUniformEncodeZeroAlloc(t *testing.T) { + light := render3d.SpotShadowLight{ + Position: math3d.Vec3{X: -2, Y: 4, Z: 3}, + Direction: math3d.Vec3{X: 1, Y: -2, Z: -1}, + Color: math3d.Vec3{X: 1, Y: 0.9, Z: 0.7}, + Intensity: 12, + Near: 0.2, + Range: 15, + InnerConeAngle: math3d.DegToRad(20), + OuterConeAngle: math3d.DegToRad(40), + Ambient: math3d.Vec3{X: 0.05, Y: 0.06, Z: 0.08}, + } + cfg := render3d.SpotShadowConfig{ + Resolution: 256, + DepthBias: 0.002, + NormalBias: 0.03, + Filter: render3d.LocalShadowFilterPCF3x3, + } + u := render3d.NewSpotShadowUniform(light, cfg) + var buf [render3d.SpotShadowUniformSize + 8]byte + out := u.Encode(buf[:]) + if len(out) != render3d.SpotShadowUniformSize || render3d.SpotShadowUniformSize != 144 { + t.Fatalf("encoded %d bytes, want 144", len(out)) + } + f := func(i int) float32 { return math.Float32frombits(binary.LittleEndian.Uint32(out[4*i:])) } + for i := range 16 { + if f(i) != u.ViewProj[i] { + t.Fatalf("ViewProj[%d] = %v, want %v", i, f(i), u.ViewProj[i]) + } + } + if f(16) != -2 || f(17) != 4 || f(18) != 3 || f(19) != 15 { + t.Fatalf("position_range mismatch: %v %v %v %v", f(16), f(17), f(18), f(19)) + } + if f(28) != 0.002 || f(29) != 0.03 || f(30) != 1.0/256.0 || f(31) != 1 { + t.Fatalf("params mismatch: %v %v %v %v", f(28), f(29), f(30), f(31)) + } + if f(32) != 0.05 || f(33) != 0.06 || f(34) != 0.08 || f(35) != 0.2 { + t.Fatalf("ambient_near mismatch: %v %v %v %v", f(32), f(33), f(34), f(35)) + } + + if allocs := testing.AllocsPerRun(100, func() { u.Encode(buf[:]) }); allocs != 0 { + t.Fatalf("SpotShadowUniform.Encode allocated %v times", allocs) + } + func() { + defer func() { + if recover() == nil { + t.Fatal("Encode with short slice did not panic") + } + }() + u.Encode(make([]byte, render3d.SpotShadowUniformSize-1)) + }() +} + +func TestPointShadowUniformEncodeZeroAlloc(t *testing.T) { + light := render3d.PointShadowLight{ + Position: math3d.Vec3{X: 1, Y: 2, Z: -3}, + Color: math3d.Vec3{X: 1, Y: 0.8, Z: 0.6}, + Intensity: 10, + Near: 0.15, + Range: 14, + Ambient: math3d.Vec3{X: 0.04, Y: 0.05, Z: 0.06}, + } + cfg := render3d.PointShadowConfig{ + FaceResolution: 128, + DepthBias: 0.001, + NormalBias: 0.02, + Filter: render3d.LocalShadowFilterHard, + } + u := render3d.NewPointShadowUniform(light, cfg) + var buf [render3d.PointShadowUniformSize + 8]byte + out := u.Encode(buf[:]) + if len(out) != render3d.PointShadowUniformSize || render3d.PointShadowUniformSize != 64 { + t.Fatalf("encoded %d bytes, want 64", len(out)) + } + f := func(i int) float32 { return math.Float32frombits(binary.LittleEndian.Uint32(out[4*i:])) } + if f(0) != 1 || f(1) != 2 || f(2) != -3 || f(3) != 14 { + t.Fatalf("position_range mismatch: %v %v %v %v", f(0), f(1), f(2), f(3)) + } + if f(4) != 10 || f(5) != 8 || f(6) != 6 || f(7) != 0.15 { + t.Fatalf("color_near mismatch: %v %v %v %v", f(4), f(5), f(6), f(7)) + } + if f(8) != 0.001 || f(9) != 0.02 || f(10) != 1.0/128.0 || f(11) != 0 { + t.Fatalf("params mismatch: %v %v %v %v", f(8), f(9), f(10), f(11)) + } + if f(12) != 0.04 || f(13) != 0.05 || f(14) != 0.06 || f(15) != 0 { + t.Fatalf("ambient_pad mismatch: %v %v %v %v", f(12), f(13), f(14), f(15)) + } + + if allocs := testing.AllocsPerRun(100, func() { u.Encode(buf[:]) }); allocs != 0 { + t.Fatalf("PointShadowUniform.Encode allocated %v times", allocs) + } + func() { + defer func() { + if recover() == nil { + t.Fatal("Encode with short slice did not panic") + } + }() + u.Encode(make([]byte, render3d.PointShadowUniformSize-1)) + }() +} + +func TestPointShadowFaceProjectionConsistency(t *testing.T) { + light := render3d.PointShadowLight{ + Position: math3d.Vec3{X: 1.5, Y: -0.75, Z: 2.25}, + Near: 0.2, + Range: 16.0, + } + probes := []struct { + offset math3d.Vec3 + wantFace gpu.CubeFace + }{ + {math3d.Vec3{X: 4.0, Y: 1.2, Z: -1.7}, gpu.CubeFacePosX}, + {math3d.Vec3{X: -3.5, Y: -0.8, Z: 1.4}, gpu.CubeFaceNegX}, + {math3d.Vec3{X: 0.9, Y: 5.0, Z: -1.3}, gpu.CubeFacePosY}, + {math3d.Vec3{X: -1.1, Y: -4.2, Z: 1.8}, gpu.CubeFaceNegY}, + {math3d.Vec3{X: 1.2, Y: -0.6, Z: 3.8}, gpu.CubeFacePosZ}, + {math3d.Vec3{X: -1.3, Y: 1.5, Z: -4.6}, gpu.CubeFaceNegZ}, + } + + for _, tc := range probes { + face, u, v, axisDist := render3d.PointShadowSelectFace(tc.offset) + if face != tc.wantFace { + t.Fatalf("offset %v selected face %d, want %d", tc.offset, face, tc.wantFace) + } + world := light.Position.Add(tc.offset) + vp := light.FaceViewProj(face) + clip := vp.MulVec4(world.Vec4(1)) + if clip.W <= 0 { + t.Fatalf("face %d clip.W = %v, want > 0", face, clip.W) + } + ndcX, ndcY, ndcZ := clip.X/clip.W, clip.Y/clip.W, clip.Z/clip.W + gotU := ndcX*0.5 + 0.5 + gotV := 0.5 - ndcY*0.5 + wantZ := (light.Range / (light.Range - light.Near)) * (1.0 - light.Near/axisDist) + if math.Abs(float64(u-gotU)) > 1e-5 || math.Abs(float64(v-gotV)) > 1e-5 { + t.Errorf("face %d UV mismatch: select=(%f,%f), proj=(%f,%f)", face, u, v, gotU, gotV) + } + if math.Abs(float64(ndcZ-wantZ)) > 1e-5 { + t.Errorf("face %d depth mismatch: analytic=%f, proj=%f", face, wantZ, ndcZ) + } + } +} + +func localShadowTestRenderSpotScene(t *testing.T, filter render3d.LocalShadowFilter) (*image.RGBA, []float32, render3d.SpotShadowUniform, *scene3d.Camera) { + t.Helper() + const shadowRes = 128 + + sr := gpu.NewSoftwareRenderer(localShadowTestWidth, localShadowTestHeight, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + camBuf, err := render3d.NewCameraBuffer(nil, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + t.Cleanup(func() { _ = camBuf.Close() }) + + spotShadow, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{ + Resolution: shadowRes, + DepthBias: 0.002, + NormalBias: 0.025, + Filter: filter, + Label: "test.spot", + }) + if err != nil { + t.Fatalf("NewSpotShadowMap: %v", err) + } + t.Cleanup(func() { _ = spotShadow.Close() }) + + litPipe, err := render3d.NewSpotShadowLitPipeline(nil, dev, camBuf.Layout(), spotShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ + DepthFormat: gpu.FormatDepth24Plus, + CullMode: gpu.CullBack, + }) + if err != nil { + t.Fatalf("NewSpotShadowLitPipeline: %v", err) + } + t.Cleanup(func() { _ = litPipe.Close() }) + + floorMesh := localShadowTestSubdividedQuad( + math3d.Vec3{Y: 0}, + math3d.Vec3{X: 1}, + math3d.Vec3{Z: -1}, + math3d.Vec3Up(), + 4.5, 4.5, 6, + ) + pillar1 := localShadowTestBoxMesh(math3d.Vec3{X: -0.2, Y: 0.9, Z: 0.1}, math3d.Vec3{X: 0.45, Y: 0.9, Z: 0.45}) + pillar2Local := localShadowTestBoxMesh(math3d.Vec3Zero(), math3d.Vec3{X: 0.35, Y: 0.65, Z: 0.35}) + pillar2Model := math3d.Translate(math3d.Vec3{X: 1.15, Y: 0.65, Z: -0.95}) + pillar2World := localShadowTestBoxMesh(math3d.Vec3{X: 1.15, Y: 0.65, Z: -0.95}, math3d.Vec3{X: 0.35, Y: 0.65, Z: 0.35}) + + gpuFloor, err := render3d.UploadMesh(nil, dev, floorMesh, render3d.MeshUpload{Label: "floor"}) + if err != nil { + t.Fatalf("UploadMesh floor: %v", err) + } + t.Cleanup(func() { _ = gpuFloor.Close() }) + gpuPillar1, err := render3d.UploadMesh(nil, dev, pillar1, render3d.MeshUpload{Label: "pillar1"}) + if err != nil { + t.Fatalf("UploadMesh pillar1: %v", err) + } + t.Cleanup(func() { _ = gpuPillar1.Close() }) + gpuPillar2Local, err := render3d.UploadMesh(nil, dev, pillar2Local, render3d.MeshUpload{Label: "pillar2-local"}) + if err != nil { + t.Fatalf("UploadMesh pillar2Local: %v", err) + } + t.Cleanup(func() { _ = gpuPillar2Local.Close() }) + gpuScene, err := render3d.UploadMesh(nil, dev, localShadowTestMergeMeshes(floorMesh, pillar1, pillar2World), render3d.MeshUpload{Label: "spot-scene"}) + if err != nil { + t.Fatalf("UploadMesh scene: %v", err) + } + t.Cleanup(func() { _ = gpuScene.Close() }) + + light := render3d.SpotShadowLight{ + Position: math3d.Vec3{X: -2.4, Y: 3.6, Z: 2.3}, + Direction: math3d.Vec3{X: 2.5, Y: -3.5, Z: -2.5}.Norm(), + Color: math3d.Vec3{X: 1.0, Y: 0.92, Z: 0.78}, + Intensity: 20.0, + Near: 0.2, + Range: 14.0, + InnerConeAngle: math3d.DegToRad(26), + OuterConeAngle: math3d.DegToRad(44), + Ambient: math3d.Vec3{X: 0.08, Y: 0.09, Z: 0.12}, + } + if err := spotShadow.Update(dev, light); err != nil { + t.Fatalf("spotShadow.Update: %v", err) + } + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0.4, Y: 4.8, Z: 5.0}, math3d.DegToRad(48), float32(localShadowTestWidth)/float32(localShadowTestHeight), 0.1, 30) + cam.LookAt(math3d.Vec3{X: 0.35, Y: 0.3, Z: -0.35}, math3d.Vec3Up()) + camBuf.WriteCamera(cam) + + enc := dev.BeginEncoder() + // Pass 1: depth-only spot shadow pass with multiple casters using distinct model transforms. + sp := spotShadow.BeginShadowPass(enc) + spotShadow.DrawCaster(dev, sp, gpuPillar1, math3d.Mat4Identity()) + spotShadow.DrawCaster(dev, sp, gpuPillar2Local, pillar2Model) + sp.End() + + // Pass 2: lit main pass sampling spot shadow map. + mp := enc.BeginRenderPass(gpu.RenderPassDesc{ + Label: "spot-lit-main", + ColorAttachments: []gpu.ColorAttachment{{ + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: localShadowTestClear, + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreDiscard, + ClearDepth: 1.0, + }, + }) + mp.SetPipeline(litPipe) + mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + mp.SetBindGroup(render3d.LocalShadowGroup, spotShadow.BindGroup()) + gpuScene.Draw(mp) + mp.End() + + dev.Submit(enc.Finish()) + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer error: %v", err) + } + + depth := localShadowTestReadDepth(t, dev, spotShadow.DepthTexture(), shadowRes, shadowRes) + return sr.Image(), depth, spotShadow.Uniforms(), cam +} + +func TestSpotShadowMatchesReferenceAndGolden(t *testing.T) { + pcfImg, pcfDepth, pcfUniform, cam := localShadowTestRenderSpotScene(t, render3d.LocalShadowFilterPCF3x3) + hardImg, hardDepth, hardUniform, _ := localShadowTestRenderSpotScene(t, render3d.LocalShadowFilterHard) + + localShadowTestAssertGolden(t, "local_shadow_spot", pcfImg) + + // Probe analytic visibility & GPU-vs-CPU color agreement across lit, shadowed, and out-of-cone points. + probes := []struct { + name string + world math3d.Vec3 + normal math3d.Vec3 + wantVisLo float32 + wantVisHi float32 + }{ + {"lit-floor-in-front", math3d.Vec3{X: -1.1, Y: 0, Z: 1.0}, math3d.Vec3Up(), 0.95, 1.0}, + {"shadowed-floor-behind-pillar1", math3d.Vec3{X: 0.7, Y: 0, Z: -0.7}, math3d.Vec3Up(), 0.0, 0.05}, + {"shadowed-floor-behind-pillar2", math3d.Vec3{X: 1.7, Y: 0, Z: -1.5}, math3d.Vec3Up(), 0.0, 0.05}, + {"lit-floor-side", math3d.Vec3{X: -1.4, Y: 0, Z: -0.9}, math3d.Vec3Up(), 0.95, 1.0}, + } + + for _, tc := range probes { + cpuVis := render3d.EvaluateSpotShadow(pcfUniform, pcfDepth, 128, tc.world, tc.normal) + if cpuVis < tc.wantVisLo || cpuVis > tc.wantVisHi { + t.Errorf("%s: CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, cpuVis, tc.wantVisLo, tc.wantVisHi) + } + cpuCol := localShadowTestColorToRGB8(render3d.EvaluateSpotLighting(pcfUniform, pcfDepth, 128, tc.world, tc.normal, localShadowTestAlbedo)) + gpuCol, px, py, ok := localShadowTestSamplePixel(pcfImg, cam, tc.world) + if !ok { + t.Fatalf("%s: probe %v outside view", tc.name, tc.world) + } + if diff := localShadowTestRGBDiff(gpuCol, cpuCol); diff > 10 { + t.Errorf("%s at (%d,%d): GPU=%v vs CPU=%v (max diff %d)", tc.name, px, py, gpuCol, cpuCol, diff) + } + + hardVis := render3d.EvaluateSpotShadow(hardUniform, hardDepth, 128, tc.world, tc.normal) + if hardVis < tc.wantVisLo || hardVis > tc.wantVisHi { + t.Errorf("%s (hard): CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, hardVis, tc.wantVisLo, tc.wantVisHi) + } + hardGPU, _, _, _ := localShadowTestSamplePixel(hardImg, cam, tc.world) + hardCPU := localShadowTestColorToRGB8(render3d.EvaluateSpotLighting(hardUniform, hardDepth, 128, tc.world, tc.normal, localShadowTestAlbedo)) + if diff := localShadowTestRGBDiff(hardGPU, hardCPU); diff > 10 { + t.Errorf("%s (hard): GPU=%v vs CPU=%v (max diff %d)", tc.name, hardGPU, hardCPU, diff) + } + } + + // Verify lit floor is markedly brighter than shadowed floor behind both casters. + litPx, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -1.1, Y: 0, Z: 1.0}) + shad1Px, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 0.7, Y: 0, Z: -0.7}) + shad2Px, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 1.7, Y: 0, Z: -1.5}) + if int(litPx[0]) < int(shad1Px[0])+80 || int(litPx[0]) < int(shad2Px[0])+80 { + t.Fatalf("expected strong shadow contrast: lit=%v shad1=%v shad2=%v", litPx, shad1Px, shad2Px) + } + + // Verify Hard vs PCF3x3: scanning across the shadow edge produces intermediate + // visibility values strictly in (0, 1) for PCF3x3 and only 0 or 1 for Hard. + pcfPenumbra := 0 + for i := range 60 { + x := float32(-0.5) + float32(i)*0.04 + pt := math3d.Vec3{X: x, Y: 0, Z: -0.7} + hv := render3d.EvaluateSpotShadow(hardUniform, hardDepth, 128, pt, math3d.Vec3Up()) + if hv != 0 && hv != 1 { + t.Fatalf("hard shadow returned non-binary visibility %v at %v", hv, pt) + } + pv := render3d.EvaluateSpotShadow(pcfUniform, pcfDepth, 128, pt, math3d.Vec3Up()) + if pv > 0.05 && pv < 0.95 { + pcfPenumbra++ + } + } + if pcfPenumbra == 0 { + t.Errorf("expected PCF3x3 to produce smooth intermediate penumbra taps along shadow boundary") + } +} + +func localShadowTestRenderPointScene(t *testing.T, filter render3d.LocalShadowFilter) (*image.RGBA, []float32, render3d.PointShadowUniform, *scene3d.Camera) { + t.Helper() + const faceRes = 64 + + sr := gpu.NewSoftwareRenderer(localShadowTestWidth, localShadowTestHeight, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + camBuf, err := render3d.NewCameraBuffer(nil, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + t.Cleanup(func() { _ = camBuf.Close() }) + + pointShadow, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{ + FaceResolution: faceRes, + DepthBias: 0.0025, + NormalBias: 0.03, + Filter: filter, + Label: "test.point", + }) + if err != nil { + t.Fatalf("NewPointShadowMap: %v", err) + } + t.Cleanup(func() { _ = pointShadow.Close() }) + + litPipe, err := render3d.NewPointShadowLitPipeline(nil, dev, camBuf.Layout(), pointShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ + DepthFormat: gpu.FormatDepth24Plus, + CullMode: gpu.CullBack, + }) + if err != nil { + t.Fatalf("NewPointShadowLitPipeline: %v", err) + } + t.Cleanup(func() { _ = litPipe.Close() }) + + // Open room corner: subdivided floor (y=0), back wall (z=-3.0, normal +Z), right wall (x=3.0, normal -X). + floor := localShadowTestSubdividedQuad( + math3d.Vec3{X: 0, Y: 0, Z: 0}, + math3d.Vec3{X: 1}, + math3d.Vec3{Z: -1}, + math3d.Vec3Up(), + 3.2, 3.2, 8, + ) + backWall := localShadowTestSubdividedQuad( + math3d.Vec3{X: 0, Y: 2.0, Z: -3.0}, + math3d.Vec3{X: 1}, + math3d.Vec3{Y: 1}, + math3d.Vec3{Z: 1}, + 3.2, 2.0, 6, + ) + rightWall := localShadowTestSubdividedQuad( + math3d.Vec3{X: 3.0, Y: 2.0, Z: 0}, + math3d.Vec3{Z: 1}, + math3d.Vec3{Y: 1}, + math3d.Vec3{X: -1}, + 3.2, 2.0, 6, + ) + + // Three blockers placed along distinct cube faces (+X, -Z, and -Y relative to light at (0, 1.8, 0)). + blockerPosX := localShadowTestBoxMesh(math3d.Vec3{X: 1.45, Y: 1.45, Z: 0.1}, math3d.Vec3{X: 0.35, Y: 0.55, Z: 0.45}) + blockerNegZ := localShadowTestBoxMesh(math3d.Vec3{X: -0.1, Y: 1.45, Z: -1.45}, math3d.Vec3{X: 0.45, Y: 0.55, Z: 0.35}) + blockerFloorLocal := localShadowTestBoxMesh(math3d.Vec3Zero(), math3d.Vec3{X: 0.45, Y: 0.35, Z: 0.45}) + blockerFloorPos := math3d.Vec3{X: -0.85, Y: 0.75, Z: 0.75} + blockerFloorWorld := localShadowTestBoxMesh(blockerFloorPos, math3d.Vec3{X: 0.45, Y: 0.35, Z: 0.45}) + + gpuBlockerX, err := render3d.UploadMesh(nil, dev, blockerPosX, render3d.MeshUpload{Label: "blocker-x"}) + if err != nil { + t.Fatalf("UploadMesh blockerX: %v", err) + } + t.Cleanup(func() { _ = gpuBlockerX.Close() }) + gpuBlockerZ, err := render3d.UploadMesh(nil, dev, blockerNegZ, render3d.MeshUpload{Label: "blocker-z"}) + if err != nil { + t.Fatalf("UploadMesh blockerZ: %v", err) + } + t.Cleanup(func() { _ = gpuBlockerZ.Close() }) + gpuBlockerFloor, err := render3d.UploadMesh(nil, dev, blockerFloorLocal, render3d.MeshUpload{Label: "blocker-y"}) + if err != nil { + t.Fatalf("UploadMesh blockerFloor: %v", err) + } + t.Cleanup(func() { _ = gpuBlockerFloor.Close() }) + gpuRoom, err := render3d.UploadMesh(nil, dev, localShadowTestMergeMeshes( + floor, backWall, rightWall, blockerPosX, blockerNegZ, blockerFloorWorld, + ), render3d.MeshUpload{Label: "point-room"}) + if err != nil { + t.Fatalf("UploadMesh room: %v", err) + } + t.Cleanup(func() { _ = gpuRoom.Close() }) + + light := render3d.PointShadowLight{ + Position: math3d.Vec3{X: 0.0, Y: 1.8, Z: 0.0}, + Color: math3d.Vec3{X: 1.0, Y: 0.94, Z: 0.85}, + Intensity: 14.0, + Near: 0.15, + Range: 12.0, + Ambient: math3d.Vec3{X: 0.07, Y: 0.08, Z: 0.11}, + } + if err := pointShadow.Update(dev, light); err != nil { + t.Fatalf("pointShadow.Update: %v", err) + } + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: -3.8, Y: 4.3, Z: 4.4}, math3d.DegToRad(50), float32(localShadowTestWidth)/float32(localShadowTestHeight), 0.1, 30) + cam.LookAt(math3d.Vec3{X: 0.5, Y: 1.0, Z: -0.5}, math3d.Vec3Up()) + camBuf.WriteCamera(cam) + + enc := dev.BeginEncoder() + // Render all 6 omnidirectional cube faces into the 3x2 depth atlas. + for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { + fp := pointShadow.BeginFacePass(enc, face) + pointShadow.DrawCaster(dev, fp, gpuBlockerX, math3d.Mat4Identity()) + pointShadow.DrawCaster(dev, fp, gpuBlockerZ, math3d.Mat4Identity()) + pointShadow.DrawCaster(dev, fp, gpuBlockerFloor, math3d.Translate(blockerFloorPos)) + fp.End() + } + + mp := enc.BeginRenderPass(gpu.RenderPassDesc{ + Label: "point-lit-main", + ColorAttachments: []gpu.ColorAttachment{{ + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: localShadowTestClear, + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreDiscard, + ClearDepth: 1.0, + }, + }) + mp.SetPipeline(litPipe) + mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + mp.SetBindGroup(render3d.LocalShadowGroup, pointShadow.BindGroup()) + gpuRoom.Draw(mp) + mp.End() + + dev.Submit(enc.Finish()) + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer error: %v", err) + } + + depth := localShadowTestReadDepth(t, dev, pointShadow.DepthTexture(), pointShadow.AtlasWidth(), pointShadow.AtlasHeight()) + return sr.Image(), depth, pointShadow.Uniforms(), cam +} + +func TestPointShadowMatchesReferenceAndGolden(t *testing.T) { + pcfImg, pcfDepth, pcfUniform, cam := localShadowTestRenderPointScene(t, render3d.LocalShadowFilterPCF3x3) + hardImg, hardDepth, hardUniform, _ := localShadowTestRenderPointScene(t, render3d.LocalShadowFilterHard) + + localShadowTestAssertGolden(t, "local_shadow_point", pcfImg) + + // Verify omnidirectional shadows across +X wall, -Z wall, and -Y floor! + probes := []struct { + name string + world math3d.Vec3 + normal math3d.Vec3 + wantFace gpu.CubeFace + wantVisLo float32 + wantVisHi float32 + }{ + {"right-wall-shadow-posX", math3d.Vec3{X: 3.0, Y: 1.1, Z: 0.2}, math3d.Vec3{X: -1}, gpu.CubeFacePosX, 0.0, 0.05}, + {"right-wall-lit-posX", math3d.Vec3{X: 3.0, Y: 2.8, Z: -1.8}, math3d.Vec3{X: -1}, gpu.CubeFacePosX, 0.95, 1.0}, + {"back-wall-shadow-negZ", math3d.Vec3{X: -0.2, Y: 1.1, Z: -3.0}, math3d.Vec3{Z: 1}, gpu.CubeFaceNegZ, 0.0, 0.05}, + {"back-wall-lit-negZ", math3d.Vec3{X: -2.0, Y: 2.6, Z: -3.0}, math3d.Vec3{Z: 1}, gpu.CubeFaceNegZ, 0.95, 1.0}, + {"floor-shadow-negY", math3d.Vec3{X: -1.45, Y: 0.0, Z: 1.3}, math3d.Vec3Up(), gpu.CubeFaceNegY, 0.0, 0.05}, + {"floor-lit-center", math3d.Vec3{X: 0.0, Y: 0.0, Z: 0.0}, math3d.Vec3Up(), gpu.CubeFaceNegY, 0.95, 1.0}, + } + + for _, tc := range probes { + gotFace, _, _, _ := render3d.PointShadowSelectFace(tc.world.Sub(pcfUniform.Position)) + if gotFace != tc.wantFace { + t.Errorf("%s: cube face = %d, want %d", tc.name, gotFace, tc.wantFace) + } + cpuVis := render3d.EvaluatePointShadow(pcfUniform, pcfDepth, 64, tc.world, tc.normal) + if cpuVis < tc.wantVisLo || cpuVis > tc.wantVisHi { + t.Errorf("%s: CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, cpuVis, tc.wantVisLo, tc.wantVisHi) + } + cpuCol := localShadowTestColorToRGB8(render3d.EvaluatePointLighting(pcfUniform, pcfDepth, 64, tc.world, tc.normal, localShadowTestAlbedo)) + gpuCol, px, py, ok := localShadowTestSamplePixel(pcfImg, cam, tc.world) + if !ok { + t.Fatalf("%s: probe %v outside view", tc.name, tc.world) + } + if diff := localShadowTestRGBDiff(gpuCol, cpuCol); diff > 12 { + t.Errorf("%s at (%d,%d): GPU=%v vs CPU=%v (max diff %d)", tc.name, px, py, gpuCol, cpuCol, diff) + } + + hardVis := render3d.EvaluatePointShadow(hardUniform, hardDepth, 64, tc.world, tc.normal) + if hardVis < tc.wantVisLo || hardVis > tc.wantVisHi { + t.Errorf("%s (hard): CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, hardVis, tc.wantVisLo, tc.wantVisHi) + } + hardGPU, _, _, _ := localShadowTestSamplePixel(hardImg, cam, tc.world) + hardCPU := localShadowTestColorToRGB8(render3d.EvaluatePointLighting(hardUniform, hardDepth, 64, tc.world, tc.normal, localShadowTestAlbedo)) + if diff := localShadowTestRGBDiff(hardGPU, hardCPU); diff > 12 { + t.Errorf("%s (hard): GPU=%v vs CPU=%v (max diff %d)", tc.name, hardGPU, hardCPU, diff) + } + } + + // Verify strong visual shadow contrast on every shadowed face (+X wall, -Z wall, -Y floor). + wallXShad, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 3.0, Y: 1.1, Z: 0.2}) + wallXLit, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 3.0, Y: 2.8, Z: -1.8}) + wallZShad, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -0.2, Y: 1.1, Z: -3.0}) + wallZLit, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -2.0, Y: 2.6, Z: -3.0}) + floorShad, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -1.45, Y: 0.0, Z: 1.3}) + floorLit, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 0.0, Y: 0.0, Z: 0.0}) + if int(wallXLit[0]) < int(wallXShad[0])+40 { + t.Errorf("+X wall shadow contrast too low: lit=%v shad=%v", wallXLit, wallXShad) + } + if int(wallZLit[0]) < int(wallZShad[0])+40 { + t.Errorf("-Z wall shadow contrast too low: lit=%v shad=%v", wallZLit, wallZShad) + } + if int(floorLit[0]) < int(floorShad[0])+80 { + t.Errorf("-Y floor shadow contrast too low: lit=%v shad=%v", floorLit, floorShad) + } +} + +func localShadowTestStartGPUView(t *testing.T, retained bool, usePoint bool, extraOpts ...nsgotest.Option) ( + *nsgotest.App, + func() bool, + *int, + *scene3d.Camera, +) { + t.Helper() + var ( + dev *gpu.Device + camBuf *render3d.CameraBuffer + spotShadow *render3d.SpotShadowMap + pointShadow *render3d.PointShadowMap + litPipe *gpu.Pipeline + gpuCaster *render3d.GPUMesh + gpuScene *render3d.GPUMesh + frames int + ) + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 4.5, Z: 4.5}, math3d.DegToRad(50), 1.0, 0.1, 30) + cam.LookAt(math3d.Vec3{X: 0, Y: 0, Z: 0}, math3d.Vec3Up()) + + floorMesh := localShadowTestSubdividedQuad( + math3d.Vec3{Y: 0}, + math3d.Vec3{X: 1}, + math3d.Vec3{Z: -1}, + math3d.Vec3Up(), + 4.0, 4.0, 6, + ) + pillarMesh := localShadowTestBoxMesh(math3d.Vec3{X: 0, Y: 0.9, Z: 0}, math3d.Vec3{X: 0.45, Y: 0.9, Z: 0.45}) + sceneMesh := localShadowTestMergeMeshes(floorMesh, pillarMesh) + + spotLight := render3d.SpotShadowLight{ + Position: math3d.Vec3{X: -2.0, Y: 3.2, Z: 0.0}, + Direction: math3d.Vec3{X: 2.0, Y: -3.2, Z: 0.0}.Norm(), + Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, + Intensity: 18, + Near: 0.2, + Range: 12, + InnerConeAngle: math3d.DegToRad(30), + OuterConeAngle: math3d.DegToRad(45), + Ambient: math3d.Vec3{X: 0.08, Y: 0.08, Z: 0.08}, + } + pointLight := render3d.PointShadowLight{ + Position: math3d.Vec3{X: -2.0, Y: 2.0, Z: 0.0}, + Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, + Intensity: 18, + Near: 0.15, + Range: 12, + Ambient: math3d.Vec3{X: 0.08, Y: 0.08, Z: 0.08}, + } + + opts := append([]nsgotest.Option{nsgotest.Size(64, 64), nsgotest.ManualFrames()}, extraOpts...) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "viewport", + Style: core.Style{Width: core.Pt(64), Height: core.Pt(64)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(d *gpu.Device) { + dev = d + var err error + camBuf, err = render3d.NewCameraBuffer(cx, d) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + if !retained || gpuCaster == nil { + gpuCaster, err = render3d.UploadMesh(cx, d, pillarMesh, render3d.MeshUpload{Label: "caster", Retained: retained}) + if err != nil { + t.Fatalf("UploadMesh caster: %v", err) + } + gpuScene, err = render3d.UploadMesh(cx, d, sceneMesh, render3d.MeshUpload{Label: "scene", Retained: retained}) + if err != nil { + t.Fatalf("UploadMesh scene: %v", err) + } + } + if usePoint { + if !retained || pointShadow == nil { + pointShadow, err = render3d.NewPointShadowMap(cx, d, render3d.PointShadowConfig{ + FaceResolution: 32, + DepthBias: 0.002, + NormalBias: 0.02, + Filter: render3d.LocalShadowFilterPCF3x3, + Retained: retained, + }) + if err != nil { + t.Fatalf("NewPointShadowMap: %v", err) + } + } + litPipe, err = render3d.NewPointShadowLitPipeline(cx, d, camBuf.Layout(), pointShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ + DepthFormat: gpu.FormatDepth24Plus, + CullMode: gpu.CullBack, + }) + if err != nil { + t.Fatalf("NewPointShadowLitPipeline: %v", err) + } + } else { + if !retained || spotShadow == nil { + spotShadow, err = render3d.NewSpotShadowMap(cx, d, render3d.SpotShadowConfig{ + Resolution: 64, + DepthBias: 0.002, + NormalBias: 0.02, + Filter: render3d.LocalShadowFilterPCF3x3, + Retained: retained, + }) + if err != nil { + t.Fatalf("NewSpotShadowMap: %v", err) + } + } + litPipe, err = render3d.NewSpotShadowLitPipeline(cx, d, camBuf.Layout(), spotShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ + DepthFormat: gpu.FormatDepth24Plus, + CullMode: gpu.CullBack, + }) + if err != nil { + t.Fatalf("NewSpotShadowLitPipeline: %v", err) + } + } + }, + OnFrame: func(frame *gpu.Frame) { + camBuf.WriteCamera(cam) + if usePoint { + if err := pointShadow.Update(dev, pointLight); err != nil { + t.Fatalf("pointShadow.Update: %v", err) + } + for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { + fp := pointShadow.BeginFacePass(frame, face) + pointShadow.DrawCaster(dev, fp, gpuCaster, math3d.Mat4Identity()) + fp.End() + } + } else { + if err := spotShadow.Update(dev, spotLight); err != nil { + t.Fatalf("spotShadow.Update: %v", err) + } + sp := spotShadow.BeginShadowPass(frame) + spotShadow.DrawCaster(dev, sp, gpuCaster, math3d.Mat4Identity()) + sp.End() + } + mp := frame.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{ + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: localShadowTestClear, + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreDiscard, + ClearDepth: 1.0, + }, + }) + mp.SetPipeline(litPipe) + mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + if usePoint { + mp.SetBindGroup(render3d.LocalShadowGroup, pointShadow.BindGroup()) + } else { + mp.SetBindGroup(render3d.LocalShadowGroup, spotShadow.BindGroup()) + } + gpuScene.Draw(mp) + mp.End() + frame.Submit() + frames++ + }, + }) + }, opts...) + + isValid := func() bool { + if usePoint { + return pointShadow != nil && pointShadow.Valid() + } + return spotShadow != nil && spotShadow.Valid() + } + return app, isValid, &frames, cam +} + +func localShadowTestAssertViewShadowContrast(t *testing.T, app *nsgotest.App, frames *int, cam *scene3d.Camera) { + t.Helper() + before := *frames + app.Advance(16 * time.Millisecond) + if *frames <= before { + t.Fatalf("expected rendered frame, got frames=%d", *frames) + } + img, err := app.GPUReadPixels("id:viewport") + if err != nil { + t.Fatalf("GPUReadPixels: %v", err) + } + litPx, _, _, okLit := localShadowTestSamplePixel(img, cam, math3d.Vec3{X: -1.2, Y: 0, Z: 0}) + shadPx, _, _, okShad := localShadowTestSamplePixel(img, cam, math3d.Vec3{X: 1.0, Y: 0, Z: 0}) + if !okLit || !okShad { + t.Fatalf("probes outside view: lit=%v shad=%v", okLit, okShad) + } + if int(litPx[0]) < int(shadPx[0])+60 { + t.Fatalf("expected strong shadow contrast in gpu.View: lit=%v shad=%v", litPx, shadPx) + } +} + +func TestLocalShadowsInGPUViewProfiles(t *testing.T) { + profiles := []struct { + name string + opts []nsgotest.Option + }{ + {"full", nil}, + {"webgl2-gles3", []nsgotest.Option{nsgotest.NoGPUCompute()}}, + } + for _, p := range profiles { + for _, kind := range []struct { + name string + usePoint bool + }{ + {"spot", false}, + {"point", true}, + } { + t.Run(p.name+"/"+kind.name, func(t *testing.T) { + app, valid, frames, cam := localShadowTestStartGPUView(t, false, kind.usePoint, p.opts...) + if !valid() { + t.Fatal("shadow map not valid after OnReady") + } + localShadowTestAssertViewShadowContrast(t, app, frames, cam) + }) + } + } +} + +func TestLocalShadowsRetainedDeviceLossRestore(t *testing.T) { + for _, kind := range []struct { + name string + usePoint bool + }{ + {"spot", false}, + {"point", true}, + } { + t.Run(kind.name, func(t *testing.T) { + app, valid, frames, cam := localShadowTestStartGPUView(t, true, kind.usePoint) + localShadowTestAssertViewShadowContrast(t, app, frames, cam) + + app.TriggerGPUDeviceLost("id:viewport", nsgotest.GPULostContextLost, "context lost") + if valid() { + t.Fatalf("retained %s shadow map still valid while device is lost", kind.name) + } + + app.RestoreGPUDevice("id:viewport") + if !valid() { + t.Fatalf("retained %s shadow map not restored after RestoreGPUDevice", kind.name) + } + localShadowTestAssertViewShadowContrast(t, app, frames, cam) + }) + } +} + +func TestLocalShadowsCloseAndScopeDisposal(t *testing.T) { + // Nil safety. + var nilSpot *render3d.SpotShadowMap + var nilPoint *render3d.PointShadowMap + if nilSpot.Valid() || nilPoint.Valid() || nilSpot.ByteSize() != 0 || nilPoint.ByteSize() != 0 { + t.Fatal("nil shadow map should report invalid and zero byte size") + } + if err := nilSpot.Close(); err != nil { + t.Fatalf("nil spot Close: %v", err) + } + if err := nilPoint.Close(); err != nil { + t.Fatalf("nil point Close: %v", err) + } + + // Explicit Close idempotency & ByteSize accounting. + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + spot, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{Resolution: 64, MaxCasters: 16}) + if err != nil { + t.Fatalf("NewSpotShadowMap: %v", err) + } + if want := uint64(64*64*4) + render3d.SpotShadowUniformSize + 16*256; spot.ByteSize() != want { + t.Fatalf("spot ByteSize = %d, want %d", spot.ByteSize(), want) + } + if err := spot.Close(); err != nil { + t.Fatalf("spot Close: %v", err) + } + if err := spot.Close(); err != nil { + t.Fatalf("spot second Close: %v", err) + } + if spot.Valid() { + t.Fatal("spot still valid after Close") + } + + point, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{FaceResolution: 32, MaxCasters: 24}) + if err != nil { + t.Fatalf("NewPointShadowMap: %v", err) + } + if want := uint64(96*64*4) + render3d.PointShadowUniformSize + 24*256; point.ByteSize() != want { + t.Fatalf("point ByteSize = %d, want %d", point.ByteSize(), want) + } + if err := point.Close(); err != nil { + t.Fatalf("point Close: %v", err) + } + if err := point.Close(); err != nil { + t.Fatalf("point second Close: %v", err) + } + if point.Valid() { + t.Fatal("point still valid after Close") + } + + // Scope disposal releases both maps automatically. + var ( + scopedSpot *render3d.SpotShadowMap + scopedPoint *render3d.PointShadowMap + show *core.Signal[bool] + ) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + show = core.NewSignal(cx, true) + return core.Show{When: show.Get, Then: func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + Style: core.Style{Width: core.Pt(8), Height: core.Pt(8)}, + OnReady: func(d *gpu.Device) { + var err error + scopedSpot, err = render3d.NewSpotShadowMap(cx, d, render3d.SpotShadowConfig{Resolution: 32}) + if err != nil { + t.Fatalf("NewSpotShadowMap: %v", err) + } + scopedPoint, err = render3d.NewPointShadowMap(cx, d, render3d.PointShadowConfig{FaceResolution: 16}) + if err != nil { + t.Fatalf("NewPointShadowMap: %v", err) + } + }, + }) + }} + }, nsgotest.Size(8, 8), nsgotest.ManualFrames()) + + if !scopedSpot.Valid() || !scopedPoint.Valid() { + t.Fatal("scoped shadow maps must be valid while mounted") + } + app.Post(func() { show.Set(false) }) + app.Settle() + if scopedSpot.Valid() || scopedPoint.Valid() { + t.Fatalf("scoped shadow maps still valid after disposal: spot=%v point=%v", scopedSpot.Valid(), scopedPoint.Valid()) + } +} diff --git a/packages/game/render3d/testdata/golden/local_shadow_point.png b/packages/game/render3d/testdata/golden/local_shadow_point.png new file mode 100644 index 0000000000000000000000000000000000000000..fcf6e919c252a6b1b92c4b06656eab4439c5bb4e GIT binary patch literal 9776 zcmV-0CePW4P)-$W|n~VpF0*S#l&w7D<^Rc!C6RbBSxg#X%6ez+$oY@s8=4)YtQU zU-!IS91HBi&eyZ=&6{^j_wPIU>#w`N4XX9E;*Qh*edg<_r6jQrNotZLF;I;CGseWm z#4()4aomng3Fh*n@6o@GACvHCAF?MYrIL>L zyFHKr7VCC)0*~!>>@kKI0B{5J%z!Wq7i9x50Jwndun$mQrTpqjTU&TYQ}{zl(!>f) zf_3+rVCclQ=U@Ex?-QukB>B7l_FpT8)yLZYv5YY2_%6S8pJbA*K%1l#0vZK(lY~FD zhZ4l{6YwjN{z#xmrUWWM znpzI{8jy*<{SBj(jI%G1(s<$rdIMibRg%E{bfOZjC)O5fhWG{`>S2d<0&Rfzf`BWp zsmg$ckd6Z>!Y|NP!eispcr_>4PIlF z5PCu%H9+G<;s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ULaS&;S4t zQhC6<4rrI6-Smls|E!B#FgW0&m=Ueg5NFO^ICK7^(}U+u4xD-a_&{?7lKfq#>_6PU z_O8|4wdya0LDyZYAvyx%D=;i=^zmbK^x5dg3+xYg|A0OM&ucz8vz3>J;E(?IpVQ5k zNdsW%-NE;s+_{y*OSvbE-*J=>9pJ1d92h)zVqoyZ$-!eMPxr%8nOhHz-Wmavaa@cF zL7?yIsjD=_&ek7lfxuJW3+Q8B9M1tYc>_c%pL0Vn;Ku*_g~DSt zr49NrfH7fBa?U4|8i!uuwo}>${QRT9F03nV$RIRKRHF%INsW=+#S?M~8+-J{r2jiTM8-%gE^1 z>A~~0YNZ$zlu|wQZVczp&eE7SIKnya`^At?&IDo4OX!0|NdDV5ze~4TF%1AEIQZV~ z9a}tWH<&Q27U${7Y%aOHZFSB!Vpaemnq^eZQB2B$s7u_A_ zbUO6O=HT$lOO{FHYk%||y2%PNfDF+Vo?c+LGZo_M)rm_Zqr;c43}3o(@e;6MW@crR z2rY@?7?$Y68c(eyBz~&;eJpZ-Q=-vWmqeeVp1cbTnebo#@EN*;SaB1Cy)oJ$gdT$E zt(N^yJyT=jlUK(ku8fY2j9zUv@2IsFhl?x(@+$$l@StG0>g= z?6~Z`Cw6Sc9#_iQ*}2iNiP5X$SFVnajE;?5xjJ&?YJ2(qv&Qn4IF4Zf zE6ixfFbs8|W6Z6Az9!nAEZ*sRoZgs=`{A#B^A?Sd5JCv?{{{eN2rzOVP)2Y70000< KMNUMnLSTX@myjy} literal 0 HcmV?d00001 diff --git a/packages/game/render3d/testdata/golden/local_shadow_spot.png b/packages/game/render3d/testdata/golden/local_shadow_spot.png new file mode 100644 index 0000000000000000000000000000000000000000..3ae58f56f41f66dca59f7f64df8419262180ee9b GIT binary patch literal 7758 zcmb7}<47sYp%mG16N=}zgEMv##1j-`cVX^<8Kq!9#>ZV;C42I+2Ax;x(IUwH4# zxo770?arL@>BeYjC}E+KqXPf{EEQ#Wo&Oy6pUhD~|7|1EV`>0^n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%zCFw+LBobs&@?9$HFG|!mW1|Usk-A1mC9OKHYz{tI zf9u0EtC+KXyF5WKq0ioxF*j3=Ob{_Ae?LJxR9yT73d;eE3zKSo2|C#nyMXtTfE~`H zKMVBUc##&n1iE@0Jqhk%M~0gI!1T09B=8#qA%O zSvly>XykK>9sUEH!I=Q+qP(vKDr`iBk$^c^Cj!UnxO1@@zZ2P_lFOi4J<4hpJOntq zzSfxgn&Iil`|Y2tw=dSMY`>Ketld%UL+`R@8Bph^CJfrf-ej9A1M^I>gW6KFTR97u z=k^d5)5Yl?%cPiw-_TWN4^E=As1DE!lw|jP`!l~R`4hL|@{{;9D{%JV?}Le`On5*6 zxMHSi((S+}6VPuM%`@T)?0q=Pg(pBu`Tb z{8x}B2vJ{-aEK|Dm!t_hEN8a7!yO<+g5q!I|6yMJhB!Kq Date: Wed, 25 Nov 2026 03:09:36 +0900 Subject: [PATCH 2/3] refactor(render3d): shadow the LightRig's spot and point lights through the PBR path The first version of the local shadows carried its own light types and lighting model, which disagreed with LightRig (no 1/pi in the diffuse term, a different near-field clamp, Range required), its ready-made pipelines ignored per-draw transforms and used a constant albedo, and its WGSL hard-coded @group(1), which collides with LightGroup. SpotShadowMap and PointShadowMap now update from the rig's SpotLight and PointLight (far plane = Range, or the config's Far when Range is 0). The WGSL only samples visibility, at LocalShadowGroup (= ShadowGroup, 3), with SpotShadowWGSLForGroup and PointShadowWGSLForGroup to move it. LightWGSL gains shade_pbr_visibility, which scales directional light 0, point light 0 and spot light 0, and ShadePointVisibility mirrors it. LitPBRSpotShadowWGSL and LitPBRPointShadowWGSL (NewLitPBRSpotShadowPipeline, NewLitPBRPointShadowPipeline, LitPBRPipelineOptions.SpotShadowLayout and PointShadowLayout) are LitPBRWGSL with the map bound. Casters follow DirectionalShadowMap: BeginShadowPass(dev, target) and BeginFacePass(dev, target, face), DrawCaster returns false when the pass or face is full or Update has not run. Each point face owns its slots, so partial or reordered face refreshes never exhaust the buffer. MaxCasters is capped at MaxLocalShadowCasters and checked against MaxBufferSize. Doc comments are unwrapped. --- packages/game/render3d/light.go | 74 +- packages/game/render3d/local_shadows.go | 1972 +++++++---------- packages/game/render3d/local_shadows_test.go | 1278 ++++++----- .../testdata/golden/local_shadow_point.png | Bin 9776 -> 9465 bytes .../testdata/golden/local_shadow_spot.png | Bin 7758 -> 7004 bytes 5 files changed, 1562 insertions(+), 1762 deletions(-) diff --git a/packages/game/render3d/light.go b/packages/game/render3d/light.go index f9d4aad7..1ce04b44 100644 --- a/packages/game/render3d/light.go +++ b/packages/game/render3d/light.go @@ -57,12 +57,13 @@ var ErrInvalidLight = errors.New("render3d: invalid light") // - pbr_brdf(n, v, l, base_color, metallic, roughness) -> vec3 // - shade_pbr(world_pos, normal, view_dir, base_color, metallic, roughness) -> vec3 // - shade_pbr_shadowed(world_pos, normal, view_dir, base_color, metallic, roughness, shadow_vis) -> vec3 +// - shade_pbr_visibility(world_pos, normal, view_dir, base_color, metallic, roughness, directional0_vis, point0_vis, spot0_vis) -> vec3 // - linear_to_srgb_channel(c) -> f32 // - linear_to_srgb(rgb) -> vec3 // // Prepend [CameraWGSL] and LightWGSL to any 3D shader that reads scene lights; the block's layout // matches [LightUniforms.Encode] and [LightRig.AppendUniformData] byte for byte, and the shading math -// matches [EvaluatePBR], [ShadePoint], [ShadePointShadowed], [PointLightAttenuation], [SpotConeAttenuation], and [LinearToSRGB]. +// matches [EvaluatePBR], [ShadePoint], [ShadePointShadowed], [ShadePointVisibility], [PointLightAttenuation], [SpotConeAttenuation], and [LinearToSRGB]. const LightWGSL = `struct DirectionalLightUniform { to_light: vec4, color: vec4, @@ -148,6 +149,10 @@ fn shade_pbr(world_pos: vec3, normal: vec3, view_dir: vec3, base_ } fn shade_pbr_shadowed(world_pos: vec3, normal: vec3, view_dir: vec3, base_color: vec3, metallic: f32, roughness: f32, shadow_vis: f32) -> vec3 { + return shade_pbr_visibility(world_pos, normal, view_dir, base_color, metallic, roughness, shadow_vis, 1.0, 1.0); +} + +fn shade_pbr_visibility(world_pos: vec3, normal: vec3, view_dir: vec3, base_color: vec3, metallic: f32, roughness: f32, shadow_vis: f32, point0_vis: f32, spot0_vis: f32) -> vec3 { let n = normalize(normal); let v = normalize(view_dir); var lo = lights.ambient.xyz * base_color; @@ -179,8 +184,12 @@ fn shade_pbr_shadowed(world_pos: vec3, normal: vec3, view_dir: vec3 0.0 && dist_sq > 1e-12) { let l = to_light / sqrt(dist_sq); let ndotl = max(dot(n, l), 0.0); + var pvis = 1.0; + if (pi_idx == 0u) { + pvis = point0_vis; + } if (ndotl > 0.0) { - lo = lo + pbr_brdf(n, v, l, base_color, metallic, roughness) * (pl.color.xyz * atten * ndotl); + lo = lo + pbr_brdf(n, v, l, base_color, metallic, roughness) * (pl.color.xyz * atten * ndotl * pvis); } } } @@ -196,8 +205,12 @@ fn shade_pbr_shadowed(world_pos: vec3, normal: vec3, view_dir: vec3 0.0 && ndotl > 0.0) { - lo = lo + pbr_brdf(n, v, l, base_color, metallic, roughness) * (sl.color_offset.xyz * atten * ndotl); + lo = lo + pbr_brdf(n, v, l, base_color, metallic, roughness) * (sl.color_offset.xyz * atten * ndotl * svis); } } } @@ -926,7 +939,7 @@ const litPBRLinearWGSL = litPBRPreludeWGSL + litPBRFragmentHeadWGSL + ` return v // LitPBRPipelineOptions configures [NewLitPBRPipelineWithOptions]. type LitPBRPipelineOptions struct { - // Label names the pipeline in GPU capture tools; empty picks render3d.lit_pbr, lit_pbr_fog, lit_pbr_ibl or lit_pbr_shadow with a .linear suffix for LinearOutput. + // Label names the pipeline in GPU capture tools; empty picks render3d.lit_pbr, lit_pbr_fog, lit_pbr_ibl, lit_pbr_shadow, lit_pbr_spot_shadow or lit_pbr_point_shadow with a .linear suffix for LinearOutput. Label string // ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat(). Use [HDRTarget.Format] when drawing into an [HDRTarget]. ColorFormat gpu.TextureFormat @@ -940,11 +953,15 @@ type LitPBRPipelineOptions struct { SkinLayout *gpu.BindGroupLayout // ShadowLayout, when set, compiles [LitPBRShadowWGSL] with this layout ([DirectionalShadowMap.Layout]) at [ShadowGroup], as [NewLitPBRShadowPipeline] does, so the first directional light is attenuated by the shadow map. The shadow uses bind group 3 like fog, IBL and skinning, so ShadowLayout cannot be combined with FogLayout, IBLLayout or SkinLayout. ShadowLayout *gpu.BindGroupLayout + // SpotShadowLayout, when set, compiles [LitPBRSpotShadowWGSL] with this layout ([SpotShadowMap.Layout]) at [LocalShadowGroup], as [NewLitPBRSpotShadowPipeline] does, so the first spot light of the [LightRig] is attenuated by the spot shadow map. It uses bind group 3 like the directional shadow, fog, IBL and skinning, so it cannot be combined with any of them. + SpotShadowLayout *gpu.BindGroupLayout + // PointShadowLayout, when set, compiles [LitPBRPointShadowWGSL] with this layout ([PointShadowMap.Layout]) at [LocalShadowGroup], as [NewLitPBRPointShadowPipeline] does, so the first point light of the [LightRig] is attenuated by the point shadow atlas. It uses bind group 3 like the directional shadow, fog, IBL and skinning, so it cannot be combined with any of them. + PointShadowLayout *gpu.BindGroupLayout // LinearOutput skips the final linear-to-sRGB encoding and its clamp to [0, 1] and writes the lit linear radiance ([ShadePoint], plus [EvaluateIBL] or [Fog.Apply] when enabled), for drawing into an [HDRTarget] that a [ToneMapPass] then resolves to the display. LinearOutput bool } -// NewLitPBRPipelineWithOptions creates a lit PBR pipeline like [NewLitPBRPipeline], [NewLitPBRFogPipeline], [NewLitPBRIBLPipeline] or [NewLitPBRShadowPipeline], with a configurable color format, with [LitPBRPipelineOptions].LinearOutput linear HDR output for an [HDRTarget], and with [LitPBRPipelineOptions].SkinLayout GPU skinning. +// NewLitPBRPipelineWithOptions creates a lit PBR pipeline like [NewLitPBRPipeline], [NewLitPBRFogPipeline], [NewLitPBRIBLPipeline], [NewLitPBRShadowPipeline], [NewLitPBRSpotShadowPipeline] or [NewLitPBRPointShadowPipeline], with a configurable color format, with [LitPBRPipelineOptions].LinearOutput linear HDR output for an [HDRTarget], and with [LitPBRPipelineOptions].SkinLayout GPU skinning. func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout *gpu.BindGroupLayout, opts LitPBRPipelineOptions) (*gpu.Pipeline, error) { if dev == nil { return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} @@ -958,6 +975,17 @@ func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, li if opts.ShadowLayout != nil && (opts.FogLayout != nil || opts.IBLLayout != nil || opts.SkinLayout != nil) { return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: the directional shadow shares bind group 3 with fog, IBL and skinning; set ShadowLayout without FogLayout, IBLLayout or SkinLayout"} } + if opts.SpotShadowLayout != nil || opts.PointShadowLayout != nil { + group3 := 0 + for _, l := range [...]*gpu.BindGroupLayout{opts.FogLayout, opts.IBLLayout, opts.SkinLayout, opts.ShadowLayout, opts.SpotShadowLayout, opts.PointShadowLayout} { + if l != nil { + group3++ + } + } + if group3 > 1 { + return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: spot and point shadows use bind group 3 like the directional shadow, fog, IBL and skinning; set at most one of them"} + } + } label, src, linearSrc := "render3d.lit_pbr", LitPBRWGSL, litPBRLinearWGSL vertexLayout := MeshVertexLayout() layouts := make([]*gpu.BindGroupLayout, PBRDrawGroup+1, FogGroup+1) @@ -978,6 +1006,12 @@ func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, li case opts.ShadowLayout != nil: label, src, linearSrc = "render3d.lit_pbr_shadow", LitPBRShadowWGSL, litPBRShadowLinearWGSL layouts = append(layouts, opts.ShadowLayout) + case opts.SpotShadowLayout != nil: + label, src, linearSrc = "render3d.lit_pbr_spot_shadow", LitPBRSpotShadowWGSL, litPBRSpotShadowLinearWGSL + layouts = append(layouts, opts.SpotShadowLayout) + case opts.PointShadowLayout != nil: + label, src, linearSrc = "render3d.lit_pbr_point_shadow", LitPBRPointShadowWGSL, litPBRPointShadowLinearWGSL + layouts = append(layouts, opts.PointShadowLayout) } layouts[CameraGroup] = camLayout layouts[LightGroup] = lightLayout @@ -1121,6 +1155,18 @@ func ShadePoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig Ligh // ShadePointShadowed is [ShadePoint] with the first directional light (rig.Directional[0]) scaled by shadowVisibility, matching shade_pbr_shadowed in [LightWGSL] and the lighting of [LitPBRShadowWGSL]. Pass [EvaluateDirectionalShadow]'s result as shadowVisibility to reproduce a shadowed pixel on the CPU; 1 gives exactly [ShadePoint]. func ShadePointShadowed(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, shadowVisibility float32) math3d.Vec3 { + return ShadePointVisibility(worldPos, normal, viewDir, mat, rig, LightVisibility{Directional0: shadowVisibility, Point0: 1, Spot0: 1}) +} + +// LightVisibility holds the shadow visibility in [0, 1] of the [LightRig] lights a shadow map can cover: the first directional light ([DirectionalShadowMap]), the first point light ([PointShadowMap]) and the first spot light ([SpotShadowMap]). 1 leaves a light unshadowed and 0 removes its contribution; the ambient term and every other light are never shadowed. +type LightVisibility struct { + Directional0 float32 + Point0 float32 + Spot0 float32 +} + +// ShadePointVisibility is [ShadePoint] with rig.Directional[0], rig.Point[0] and rig.Spot[0] scaled by the matching fields of vis, matching shade_pbr_visibility in [LightWGSL] and the lighting of [LitPBRShadowWGSL], [LitPBRSpotShadowWGSL] and [LitPBRPointShadowWGSL]. Pass [EvaluateSpotShadow] or [EvaluatePointShadow] results to reproduce a pixel those shaders draw. +func ShadePointVisibility(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, vis LightVisibility) math3d.Vec3 { amb := rig.Ambient.Color.Scale(rig.Ambient.Intensity) lo := math3d.Vec3{ X: amb.X*mat.BaseColor.X + mat.Emissive.X, @@ -1148,11 +1194,11 @@ func ShadePointShadowed(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, continue } brdf := EvaluatePBR(n, v, l, mat) - vis := float32(1) + dvis := float32(1) if i == 0 { - vis = shadowVisibility + dvis = vis.Directional0 } - rad := dl.Color.Scale(dl.Intensity * (ndotl * vis)) + rad := dl.Color.Scale(dl.Intensity * (ndotl * dvis)) lo.X += brdf.X * rad.X lo.Y += brdf.Y * rad.Y lo.Z += brdf.Z * rad.Z @@ -1173,7 +1219,11 @@ func ShadePointShadowed(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, continue } brdf := EvaluatePBR(n, v, l, mat) - rad := pl.Color.Scale(pl.Intensity * atten * ndotl) + pvis := float32(1) + if i == 0 { + pvis = vis.Point0 + } + rad := pl.Color.Scale(pl.Intensity * atten * ndotl * pvis) lo.X += brdf.X * rad.X lo.Y += brdf.Y * rad.Y lo.Z += brdf.Z * rad.Z @@ -1199,7 +1249,11 @@ func ShadePointShadowed(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, continue } brdf := EvaluatePBR(n, v, l, mat) - rad := sl.Color.Scale(sl.Intensity * atten * ndotl) + svis := float32(1) + if i == 0 { + svis = vis.Spot0 + } + rad := sl.Color.Scale(sl.Intensity * atten * ndotl * svis) lo.X += brdf.X * rad.X lo.Y += brdf.Y * rad.Y lo.Z += brdf.Z * rad.Z diff --git a/packages/game/render3d/local_shadows.go b/packages/game/render3d/local_shadows.go index cf05baba..e9b286dd 100644 --- a/packages/game/render3d/local_shadows.go +++ b/packages/game/render3d/local_shadows.go @@ -11,15 +11,48 @@ import ( "github.com/nsgo-dev/nsgo/gpu" ) -// ErrInvalidLocalShadow is wrapped by every validation error returned for spot -// or point light shadow maps and light configurations. +// ErrInvalidLocalShadow is wrapped by every validation error returned for spot or point light shadow maps and their configurations. var ErrInvalidLocalShadow = errors.New("render3d: invalid local shadow") -// LocalShadowGroup is the bind group index used by [SpotShadowWGSL], -// [PointShadowWGSL], [NewSpotShadowLitPipeline], and [NewPointShadowLitPipeline] -// (paired with [CameraGroup] at slot 0). Callers building custom pipelines may -// place [SpotShadowMap.Layout] or [PointShadowMap.Layout] at any group index. -const LocalShadowGroup = 1 +// Spot and point light shadow constants and defaults (#255). +const ( + // LocalShadowGroup is the bind group index [SpotShadowWGSL], [PointShadowWGSL], [LitPBRSpotShadowWGSL] and [LitPBRPointShadowWGSL] reserve for a spot or point shadow map (uniform buffer at binding 0, depth texture at binding 1, comparison sampler at binding 2). It is [ShadowGroup], the group after [CameraGroup] (0), [LightGroup] (1) and [PBRDrawGroup] (2), so a lit PBR pipeline takes one shadow map, fog, IBL or skin palette there. Custom shaders that need group 3 for something else, or that combine a spot and a point shadow, place the bindings elsewhere with [SpotShadowWGSLForGroup] and [PointShadowWGSLForGroup]. + LocalShadowGroup = ShadowGroup + + // PointShadowFaceCount is the number of cube faces rendered for a point light. + PointShadowFaceCount = 6 + // PointShadowAtlasCols is the horizontal tile count of the 3x2 point shadow atlas. + PointShadowAtlasCols = 3 + // PointShadowAtlasRows is the vertical tile count of the 3x2 point shadow atlas. + PointShadowAtlasRows = 2 + + // SpotShadowUniformSize is the byte size of [SpotShadowUniform.Encode] and the WGSL SpotShadow block: one mat4x4 and one vec4 (80 bytes). + SpotShadowUniformSize = 64 + 16 + + // PointShadowUniformSize is the byte size of [PointShadowUniform.Encode] and the WGSL PointShadow block: three vec4 (48 bytes). + PointShadowUniformSize = 3 * 16 + + // DefaultLocalShadowNear is the default near plane distance of spot and point shadow projections. + DefaultLocalShadowNear float32 = 0.1 + // DefaultLocalShadowFar is the default far plane distance used for a light whose Range is 0 (unbounded inverse-square falloff). Lit surfaces farther than this from the light are left unshadowed. + DefaultLocalShadowFar float32 = 50 + + // DefaultLocalShadowMaxCasters is the default number of caster draws per spot shadow pass, and per cube face of a point shadow, when MaxCasters is zero. + DefaultLocalShadowMaxCasters uint32 = 256 + // MaxLocalShadowCasters is the largest MaxCasters [SpotShadowConfig.Validate] and [PointShadowConfig.Validate] accept. Each caster takes a 256-byte uniform slot, so a spot shadow at this limit holds a 1 MiB caster buffer and a point shadow six times that. + MaxLocalShadowCasters uint32 = 4096 + + // MaxSpotShadowConeAngle is the widest spot light OuterConeAngle (in radians, just under 90 degrees) a [SpotShadowMap] can project: its perspective field of view is twice the cone angle. Use a [PointShadowMap] for wider cones. + MaxSpotShadowConeAngle float32 = math.Pi/2 - 0.01 + + localShadowCasterSlotStride = 256 // WebGPU / Metal / D3D11 MinUniformBufferAlignment + localShadowCasterDataSize = 128 // light_view_proj (64) + model (64) + + defaultSpotShadowResolution = 1024 + defaultPointShadowResolution = 512 + defaultLocalShadowDepthBias = 0.0015 + defaultLocalShadowNormalBias = 0.02 +) // LocalShadowFilter selects how a local shadow map samples its depth texture. type LocalShadowFilter uint8 @@ -27,8 +60,7 @@ type LocalShadowFilter uint8 const ( // LocalShadowFilterHard performs a single nearest-neighbor depth comparison tap. LocalShadowFilterHard LocalShadowFilter = iota - // LocalShadowFilterPCF3x3 performs a 3x3 percentage-closer filter using - // linear comparison taps clamped inside the shadow map or cube face tile. + // LocalShadowFilterPCF3x3 performs a 3x3 percentage-closer filter using linear comparison taps clamped inside the shadow map or cube face tile. LocalShadowFilterPCF3x3 ) @@ -44,35 +76,7 @@ func (f LocalShadowFilter) String() string { } } -const ( - // PointShadowFaceCount is the number of cube faces rendered for a point light. - PointShadowFaceCount = 6 - // PointShadowAtlasCols is the horizontal tile count of the 3x2 point shadow atlas. - PointShadowAtlasCols = 3 - // PointShadowAtlasRows is the vertical tile count of the 3x2 point shadow atlas. - PointShadowAtlasRows = 2 - - // SpotShadowUniformSize is the byte size of [SpotShadowUniform.Encode] and - // the WGSL SpotShadow uniform block (144 bytes, 16-byte aligned). - SpotShadowUniformSize = 64 + 5*16 - - // PointShadowUniformSize is the byte size of [PointShadowUniform.Encode] and - // the WGSL PointShadow uniform block (64 bytes, 16-byte aligned). - PointShadowUniformSize = 4 * 16 - - localShadowCasterSlotStride = 256 // WebGPU / Metal / D3D11 MinUniformBufferAlignment - localShadowCasterDataSize = 128 // light_view_proj (64) + model (64) - - defaultSpotShadowResolution = 1024 - defaultPointShadowResolution = 512 - defaultLocalShadowDepthBias = 0.0015 - defaultLocalShadowNormalBias = 0.02 - defaultSpotMaxCasters = 256 - defaultPointMaxCasters = 1024 -) - -// localShadowDepthWGSL renders shadow caster geometry into a Depth32Float -// shadow map or atlas tile without a fragment stage. +// localShadowDepthWGSL renders shadow caster geometry into a Depth32Float shadow map or atlas tile without a fragment stage. const localShadowDepthWGSL = `struct LocalShadowCaster { light_view_proj: mat4x4, model: mat4x4, @@ -93,29 +97,22 @@ fn vs_local_shadow_depth(in: VertexIn) -> @builtin(position) vec4 { } ` -// SpotShadowWGSL declares the spot-light shadow uniform block, depth map, and -// comparison sampler at @group(1) bindings 0..2 together with portable WGSL -// helpers sample_spot_shadow and evaluate_spot_lighting. -// -// Prepend [CameraWGSL] and SpotShadowWGSL to a 3D fragment shader. The shader -// avoids exp/exp2/log2 and uses textureSampleCompareLevel so it runs identically -// across Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and -// NSGo's software GPU renderer. -const SpotShadowWGSL = `struct SpotShadow { +// spotShadowStructWGSL declares the uniform block shared by [SpotShadowWGSL] and [SpotShadowWGSLForGroup]. +const spotShadowStructWGSL = `struct SpotShadow { view_proj: mat4x4, - position_range: vec4, - direction_inner: vec4, - color_outer: vec4, params: vec4, - ambient_near: vec4, } +` -@group(1) @binding(0) var spot_shadow: SpotShadow; -@group(1) @binding(1) var spot_shadow_map: texture_depth_2d; -@group(1) @binding(2) var spot_shadow_sampler: sampler_comparison; - +// spotShadowSampleFnWGSL is the sample_spot_shadow helper shared by [SpotShadowWGSL] and [SpotShadowWGSLForGroup]. +const spotShadowSampleFnWGSL = ` fn sample_spot_shadow(world_pos: vec3, world_normal: vec3) -> f32 { - let biased_pos = world_pos + world_normal * spot_shadow.params.y; + var n = vec3(0.0, 0.0, 0.0); + let n_len = length(world_normal); + if (n_len > 0.000001) { + n = world_normal / n_len; + } + let biased_pos = world_pos + n * spot_shadow.params.y; let clip = spot_shadow.view_proj * vec4(biased_pos, 1.0); if (clip.w <= 0.00001) { return 1.0; @@ -134,69 +131,42 @@ fn sample_spot_shadow(world_pos: vec3, world_normal: vec3) -> f32 { return textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv, uv_min, uv_max), ref_depth); } var sum: f32 = 0.0; - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(-inv_res, -inv_res), uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(0.0, -inv_res), uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(inv_res, -inv_res), uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(-inv_res, 0.0), uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv, uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(inv_res, 0.0), uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(-inv_res, inv_res), uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(0.0, inv_res), uv_min, uv_max), ref_depth); - sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + vec2(inv_res, inv_res), uv_min, uv_max), ref_depth); + for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { + for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { + let off = vec2(f32(dx) * inv_res, f32(dy) * inv_res); + sum = sum + textureSampleCompareLevel(spot_shadow_map, spot_shadow_sampler, clamp(uv + off, uv_min, uv_max), ref_depth); + } + } return sum / 9.0; } - -fn evaluate_spot_lighting(world_pos: vec3, world_normal: vec3, albedo: vec3) -> vec3 { - let n = normalize(world_normal); - let to_light = spot_shadow.position_range.xyz - world_pos; - let dist = length(to_light); - let light_range = spot_shadow.position_range.w; - let ambient = albedo * spot_shadow.ambient_near.xyz; - if (dist <= 0.0001 || dist >= light_range) { - return ambient; - } - let l_dir = to_light / dist; - let ndl = max(dot(n, l_dir), 0.0); - if (ndl <= 0.0) { - return ambient; - } - let cos_theta = dot(-l_dir, spot_shadow.direction_inner.xyz); - let cos_outer = spot_shadow.color_outer.w; - let cos_inner = spot_shadow.direction_inner.w; - let cone_t = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 0.0001), 0.0, 1.0); - let cone = cone_t * cone_t * (3.0 - 2.0 * cone_t); - if (cone <= 0.0) { - return ambient; - } - let ratio = dist / light_range; - let r2 = ratio * ratio; - let win = clamp(1.0 - r2 * r2, 0.0, 1.0); - let atten = (win * win) / max(dist * dist, 0.01); - let vis = sample_spot_shadow(world_pos, n); - return ambient + albedo * spot_shadow.color_outer.xyz * (ndl * cone * atten * vis); -} ` -// PointShadowWGSL declares the omnidirectional point-light shadow uniform block, -// 3x2 2D depth atlas, and comparison sampler at @group(1) bindings 0..2 together -// with portable WGSL helpers sample_point_shadow and evaluate_point_lighting. -// -// Prepend [CameraWGSL] and PointShadowWGSL to a 3D fragment shader. Because all -// six 90-degree cube faces live in a single 3x2 texture_depth_2d atlas with -// per-tile UV clamping, sampling and 3x3 PCF work portably across Metal, -// Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and NSGo's software -// GPU renderer without cubemap depth-attachment limitations. -const PointShadowWGSL = `struct PointShadow { - position_range: vec4, - color_near: vec4, +// SpotShadowWGSL declares the spot shadow uniform block, depth map and comparison sampler at [LocalShadowGroup] (@group(3)) and the portable sample_spot_shadow(world_pos, world_normal) helper returning the spot light's visibility in [0, 1]. It equals SpotShadowWGSLForGroup(LocalShadowGroup). [LitPBRSpotShadowWGSL] is the ready-made PBR shader built on it; a custom lit shader multiplies its spot light's contribution by the helper's result, for example through shade_pbr_visibility in [LightWGSL]. It uses only textureSampleCompareLevel, so it runs on every NSGo backend, the WebGL 2 / GLES 3 profile and the software renderer included. +const SpotShadowWGSL = spotShadowStructWGSL + ` +@group(3) @binding(0) var spot_shadow: SpotShadow; +@group(3) @binding(1) var spot_shadow_map: texture_depth_2d; +@group(3) @binding(2) var spot_shadow_sampler: sampler_comparison; +` + spotShadowSampleFnWGSL + +// SpotShadowWGSLForGroup returns [SpotShadowWGSL] with its bindings placed at @group(group) instead of [LocalShadowGroup]. +func SpotShadowWGSLForGroup(group uint32) string { + return fmt.Sprintf(`%s +@group(%[2]d) @binding(0) var spot_shadow: SpotShadow; +@group(%[2]d) @binding(1) var spot_shadow_map: texture_depth_2d; +@group(%[2]d) @binding(2) var spot_shadow_sampler: sampler_comparison; +%[3]s`, spotShadowStructWGSL, group, spotShadowSampleFnWGSL) +} + +// pointShadowStructWGSL declares the uniform block shared by [PointShadowWGSL] and [PointShadowWGSLForGroup]. +const pointShadowStructWGSL = `struct PointShadow { + position_far: vec4, params: vec4, - ambient_pad: vec4, + near_pad: vec4, } +` -@group(1) @binding(0) var point_shadow: PointShadow; -@group(1) @binding(1) var point_shadow_map: texture_depth_2d; -@group(1) @binding(2) var point_shadow_sampler: sampler_comparison; - +// pointShadowSampleFnWGSL holds the point_shadow_tile_tap and sample_point_shadow helpers shared by [PointShadowWGSL] and [PointShadowWGSLForGroup]. +const pointShadowSampleFnWGSL = ` fn point_shadow_tile_tap(col: f32, row: f32, local_uv: vec2, offset: vec2, pad: f32, ref_depth: f32) -> f32 { let clamped = clamp(local_uv + offset, vec2(pad, pad), vec2(1.0 - pad, 1.0 - pad)); let atlas_uv = vec2((col + clamped.x) / 3.0, (row + clamped.y) / 2.0); @@ -204,8 +174,13 @@ fn point_shadow_tile_tap(col: f32, row: f32, local_uv: vec2, offset: vec2, world_normal: vec3) -> f32 { - let biased_pos = world_pos + world_normal * point_shadow.params.y; - let v = biased_pos - point_shadow.position_range.xyz; + var n = vec3(0.0, 0.0, 0.0); + let n_len = length(world_normal); + if (n_len > 0.000001) { + n = world_normal / n_len; + } + let biased_pos = world_pos + n * point_shadow.params.y; + let v = biased_pos - point_shadow.position_far.xyz; let av = abs(v); var col: f32 = 0.0; var row: f32 = 0.0; @@ -237,8 +212,8 @@ fn sample_point_shadow(world_pos: vec3, world_normal: vec3) -> f32 { x_view = v.x; y_view = v.y; axis_dist = -v.z; } } - let near_p = point_shadow.color_near.w; - let far_p = point_shadow.position_range.w; + let near_p = point_shadow.near_pad.x; + let far_p = point_shadow.position_far.w; if (axis_dist <= near_p || axis_dist >= far_p) { return 1.0; } @@ -251,117 +226,175 @@ fn sample_point_shadow(world_pos: vec3, world_normal: vec3) -> f32 { return point_shadow_tile_tap(col, row, local_uv, vec2(0.0, 0.0), pad, ref_depth); } var sum: f32 = 0.0; - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(-inv_res, -inv_res), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(0.0, -inv_res), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(inv_res, -inv_res), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(-inv_res, 0.0), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(0.0, 0.0), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(inv_res, 0.0), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(-inv_res, inv_res), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(0.0, inv_res), pad, ref_depth); - sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(inv_res, inv_res), pad, ref_depth); + for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { + for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { + sum = sum + point_shadow_tile_tap(col, row, local_uv, vec2(f32(dx) * inv_res, f32(dy) * inv_res), pad, ref_depth); + } + } return sum / 9.0; } +` -fn evaluate_point_lighting(world_pos: vec3, world_normal: vec3, albedo: vec3) -> vec3 { - let n = normalize(world_normal); - let to_light = point_shadow.position_range.xyz - world_pos; - let dist = length(to_light); - let light_range = point_shadow.position_range.w; - let ambient = albedo * point_shadow.ambient_pad.xyz; - if (dist <= 0.0001 || dist >= light_range) { - return ambient; - } - let l_dir = to_light / dist; - let ndl = max(dot(n, l_dir), 0.0); - if (ndl <= 0.0) { - return ambient; - } - let ratio = dist / light_range; - let r2 = ratio * ratio; - let win = clamp(1.0 - r2 * r2, 0.0, 1.0); - let atten = (win * win) / max(dist * dist, 0.01); - let vis = sample_point_shadow(world_pos, n); - return ambient + albedo * point_shadow.color_near.xyz * (ndl * atten * vis); +// PointShadowWGSL declares the point shadow uniform block, 3x2 depth atlas and comparison sampler at [LocalShadowGroup] (@group(3)) and the portable sample_point_shadow(world_pos, world_normal) helper returning the point light's visibility in [0, 1]. It equals PointShadowWGSLForGroup(LocalShadowGroup). All six cube faces live in one texture_depth_2d atlas with per-tile UV clamping, so sampling and 3x3 PCF work on every NSGo backend without depth cube maps. [LitPBRPointShadowWGSL] is the ready-made PBR shader built on it. +const PointShadowWGSL = pointShadowStructWGSL + ` +@group(3) @binding(0) var point_shadow: PointShadow; +@group(3) @binding(1) var point_shadow_map: texture_depth_2d; +@group(3) @binding(2) var point_shadow_sampler: sampler_comparison; +` + pointShadowSampleFnWGSL + +// PointShadowWGSLForGroup returns [PointShadowWGSL] with its bindings placed at @group(group) instead of [LocalShadowGroup]. +func PointShadowWGSLForGroup(group uint32) string { + return fmt.Sprintf(`%s +@group(%[2]d) @binding(0) var point_shadow: PointShadow; +@group(%[2]d) @binding(1) var point_shadow_map: texture_depth_2d; +@group(%[2]d) @binding(2) var point_shadow_sampler: sampler_comparison; +%[3]s`, pointShadowStructWGSL, group, pointShadowSampleFnWGSL) +} + +// LitPBRSpotShadowWGSL is [LitPBRWGSL] with a spot light shadow: the same vertex stage (per-draw model and normal matrices from [PBRDrawUniform]), bind groups [CameraGroup], [LightGroup] and [PBRDrawGroup], and lighting, plus [SpotShadowWGSL] at [LocalShadowGroup]. The fragment stage multiplies the first spot light of the [LightRig] (lights.spot[0]) by sample_spot_shadow; every other light, the ambient term and emission are unshadowed. [ShadePointVisibility] with Spot0 set is its CPU reference. Use [NewLitPBRSpotShadowPipeline] or [LitPBRPipelineOptions].SpotShadowLayout to create a pipeline from it. +const LitPBRSpotShadowWGSL = litPBRPreludeWGSL + SpotShadowWGSL + litPBRSpotShadowFragmentHeadWGSL + ` return vec4(linear_to_srgb(lit), pbr_draw.base_color.a); } ` -const spotShadowLitShaderWGSL = CameraWGSL + "\n" + SpotShadowWGSL + ` -struct VertexIn { - @location(0) pos: vec3, - @location(1) normal: vec3, - @location(2) uv: vec2, +// litPBRSpotShadowLinearWGSL is [LitPBRSpotShadowWGSL] writing the lit linear color without sRGB encoding. +const litPBRSpotShadowLinearWGSL = litPBRPreludeWGSL + SpotShadowWGSL + litPBRSpotShadowFragmentHeadWGSL + ` return vec4(lit, pbr_draw.base_color.a); } +` -struct VertexOut { - @builtin(position) clip: vec4, - @location(0) world_pos: vec3, - @location(1) world_normal: vec3, +const litPBRSpotShadowFragmentHeadWGSL = ` +@fragment +fn fs_main(in: PBRVertexOut) -> @location(0) vec4 { + let view_dir = normalize(camera.eye.xyz - in.world_pos * camera.eye.w); + let spot_vis = sample_spot_shadow(in.world_pos, in.world_normal); + let lit = shade_pbr_visibility( + in.world_pos, + in.world_normal, + view_dir, + pbr_draw.base_color.rgb, + pbr_draw.pbr_params.x, + pbr_draw.pbr_params.y, + 1.0, + 1.0, + spot_vis, + ) + pbr_draw.emissive.rgb; +` + +// LitPBRPointShadowWGSL is [LitPBRWGSL] with a point light shadow: the same vertex stage, bind groups and lighting, plus [PointShadowWGSL] at [LocalShadowGroup]. The fragment stage multiplies the first point light of the [LightRig] (lights.point[0]) by sample_point_shadow; every other light, the ambient term and emission are unshadowed. [ShadePointVisibility] with Point0 set is its CPU reference. Use [NewLitPBRPointShadowPipeline] or [LitPBRPipelineOptions].PointShadowLayout to create a pipeline from it. +const LitPBRPointShadowWGSL = litPBRPreludeWGSL + PointShadowWGSL + litPBRPointShadowFragmentHeadWGSL + ` return vec4(linear_to_srgb(lit), pbr_draw.base_color.a); } +` -@vertex -fn vs_spot_lit(in: VertexIn) -> VertexOut { - var out: VertexOut; - out.clip = camera.view_proj * vec4(in.pos, 1.0); - out.world_pos = in.pos; - out.world_normal = in.normal; - return out; +// litPBRPointShadowLinearWGSL is [LitPBRPointShadowWGSL] writing the lit linear color without sRGB encoding. +const litPBRPointShadowLinearWGSL = litPBRPreludeWGSL + PointShadowWGSL + litPBRPointShadowFragmentHeadWGSL + ` return vec4(lit, pbr_draw.base_color.a); } +` +const litPBRPointShadowFragmentHeadWGSL = ` @fragment -fn fs_spot_lit(in: VertexOut) -> @location(0) vec4 { - let color = evaluate_spot_lighting(in.world_pos, in.world_normal, vec3(0.85, 0.85, 0.85)); - return vec4(clamp(color, vec3(0.0), vec3(1.0)), 1.0); -} +fn fs_main(in: PBRVertexOut) -> @location(0) vec4 { + let view_dir = normalize(camera.eye.xyz - in.world_pos * camera.eye.w); + let point_vis = sample_point_shadow(in.world_pos, in.world_normal); + let lit = shade_pbr_visibility( + in.world_pos, + in.world_normal, + view_dir, + pbr_draw.base_color.rgb, + pbr_draw.pbr_params.x, + pbr_draw.pbr_params.y, + 1.0, + point_vis, + 1.0, + ) + pbr_draw.emissive.rgb; ` -const pointShadowLitShaderWGSL = CameraWGSL + "\n" + PointShadowWGSL + ` -struct VertexIn { - @location(0) pos: vec3, - @location(1) normal: vec3, - @location(2) uv: vec2, +// NewLitPBRSpotShadowPipeline compiles [LitPBRSpotShadowWGSL] and creates a pipeline configured like [NewLitPBRPipeline] with spotLayout ([SpotShadowMap.Layout]) added at [LocalShadowGroup]. +func NewLitPBRSpotShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, spotLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error) { + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if spotLayout == nil { + return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: NewLitPBRSpotShadowPipeline requires a spot shadow bind group layout"} + } + return NewLitPBRPipelineWithOptions(cx, dev, camLayout, lightLayout, drawLayout, LitPBRPipelineOptions{SpotShadowLayout: spotLayout, DepthFormat: depthFormat}) } -struct VertexOut { - @builtin(position) clip: vec4, - @location(0) world_pos: vec3, - @location(1) world_normal: vec3, +// NewLitPBRPointShadowPipeline compiles [LitPBRPointShadowWGSL] and creates a pipeline configured like [NewLitPBRPipeline] with pointLayout ([PointShadowMap.Layout]) added at [LocalShadowGroup]. +func NewLitPBRPointShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, pointLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error) { + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if pointLayout == nil { + return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: NewLitPBRPointShadowPipeline requires a point shadow bind group layout"} + } + return NewLitPBRPipelineWithOptions(cx, dev, camLayout, lightLayout, drawLayout, LitPBRPipelineOptions{PointShadowLayout: pointLayout, DepthFormat: depthFormat}) } -@vertex -fn vs_point_lit(in: VertexIn) -> VertexOut { - var out: VertexOut; - out.clip = camera.view_proj * vec4(in.pos, 1.0); - out.world_pos = in.pos; - out.world_normal = in.normal; - return out; +// localShadowPlanes validates the near and far planes both configs carry. +func localShadowPlanes(kind string, near, far float32) error { + if !finite(near) || near <= 0 { + return fmt.Errorf("%w: %s Near %v must be finite and positive", ErrInvalidLocalShadow, kind, near) + } + if !finite(far) || far <= near { + return fmt.Errorf("%w: %s Far %v must be finite and greater than Near %v", ErrInvalidLocalShadow, kind, far, near) + } + return nil } -@fragment -fn fs_point_lit(in: VertexOut) -> @location(0) vec4 { - let color = evaluate_point_lighting(in.world_pos, in.world_normal, vec3(0.85, 0.85, 0.85)); - return vec4(clamp(color, vec3(0.0), vec3(1.0)), 1.0); +func validateLocalShadowCommon(kind string, depthBias, normalBias float32, filter LocalShadowFilter, cull gpu.CullMode, maxCasters uint32) error { + if !finite(depthBias) || depthBias < 0 { + return fmt.Errorf("%w: %s DepthBias %v must be finite and non-negative", ErrInvalidLocalShadow, kind, depthBias) + } + if !finite(normalBias) || normalBias < 0 { + return fmt.Errorf("%w: %s NormalBias %v must be finite and non-negative", ErrInvalidLocalShadow, kind, normalBias) + } + if !localShadowValidFilter(filter) { + return fmt.Errorf("%w: invalid %s Filter %d", ErrInvalidLocalShadow, kind, filter) + } + if !localShadowValidCull(cull) { + return fmt.Errorf("%w: invalid %s CullMode %d", ErrInvalidLocalShadow, kind, cull) + } + if maxCasters > MaxLocalShadowCasters { + return fmt.Errorf("%w: %s MaxCasters %d exceeds MaxLocalShadowCasters (%d)", ErrInvalidLocalShadow, kind, maxCasters, MaxLocalShadowCasters) + } + return nil +} + +// localShadowFar returns the far plane for a light with the given Range: the Range itself when it bounds the light, otherwise the configured far. +func localShadowFar(kind string, lightRange, near, cfgFar float32) (float32, error) { + far := cfgFar + if lightRange > 0 { + far = lightRange + } + if far <= near { + return 0, fmt.Errorf("%w: %s light Range %v must be greater than the shadow Near %v", ErrInvalidLocalShadow, kind, far, near) + } + return far, nil +} + +func localShadowFilterMode(f LocalShadowFilter) float32 { + if f == LocalShadowFilterPCF3x3 { + return 1 + } + return 0 } -` // SpotShadowConfig configures a perspective 2D [SpotShadowMap]. type SpotShadowConfig struct { - // Resolution is the width and height of the square depth shadow map in texels. - // Zero defaults to 1024. + // Resolution is the width and height of the square depth shadow map in texels. Zero defaults to 1024. Resolution uint32 - // DepthBias subtracts a constant NDC [0, 1] bias during depth comparison to - // avoid shadow acne. Zero defaults to 0.0015 when using DefaultSpotShadowConfig; - // explicit zero disables constant depth bias. + // Near is the near plane distance of the shadow projection. Zero defaults to [DefaultLocalShadowNear]. + Near float32 + // Far is the far plane distance used when the spot light's Range is 0; a light with a Range uses that instead. Zero defaults to [DefaultLocalShadowFar]. + Far float32 + // DepthBias subtracts a constant NDC [0, 1] bias during depth comparison to avoid shadow acne. [DefaultSpotShadowConfig] sets 0.0015; zero disables it. DepthBias float32 - // NormalBias offsets the shaded world position along its surface normal before - // projecting into light space. + // NormalBias offsets the shaded world position along its surface normal before projecting into light space. NormalBias float32 // Filter selects hard single-tap or 3x3 PCF comparison sampling. Filter LocalShadowFilter // CullMode sets face culling for the shadow caster pass (default gpu.CullNone). CullMode gpu.CullMode - // MaxCasters is the maximum number of DrawCaster calls per shadow pass. - // Zero defaults to 256. + // MaxCasters is the maximum number of [SpotShadowMap.DrawCaster] calls per shadow pass, at most [MaxLocalShadowCasters]. Zero defaults to [DefaultLocalShadowMaxCasters]. MaxCasters uint32 // Label names GPU resources in capture tools. Label string @@ -373,588 +406,122 @@ type SpotShadowConfig struct { func DefaultSpotShadowConfig() SpotShadowConfig { return SpotShadowConfig{ Resolution: defaultSpotShadowResolution, + Near: DefaultLocalShadowNear, + Far: DefaultLocalShadowFar, DepthBias: defaultLocalShadowDepthBias, NormalBias: defaultLocalShadowNormalBias, Filter: LocalShadowFilterPCF3x3, CullMode: gpu.CullNone, - MaxCasters: defaultSpotMaxCasters, + MaxCasters: DefaultLocalShadowMaxCasters, } } -// Normalized returns a copy of c with zero Resolution and MaxCasters filled with defaults. +// Normalized returns a copy of c with zero Resolution, Near, Far and MaxCasters filled with defaults. func (c SpotShadowConfig) Normalized() SpotShadowConfig { if c.Resolution == 0 { c.Resolution = defaultSpotShadowResolution } + if c.Near == 0 { + c.Near = DefaultLocalShadowNear + } + if c.Far == 0 { + c.Far = DefaultLocalShadowFar + } if c.MaxCasters == 0 { - c.MaxCasters = defaultSpotMaxCasters + c.MaxCasters = DefaultLocalShadowMaxCasters } return c } -// Validate checks that c's resolution, biases, filter, and cull mode are valid. -// Every error wraps [ErrInvalidLocalShadow]. +// Validate checks that c's planes, biases, filter, cull mode and caster count are valid. Every error wraps [ErrInvalidLocalShadow]. func (c SpotShadowConfig) Validate() error { n := c.Normalized() - if !finite(n.DepthBias) || n.DepthBias < 0 { - return fmt.Errorf("%w: spot DepthBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.DepthBias) - } - if !finite(n.NormalBias) || n.NormalBias < 0 { - return fmt.Errorf("%w: spot NormalBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.NormalBias) - } - if !localShadowValidFilter(n.Filter) { - return fmt.Errorf("%w: invalid spot Filter %d", ErrInvalidLocalShadow, n.Filter) - } - if !localShadowValidCull(n.CullMode) { - return fmt.Errorf("%w: invalid spot CullMode %d", ErrInvalidLocalShadow, n.CullMode) + if err := localShadowPlanes("spot", n.Near, n.Far); err != nil { + return err } - return nil + return validateLocalShadowCommon("spot", n.DepthBias, n.NormalBias, n.Filter, n.CullMode, n.MaxCasters) } -// SpotShadowLight defines the spot light parameters used to build the perspective -// shadow projection and evaluate direct shadowed spot lighting. -type SpotShadowLight struct { - Position math3d.Vec3 - Direction math3d.Vec3 - Color math3d.Vec3 - Intensity float32 - Near float32 - Range float32 - InnerConeAngle float32 // half-angle in radians, 0 <= InnerConeAngle <= OuterConeAngle - OuterConeAngle float32 // half-angle in radians, 0 < OuterConeAngle < pi/2 - Ambient math3d.Vec3 +// SpotShadowUniform is the packed uniform data matching the WGSL SpotShadow block declared by [SpotShadowWGSL]. +type SpotShadowUniform struct { + // ViewProj is the spot light's [0, 1]-depth perspective view-projection matrix. + ViewProj math3d.Mat4 + DepthBias float32 + NormalBias float32 + InvResolution float32 + // FilterMode is 0 for [LocalShadowFilterHard] and 1 for [LocalShadowFilterPCF3x3]. + FilterMode float32 } -// Validate checks that every vector and scalar is finite and within valid physical -// and perspective-projection bounds. Every error wraps [ErrInvalidLocalShadow]. -func (l SpotShadowLight) Validate() error { - if !finite3(l.Position) { - return fmt.Errorf("%w: spot Position is not finite", ErrInvalidLocalShadow) - } - if !finite3(l.Direction) || l.Direction.LenSq() < 1e-12 { - return fmt.Errorf("%w: spot Direction must be finite and non-zero", ErrInvalidLocalShadow) - } - if !finite3(l.Color) || l.Color.X < 0 || l.Color.Y < 0 || l.Color.Z < 0 { - return fmt.Errorf("%w: spot Color must be finite and non-negative", ErrInvalidLocalShadow) - } - if !finite3(l.Ambient) || l.Ambient.X < 0 || l.Ambient.Y < 0 || l.Ambient.Z < 0 { - return fmt.Errorf("%w: spot Ambient must be finite and non-negative", ErrInvalidLocalShadow) - } - if !finite(l.Intensity) || l.Intensity < 0 { - return fmt.Errorf("%w: spot Intensity %v must be finite and non-negative", ErrInvalidLocalShadow, l.Intensity) - } - if !finite(l.Near) || l.Near <= 0 { - return fmt.Errorf("%w: spot Near %v must be finite and positive", ErrInvalidLocalShadow, l.Near) +// SpotShadowViewProj returns the [0, 1]-depth perspective view-projection matrix a [SpotShadowMap] renders light with: looking from light.Position along light.Direction with a square field of view of 2 * light.OuterConeAngle, from near to far. +func SpotShadowViewProj(light SpotLight, near, far float32) math3d.Mat4 { + dir, ok := spotUnitDirection(light) + if !ok { + dir = math3d.Vec3{Y: -1} } - if !finite(l.Range) || l.Range <= l.Near { - return fmt.Errorf("%w: spot Range %v must be finite and greater than Near %v", ErrInvalidLocalShadow, l.Range, l.Near) - } - const maxOuter = float32(math.Pi/2 - 1e-3) - if !finite(l.OuterConeAngle) || l.OuterConeAngle <= 0 || l.OuterConeAngle >= maxOuter { - return fmt.Errorf("%w: spot OuterConeAngle %v must be in (0, pi/2)", ErrInvalidLocalShadow, l.OuterConeAngle) - } - if !finite(l.InnerConeAngle) || l.InnerConeAngle < 0 || l.InnerConeAngle > l.OuterConeAngle { - return fmt.Errorf("%w: spot InnerConeAngle %v must be in [0, OuterConeAngle %v]", ErrInvalidLocalShadow, l.InnerConeAngle, l.OuterConeAngle) - } - return nil -} - -// ViewMatrix returns the right-handed shadow view matrix looking from l.Position -// along l.Direction. -func (l SpotShadowLight) ViewMatrix() math3d.Mat4 { - dir := l.Direction.Norm() up := math3d.Vec3Up() if localShadowAbs(dir.Y) > 0.99 { up = math3d.Vec3{Z: 1} } - return math3d.LookAt(l.Position, l.Position.Add(dir), up) -} - -// ProjMatrix returns the [0, 1] NDC depth perspective projection matching -// fovY = 2 * l.OuterConeAngle, aspect = 1, near = l.Near, and far = l.Range. -func (l SpotShadowLight) ProjMatrix() math3d.Mat4 { - return math3d.Perspective(2*l.OuterConeAngle, 1.0, l.Near, l.Range) -} - -// ViewProj returns ProjMatrix().Mul(ViewMatrix()). -func (l SpotShadowLight) ViewProj() math3d.Mat4 { - return l.ProjMatrix().Mul(l.ViewMatrix()) + view := math3d.LookAt(light.Position, light.Position.Add(dir), up) + return math3d.Perspective(2*light.OuterConeAngle, 1.0, near, far).Mul(view) } -// SpotShadowUniform is the packed uniform data matching the WGSL SpotShadow block -// declared by [SpotShadowWGSL]. -type SpotShadowUniform struct { - ViewProj math3d.Mat4 - Position math3d.Vec3 - Range float32 - Direction math3d.Vec3 - CosInner float32 - ColorIntensity math3d.Vec3 - CosOuter float32 - DepthBias float32 - NormalBias float32 - InvResolution float32 - FilterMode float32 - Ambient math3d.Vec3 - Near float32 -} - -// NewSpotShadowUniform computes the uniform data for light and cfg. -func NewSpotShadowUniform(light SpotShadowLight, cfg SpotShadowConfig) SpotShadowUniform { - n := cfg.Normalized() - dir := light.Direction.Norm() - filterMode := float32(0) - if n.Filter == LocalShadowFilterPCF3x3 { - filterMode = 1 - } - return SpotShadowUniform{ - ViewProj: light.ViewProj(), - Position: light.Position, - Range: light.Range, - Direction: dir, - CosInner: float32(math.Cos(float64(light.InnerConeAngle))), - ColorIntensity: light.Color.Scale(light.Intensity), - CosOuter: float32(math.Cos(float64(light.OuterConeAngle))), - DepthBias: n.DepthBias, - NormalBias: n.NormalBias, - InvResolution: 1.0 / float32(n.Resolution), - FilterMode: filterMode, - Ambient: light.Ambient, - Near: light.Near, - } -} - -// Encode writes u into dst in the little-endian layout declared by [SpotShadowWGSL] -// and returns dst[:SpotShadowUniformSize]. It allocates nothing and panics if -// len(dst) < SpotShadowUniformSize. -func (u *SpotShadowUniform) Encode(dst []byte) []byte { - if len(dst) < SpotShadowUniformSize { - panic("render3d: SpotShadowUniform.Encode: dst shorter than SpotShadowUniformSize") +// NewSpotShadowUniform computes the shadow uniform data for the [LightRig] spot light light under cfg. The projection's far plane is light.Range, or cfg.Far when Range is 0. It returns an error wrapping [ErrInvalidLight] when light is invalid, and one wrapping [ErrInvalidLocalShadow] when cfg is invalid, the cone is wider than [MaxSpotShadowConeAngle], or the far plane is not beyond the near plane. +func NewSpotShadowUniform(light SpotLight, cfg SpotShadowConfig) (SpotShadowUniform, error) { + if err := light.Validate(); err != nil { + return SpotShadowUniform{}, err } - dst = dst[:SpotShadowUniformSize] - off := 0 - putF := func(v float32) { - binary.LittleEndian.PutUint32(dst[off:], math.Float32bits(v)) - off += 4 - } - for _, f := range u.ViewProj { - putF(f) - } - putF(u.Position.X) - putF(u.Position.Y) - putF(u.Position.Z) - putF(u.Range) - putF(u.Direction.X) - putF(u.Direction.Y) - putF(u.Direction.Z) - putF(u.CosInner) - putF(u.ColorIntensity.X) - putF(u.ColorIntensity.Y) - putF(u.ColorIntensity.Z) - putF(u.CosOuter) - putF(u.DepthBias) - putF(u.NormalBias) - putF(u.InvResolution) - putF(u.FilterMode) - putF(u.Ambient.X) - putF(u.Ambient.Y) - putF(u.Ambient.Z) - putF(u.Near) - return dst -} - -// SpotShadowMap manages a depth-only perspective 2D shadow map, its depth caster -// pipeline, and its sampling bind group for a spot light on a [gpu.Device]. -type SpotShadowMap struct { - cfg SpotShadowConfig - rt *gpu.RenderTarget - sampler *gpu.Sampler - uniformBuf *gpu.Buffer - casterBuf *gpu.Buffer - layout *gpu.BindGroupLayout - bindGroup *gpu.BindGroup - casterLayout *gpu.BindGroupLayout - casterGroup *gpu.BindGroup - depthPipe *gpu.Pipeline - uniforms SpotShadowUniform - casterSlot uint32 - uniformBytes [SpotShadowUniformSize]byte - casterScratch [localShadowCasterDataSize]byte -} - -// NewSpotShadowMap creates a depth-only perspective spot shadow map and its GPU -// resources scoped to cx. Invalid configuration returns an error wrapping -// [ErrInvalidLocalShadow]; device errors are returned as [gpu.Error]. -func NewSpotShadowMap(cx *core.Scope, dev *gpu.Device, cfg SpotShadowConfig) (*SpotShadowMap, error) { if err := cfg.Validate(); err != nil { - return nil, err + return SpotShadowUniform{}, err } - if dev == nil { - return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + if light.OuterConeAngle > MaxSpotShadowConeAngle { + return SpotShadowUniform{}, fmt.Errorf("%w: spot OuterConeAngle %v exceeds MaxSpotShadowConeAngle %v", ErrInvalidLocalShadow, light.OuterConeAngle, MaxSpotShadowConeAngle) } n := cfg.Normalized() - maxDim := dev.Limits().MaxTextureDimension2D - if maxDim > 0 && n.Resolution > maxDim { - return nil, fmt.Errorf("%w: spot resolution %d exceeds MaxTextureDimension2D %d", ErrInvalidLocalShadow, n.Resolution, maxDim) - } - - label := n.Label - if label == "" { - label = "render3d.spot_shadow" - } - - var closers []interface{ Close() error } - fail := func(err error) (*SpotShadowMap, error) { - for i := len(closers) - 1; i >= 0; i-- { - if closers[i] != nil { - _ = closers[i].Close() - } - } - return nil, err - } - - rt, err := dev.CreateRenderTarget(cx, gpu.RenderTargetDesc{ - Label: label + ".depth", - Width: n.Resolution, - Height: n.Resolution, - DepthFormat: gpu.FormatDepth32Float, - Retained: n.Retained, - }) - if err != nil { - return fail(err) - } - closers = append(closers, rt) - - filterMode := gpu.FilterNearest - if n.Filter == LocalShadowFilterPCF3x3 { - filterMode = gpu.FilterLinear - } - samp, err := dev.CreateSampler(cx, gpu.SamplerDesc{ - Label: label + ".sampler", - MinFilter: filterMode, - MagFilter: filterMode, - AddressU: gpu.AddressClampToEdge, - AddressV: gpu.AddressClampToEdge, - AddressW: gpu.AddressClampToEdge, - Compare: gpu.CompareLessEqual, - Retained: n.Retained, - }) - if err != nil { - return fail(err) - } - closers = append(closers, samp) - - uniformBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ - Label: label + ".uniform", - Size: SpotShadowUniformSize, - Usage: gpu.UsageUniform | gpu.UsageCopyDst, - Retained: n.Retained, - }) - if err != nil { - return fail(err) - } - closers = append(closers, uniformBuf) - - casterBufSize := uint64(n.MaxCasters) * localShadowCasterSlotStride - casterBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ - Label: label + ".casters", - Size: casterBufSize, - Usage: gpu.UsageUniform | gpu.UsageCopyDst, - Retained: n.Retained, - }) - if err != nil { - return fail(err) - } - closers = append(closers, casterBuf) - - layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ - Label: label + ".layout", - Entries: []gpu.BindGroupLayoutEntry{ - {Binding: 0, Visibility: gpu.StageVertex | gpu.StageFragment, Type: gpu.BindingUniform}, - {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, - {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingComparisonSampler}, - }, - }) - if err != nil { - return fail(err) - } - closers = append(closers, layout) - - bindGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ - Label: label + ".bind_group", - Layout: layout, - Entries: []gpu.BindGroupEntry{ - {Binding: 0, Buffer: uniformBuf, Size: SpotShadowUniformSize}, - {Binding: 1, Texture: rt.Depth}, - {Binding: 2, Sampler: samp}, - }, - }) - if err != nil { - return fail(err) - } - closers = append(closers, bindGroup) - - casterLayout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ - Label: label + ".caster_layout", - Entries: []gpu.BindGroupLayoutEntry{ - {Binding: 0, Visibility: gpu.StageVertex, Type: gpu.BindingUniform, HasDynamicOffset: true}, - }, - }) - if err != nil { - return fail(err) - } - closers = append(closers, casterLayout) - - casterGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ - Label: label + ".caster_group", - Layout: casterLayout, - Entries: []gpu.BindGroupEntry{ - {Binding: 0, Buffer: casterBuf, Offset: 0, Size: localShadowCasterDataSize}, - }, - }) - if err != nil { - return fail(err) - } - closers = append(closers, casterGroup) - - depthMod, err := gpu.CompileWGSL(localShadowDepthWGSL) - if err != nil { - return fail(err) - } - depthPipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ - Label: label + ".depth_pipe", - Vertex: gpu.ShaderStage{Module: depthMod, EntryPoint: "vs_local_shadow_depth"}, - Layouts: []*gpu.BindGroupLayout{casterLayout}, - VertexBuffers: []gpu.VertexBufferLayout{MeshVertexLayout()}, - Primitive: gpu.PrimitiveState{ - Topology: gpu.TopologyTriangleList, - FrontFace: gpu.FrontCCW, - CullMode: n.CullMode, - }, - DepthStencil: &gpu.DepthStencilState{ - Format: gpu.FormatDepth32Float, - DepthWrite: true, - DepthCompare: gpu.CompareLess, - }, - Retained: n.Retained, - }) + far, err := localShadowFar("spot", light.Range, n.Near, n.Far) if err != nil { - return fail(err) + return SpotShadowUniform{}, err } - - return &SpotShadowMap{ - cfg: n, - rt: rt, - sampler: samp, - uniformBuf: uniformBuf, - casterBuf: casterBuf, - layout: layout, - bindGroup: bindGroup, - casterLayout: casterLayout, - casterGroup: casterGroup, - depthPipe: depthPipe, + return SpotShadowUniform{ + ViewProj: SpotShadowViewProj(light, n.Near, far), + DepthBias: n.DepthBias, + NormalBias: n.NormalBias, + InvResolution: 1.0 / float32(n.Resolution), + FilterMode: localShadowFilterMode(n.Filter), }, nil } -// Update validates light, updates the spot shadow projection and uniforms, and -// writes the uniform buffer on dev without heap allocations. -func (s *SpotShadowMap) Update(dev *gpu.Device, light SpotShadowLight) error { - if s == nil || !s.Valid() { - return fmt.Errorf("%w: spot shadow map is not valid", ErrInvalidLocalShadow) - } - if err := light.Validate(); err != nil { - return err - } - if dev == nil { - return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} - } - s.uniforms = NewSpotShadowUniform(light, s.cfg) - dev.WriteBuffer(s.uniformBuf, 0, s.uniforms.Encode(s.uniformBytes[:])) - return nil -} - -// Uniforms returns the last spot shadow uniform data written via [SpotShadowMap.Update]. -func (s *SpotShadowMap) Uniforms() SpotShadowUniform { - if s == nil { - return SpotShadowUniform{} - } - return s.uniforms -} - -// ViewProj returns the spot light's perspective view-projection matrix. -func (s *SpotShadowMap) ViewProj() math3d.Mat4 { - if s == nil { - return math3d.Mat4Identity() - } - return s.uniforms.ViewProj -} - -// Config returns the normalized [SpotShadowConfig]. -func (s *SpotShadowMap) Config() SpotShadowConfig { - if s == nil { - return SpotShadowConfig{} - } - return s.cfg -} - -// RenderTarget returns the underlying depth-only [gpu.RenderTarget]. -func (s *SpotShadowMap) RenderTarget() *gpu.RenderTarget { - if s == nil { - return nil - } - return s.rt -} - -// DepthTexture returns the underlying Depth32Float [gpu.Texture]. -func (s *SpotShadowMap) DepthTexture() *gpu.Texture { - if s == nil || s.rt == nil { - return nil - } - return s.rt.Depth -} - -// Sampler returns the comparison [gpu.Sampler] bound in [SpotShadowMap.BindGroup]. -func (s *SpotShadowMap) Sampler() *gpu.Sampler { - if s == nil { - return nil - } - return s.sampler -} - -// Layout returns the bind group layout for sampling this spot shadow map -// (binding 0: SpotShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison). -func (s *SpotShadowMap) Layout() *gpu.BindGroupLayout { - if s == nil { - return nil - } - return s.layout -} - -// BindGroup returns the bind group to set at [LocalShadowGroup] (or any group slot -// matching [SpotShadowMap.Layout]) during the lit render pass. -func (s *SpotShadowMap) BindGroup() *gpu.BindGroup { - if s == nil { - return nil - } - return s.bindGroup -} - -// ByteSize returns the GPU memory held by the depth texture and uniform buffers. -func (s *SpotShadowMap) ByteSize() uint64 { - if s == nil { - return 0 - } - depthBytes := uint64(s.cfg.Resolution) * uint64(s.cfg.Resolution) * 4 - return depthBytes + s.uniformBuf.Size() + s.casterBuf.Size() -} - -// Valid reports whether all underlying GPU resources are open and live. -func (s *SpotShadowMap) Valid() bool { - return s != nil && - s.rt != nil && s.rt.Valid() && - s.sampler != nil && s.sampler.Valid() && - s.uniformBuf != nil && s.uniformBuf.Valid() && - s.casterBuf != nil && s.casterBuf.Valid() && - s.layout != nil && s.layout.Valid() && - s.bindGroup != nil && s.bindGroup.Valid() && - s.casterLayout != nil && s.casterLayout.Valid() && - s.casterGroup != nil && s.casterGroup.Valid() && - s.depthPipe != nil && s.depthPipe.Valid() -} - -// LocalShadowPassRecorder is satisfied by both [*gpu.Encoder] and [*gpu.Frame], -// allowing [SpotShadowMap.BeginShadowPass] and [PointShadowMap.BeginFacePass] -// to record shadow passes both inside [gpu.ViewProps.OnFrame] and on standalone -// command encoders. -type LocalShadowPassRecorder interface { - BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass -} - -// BeginShadowPass begins a depth-only render pass targeting the spot shadow map, -// clears depth to 1.0, sets the full viewport/scissor, binds the depth pipeline, -// and resets the caster dynamic-offset slot counter. -func (s *SpotShadowMap) BeginShadowPass(rec LocalShadowPassRecorder) *gpu.RenderPass { - if s == nil || rec == nil || !s.Valid() { - return nil - } - s.casterSlot = 0 - pass := rec.BeginRenderPass(gpu.RenderPassDesc{ - Label: s.cfg.Label + ".pass", - DepthStencil: &gpu.DepthStencilAttachment{ - Texture: s.rt.Depth, - DepthLoadOp: gpu.LoadClear, - DepthStoreOp: gpu.StoreStore, - ClearDepth: 1.0, - }, - }) - res := s.cfg.Resolution - pass.SetViewport(0, 0, float32(res), float32(res), 0, 1) - pass.SetScissor(0, 0, int32(res), int32(res)) - pass.SetPipeline(s.depthPipe) - return pass -} - -// DrawCaster records a shadow caster draw for mesh transformed by model inside -// a pass started by [SpotShadowMap.BeginShadowPass]. Each call uses a distinct -// 256-byte aligned dynamic-offset uniform slot so multiple casters can be drawn -// in one pass without overwriting earlier transforms. -func (s *SpotShadowMap) DrawCaster(dev *gpu.Device, pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) { - if s == nil || dev == nil || pass == nil || !s.Valid() || !mesh.Valid() { - return - } - if s.casterSlot >= s.cfg.MaxCasters { - return - } - offset := uint64(s.casterSlot) * localShadowCasterSlotStride - s.casterSlot++ - encodeLocalShadowCaster(s.casterScratch[:], s.uniforms.ViewProj, model) - dev.WriteBuffer(s.casterBuf, offset, s.casterScratch[:]) - pass.SetBindGroup(0, s.casterGroup, uint32(offset)) - mesh.Draw(pass) -} - -// Close releases all GPU resources owned by s. It is safe to call on a nil -// receiver or more than once. -func (s *SpotShadowMap) Close() error { - if s == nil { - return nil +// Encode writes u into dst in the little-endian layout declared by [SpotShadowWGSL] and returns dst[:SpotShadowUniformSize]. It allocates nothing and panics if len(dst) < SpotShadowUniformSize. +func (u *SpotShadowUniform) Encode(dst []byte) []byte { + if len(dst) < SpotShadowUniformSize { + panic("render3d: SpotShadowUniform.Encode: dst shorter than SpotShadowUniformSize") } - var err error - for _, c := range []interface{ Close() error }{ - s.depthPipe, - s.casterGroup, - s.casterLayout, - s.bindGroup, - s.layout, - s.casterBuf, - s.uniformBuf, - s.sampler, - s.rt, - } { - if c != nil { - err = errors.Join(err, c.Close()) - } + dst = dst[:SpotShadowUniformSize] + for i, f := range u.ViewProj { + binary.LittleEndian.PutUint32(dst[4*i:], math.Float32bits(f)) } - return err + putVec4(dst[64:], math3d.Vec4{X: u.DepthBias, Y: u.NormalBias, Z: u.InvResolution, W: u.FilterMode}) + return dst } // PointShadowConfig configures an omnidirectional 3x2 depth-atlas [PointShadowMap]. type PointShadowConfig struct { - // FaceResolution is the width and height of one cube face tile in texels. - // The 3x2 depth atlas has size (3 * FaceResolution) x (2 * FaceResolution). - // Zero defaults to 512. + // FaceResolution is the width and height of one cube face tile in texels. The 3x2 depth atlas has size (3 * FaceResolution) x (2 * FaceResolution). Zero defaults to 512. FaceResolution uint32 + // Near is the near plane distance of the six face projections. Zero defaults to [DefaultLocalShadowNear]. + Near float32 + // Far is the far plane distance used when the point light's Range is 0; a light with a Range uses that instead. Zero defaults to [DefaultLocalShadowFar]. + Far float32 // DepthBias subtracts a constant NDC [0, 1] bias during depth comparison. DepthBias float32 - // NormalBias offsets the shaded world position along its surface normal before - // selecting the cube face and comparing depth. + // NormalBias offsets the shaded world position along its surface normal before selecting the cube face and comparing depth. NormalBias float32 // Filter selects hard single-tap or 3x3 PCF comparison sampling. Filter LocalShadowFilter // CullMode sets face culling for the shadow caster passes (default gpu.CullNone). CullMode gpu.CullMode - // MaxCasters is the total maximum DrawCaster calls across all 6 faces per frame. - // Zero defaults to 1024. + // MaxCasters is the maximum number of [PointShadowMap.DrawCaster] calls per cube face pass, at most [MaxLocalShadowCasters]. Each face has its own slots, so faces can be recorded in any order or skipped. Zero defaults to [DefaultLocalShadowMaxCasters]. MaxCasters uint32 // Label names GPU resources in capture tools. Label string @@ -962,27 +529,33 @@ type PointShadowConfig struct { Retained bool } -// DefaultPointShadowConfig returns a ready-to-use 512x512-per-face PCF 3x3 point -// shadow configuration. +// DefaultPointShadowConfig returns a ready-to-use 512x512-per-face PCF 3x3 point shadow configuration. func DefaultPointShadowConfig() PointShadowConfig { return PointShadowConfig{ FaceResolution: defaultPointShadowResolution, + Near: DefaultLocalShadowNear, + Far: DefaultLocalShadowFar, DepthBias: defaultLocalShadowDepthBias, NormalBias: defaultLocalShadowNormalBias, Filter: LocalShadowFilterPCF3x3, CullMode: gpu.CullNone, - MaxCasters: defaultPointMaxCasters, + MaxCasters: DefaultLocalShadowMaxCasters, } } -// Normalized returns a copy of c with zero FaceResolution and MaxCasters filled -// with defaults. +// Normalized returns a copy of c with zero FaceResolution, Near, Far and MaxCasters filled with defaults. func (c PointShadowConfig) Normalized() PointShadowConfig { if c.FaceResolution == 0 { c.FaceResolution = defaultPointShadowResolution } + if c.Near == 0 { + c.Near = DefaultLocalShadowNear + } + if c.Far == 0 { + c.Far = DefaultLocalShadowFar + } if c.MaxCasters == 0 { - c.MaxCasters = defaultPointMaxCasters + c.MaxCasters = DefaultLocalShadowMaxCasters } return c } @@ -993,66 +566,55 @@ func (c PointShadowConfig) AtlasSize() (width, height uint32) { return n.FaceResolution * PointShadowAtlasCols, n.FaceResolution * PointShadowAtlasRows } -// Validate checks that c's resolution, biases, filter, and cull mode are valid. -// Every error wraps [ErrInvalidLocalShadow]. +// Validate checks that c's resolution, planes, biases, filter, cull mode and caster count are valid. Every error wraps [ErrInvalidLocalShadow]. func (c PointShadowConfig) Validate() error { n := c.Normalized() if uint64(n.FaceResolution)*PointShadowAtlasCols > math.MaxUint32 { return fmt.Errorf("%w: point FaceResolution %d overflows atlas dimensions", ErrInvalidLocalShadow, n.FaceResolution) } - if !finite(n.DepthBias) || n.DepthBias < 0 { - return fmt.Errorf("%w: point DepthBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.DepthBias) - } - if !finite(n.NormalBias) || n.NormalBias < 0 { - return fmt.Errorf("%w: point NormalBias %v must be finite and non-negative", ErrInvalidLocalShadow, n.NormalBias) - } - if !localShadowValidFilter(n.Filter) { - return fmt.Errorf("%w: invalid point Filter %d", ErrInvalidLocalShadow, n.Filter) - } - if !localShadowValidCull(n.CullMode) { - return fmt.Errorf("%w: invalid point CullMode %d", ErrInvalidLocalShadow, n.CullMode) + if err := localShadowPlanes("point", n.Near, n.Far); err != nil { + return err } - return nil + return validateLocalShadowCommon("point", n.DepthBias, n.NormalBias, n.Filter, n.CullMode, n.MaxCasters) } -// PointShadowLight defines the point light parameters used to build the six -// 90-degree cube-face shadow projections and evaluate omnidirectional lighting. -type PointShadowLight struct { - Position math3d.Vec3 - Color math3d.Vec3 - Intensity float32 - Near float32 - Range float32 - Ambient math3d.Vec3 +// PointShadowUniform is the packed uniform data matching the WGSL PointShadow block declared by [PointShadowWGSL]. +type PointShadowUniform struct { + Position math3d.Vec3 + Near float32 + Far float32 + DepthBias float32 + NormalBias float32 + InvFaceResolution float32 + // FilterMode is 0 for [LocalShadowFilterHard] and 1 for [LocalShadowFilterPCF3x3]. + FilterMode float32 } -// Validate checks that all fields are finite and within valid projection bounds. -// Every error wraps [ErrInvalidLocalShadow]. -func (l PointShadowLight) Validate() error { - if !finite3(l.Position) { - return fmt.Errorf("%w: point Position is not finite", ErrInvalidLocalShadow) - } - if !finite3(l.Color) || l.Color.X < 0 || l.Color.Y < 0 || l.Color.Z < 0 { - return fmt.Errorf("%w: point Color must be finite and non-negative", ErrInvalidLocalShadow) - } - if !finite3(l.Ambient) || l.Ambient.X < 0 || l.Ambient.Y < 0 || l.Ambient.Z < 0 { - return fmt.Errorf("%w: point Ambient must be finite and non-negative", ErrInvalidLocalShadow) - } - if !finite(l.Intensity) || l.Intensity < 0 { - return fmt.Errorf("%w: point Intensity %v must be finite and non-negative", ErrInvalidLocalShadow, l.Intensity) +// NewPointShadowUniform computes the shadow uniform data for the [LightRig] point light light under cfg. The far plane is light.Range, or cfg.Far when Range is 0. It returns an error wrapping [ErrInvalidLight] when light is invalid, and one wrapping [ErrInvalidLocalShadow] when cfg is invalid or the far plane is not beyond the near plane. +func NewPointShadowUniform(light PointLight, cfg PointShadowConfig) (PointShadowUniform, error) { + if err := light.Validate(); err != nil { + return PointShadowUniform{}, err } - if !finite(l.Near) || l.Near <= 0 { - return fmt.Errorf("%w: point Near %v must be finite and positive", ErrInvalidLocalShadow, l.Near) + if err := cfg.Validate(); err != nil { + return PointShadowUniform{}, err } - if !finite(l.Range) || l.Range <= l.Near { - return fmt.Errorf("%w: point Range %v must be finite and greater than Near %v", ErrInvalidLocalShadow, l.Range, l.Near) + n := cfg.Normalized() + far, err := localShadowFar("point", light.Range, n.Near, n.Far) + if err != nil { + return PointShadowUniform{}, err } - return nil + return PointShadowUniform{ + Position: light.Position, + Near: n.Near, + Far: far, + DepthBias: n.DepthBias, + NormalBias: n.NormalBias, + InvFaceResolution: 1.0 / float32(n.FaceResolution), + FilterMode: localShadowFilterMode(n.Filter), + }, nil } -// pointFaceBasis holds the canonical right-handed forward and up vectors for -// cube faces 0..5 matching [gpu.CubeFacePosX]..[gpu.CubeFaceNegZ] and -// [PointShadowWGSL]. +// pointFaceBasis holds the canonical right-handed forward and up vectors for cube faces 0..5 matching [gpu.CubeFacePosX]..[gpu.CubeFaceNegZ] and [PointShadowWGSL]. var pointFaceBasis = [PointShadowFaceCount]struct { forward math3d.Vec3 up math3d.Vec3 @@ -1065,165 +627,67 @@ var pointFaceBasis = [PointShadowFaceCount]struct { gpu.CubeFaceNegZ: {forward: math3d.Vec3{Z: -1}, up: math3d.Vec3{Y: 1}}, } -// FaceViewMatrix returns the right-handed view matrix for cube face (0..5). -// Out-of-range face indices clamp to [gpu.CubeFacePosX]. -func (l PointShadowLight) FaceViewMatrix(face gpu.CubeFace) math3d.Mat4 { +// FaceViewProj returns the 90-degree [0, 1]-depth perspective view-projection matrix of cube face (0..5) that [PointShadowMap] renders with. Out-of-range faces clamp to [gpu.CubeFacePosX]. +func (u PointShadowUniform) FaceViewProj(face gpu.CubeFace) math3d.Mat4 { if face >= PointShadowFaceCount { face = gpu.CubeFacePosX } b := pointFaceBasis[face] - return math3d.LookAt(l.Position, l.Position.Add(b.forward), b.up) -} - -// FaceProjMatrix returns the 90-degree square [0, 1] depth perspective projection -// shared by all six cube faces of the point light. -func (l PointShadowLight) FaceProjMatrix() math3d.Mat4 { - return math3d.Perspective(math.Pi/2, 1.0, l.Near, l.Range) -} - -// FaceViewProj returns FaceProjMatrix().Mul(FaceViewMatrix(face)). -func (l PointShadowLight) FaceViewProj(face gpu.CubeFace) math3d.Mat4 { - return l.FaceProjMatrix().Mul(l.FaceViewMatrix(face)) -} - -// PointShadowUniform is the packed uniform data matching the WGSL PointShadow -// block declared by [PointShadowWGSL]. -type PointShadowUniform struct { - Position math3d.Vec3 - Range float32 - ColorIntensity math3d.Vec3 - Near float32 - DepthBias float32 - NormalBias float32 - InvFaceResolution float32 - FilterMode float32 - Ambient math3d.Vec3 -} - -// NewPointShadowUniform computes the uniform data for light and cfg. -func NewPointShadowUniform(light PointShadowLight, cfg PointShadowConfig) PointShadowUniform { - n := cfg.Normalized() - filterMode := float32(0) - if n.Filter == LocalShadowFilterPCF3x3 { - filterMode = 1 - } - return PointShadowUniform{ - Position: light.Position, - Range: light.Range, - ColorIntensity: light.Color.Scale(light.Intensity), - Near: light.Near, - DepthBias: n.DepthBias, - NormalBias: n.NormalBias, - InvFaceResolution: 1.0 / float32(n.FaceResolution), - FilterMode: filterMode, - Ambient: light.Ambient, - } + view := math3d.LookAt(u.Position, u.Position.Add(b.forward), b.up) + return math3d.Perspective(math.Pi/2, 1.0, u.Near, u.Far).Mul(view) } -// Encode writes u into dst in the little-endian layout declared by [PointShadowWGSL] -// and returns dst[:PointShadowUniformSize]. It allocates nothing and panics if -// len(dst) < PointShadowUniformSize. +// Encode writes u into dst in the little-endian layout declared by [PointShadowWGSL] and returns dst[:PointShadowUniformSize]. It allocates nothing and panics if len(dst) < PointShadowUniformSize. func (u *PointShadowUniform) Encode(dst []byte) []byte { if len(dst) < PointShadowUniformSize { panic("render3d: PointShadowUniform.Encode: dst shorter than PointShadowUniformSize") } dst = dst[:PointShadowUniformSize] - off := 0 - putF := func(v float32) { - binary.LittleEndian.PutUint32(dst[off:], math.Float32bits(v)) - off += 4 - } - putF(u.Position.X) - putF(u.Position.Y) - putF(u.Position.Z) - putF(u.Range) - putF(u.ColorIntensity.X) - putF(u.ColorIntensity.Y) - putF(u.ColorIntensity.Z) - putF(u.Near) - putF(u.DepthBias) - putF(u.NormalBias) - putF(u.InvFaceResolution) - putF(u.FilterMode) - putF(u.Ambient.X) - putF(u.Ambient.Y) - putF(u.Ambient.Z) - putF(0) + putVec4(dst[0:], math3d.Vec4{X: u.Position.X, Y: u.Position.Y, Z: u.Position.Z, W: u.Far}) + putVec4(dst[16:], math3d.Vec4{X: u.DepthBias, Y: u.NormalBias, Z: u.InvFaceResolution, W: u.FilterMode}) + putVec4(dst[32:], math3d.Vec4{X: u.Near}) return dst } -// PointShadowMap manages a 3x2 2D depth-atlas omnidirectional shadow map, its -// caster pipeline, and its sampling bind group for a point light on a [gpu.Device]. -type PointShadowMap struct { - cfg PointShadowConfig - atlasW uint32 - atlasH uint32 - rt *gpu.RenderTarget - sampler *gpu.Sampler - uniformBuf *gpu.Buffer - casterBuf *gpu.Buffer - layout *gpu.BindGroupLayout - bindGroup *gpu.BindGroup - casterLayout *gpu.BindGroupLayout - casterGroup *gpu.BindGroup - depthPipe *gpu.Pipeline - uniforms PointShadowUniform - faceViewProj [PointShadowFaceCount]math3d.Mat4 - activeFace gpu.CubeFace - casterSlot uint32 - uniformBytes [PointShadowUniformSize]byte - casterScratch [localShadowCasterDataSize]byte +// localShadowResources holds the GPU objects a spot or point shadow map owns. +type localShadowResources struct { + rt *gpu.RenderTarget + sampler *gpu.Sampler + uniformBuf *gpu.Buffer + casterBuf *gpu.Buffer + layout *gpu.BindGroupLayout + bindGroup *gpu.BindGroup + casterLayout *gpu.BindGroupLayout + casterGroup *gpu.BindGroup + depthPipe *gpu.Pipeline } -// NewPointShadowMap creates a 3x2 Depth32Float atlas point shadow map and its -// GPU resources scoped to cx. Invalid configuration returns an error wrapping -// [ErrInvalidLocalShadow]; device errors are returned as [gpu.Error]. -func NewPointShadowMap(cx *core.Scope, dev *gpu.Device, cfg PointShadowConfig) (*PointShadowMap, error) { - if err := cfg.Validate(); err != nil { - return nil, err +// newLocalShadowResources creates a width x height Depth32Float target, its comparison sampler and sampling bind group, a uniformSize uniform buffer, a casterSlots-slot dynamic-offset caster buffer and the depth-only caster pipeline. +func newLocalShadowResources(cx *core.Scope, dev *gpu.Device, label string, width, height uint32, uniformSize, casterSlots uint64, filter LocalShadowFilter, cull gpu.CullMode, retained bool) (localShadowResources, error) { + var r localShadowResources + casterBufSize := casterSlots * localShadowCasterSlotStride + if maxBuf := dev.Limits().MaxBufferSize; maxBuf > 0 && casterBufSize > maxBuf { + return r, fmt.Errorf("%w: %s caster buffer of %d bytes exceeds MaxBufferSize %d; lower MaxCasters", ErrInvalidLocalShadow, label, casterBufSize, maxBuf) } - if dev == nil { - return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} - } - n := cfg.Normalized() - atlasW, atlasH := n.AtlasSize() - maxDim := dev.Limits().MaxTextureDimension2D - if maxDim > 0 && (atlasW > maxDim || atlasH > maxDim) { - return nil, fmt.Errorf("%w: point shadow atlas %dx%d exceeds MaxTextureDimension2D %d", ErrInvalidLocalShadow, atlasW, atlasH, maxDim) - } - - label := n.Label - if label == "" { - label = "render3d.point_shadow" - } - - var closers []interface{ Close() error } - fail := func(err error) (*PointShadowMap, error) { - for i := len(closers) - 1; i >= 0; i-- { - if closers[i] != nil { - _ = closers[i].Close() - } - } - return nil, err + var err error + fail := func(e error) (localShadowResources, error) { + _ = r.close() + return localShadowResources{}, e } - - rt, err := dev.CreateRenderTarget(cx, gpu.RenderTargetDesc{ - Label: label + ".atlas", - Width: atlasW, - Height: atlasH, - DepthFormat: gpu.FormatDepth32Float, - Retained: n.Retained, - }) - if err != nil { + if r.rt, err = dev.CreateRenderTarget(cx, gpu.RenderTargetDesc{ + Label: label + ".depth", + Width: width, + Height: height, + DepthFormat: gpu.FormatDepth32Float, + Retained: retained, + }); err != nil { return fail(err) } - closers = append(closers, rt) - filterMode := gpu.FilterNearest - if n.Filter == LocalShadowFilterPCF3x3 { + if filter == LocalShadowFilterPCF3x3 { filterMode = gpu.FilterLinear } - samp, err := dev.CreateSampler(cx, gpu.SamplerDesc{ + if r.sampler, err = dev.CreateSampler(cx, gpu.SamplerDesc{ Label: label + ".sampler", MinFilter: filterMode, MagFilter: filterMode, @@ -1231,145 +695,385 @@ func NewPointShadowMap(cx *core.Scope, dev *gpu.Device, cfg PointShadowConfig) ( AddressV: gpu.AddressClampToEdge, AddressW: gpu.AddressClampToEdge, Compare: gpu.CompareLessEqual, - Retained: n.Retained, - }) - if err != nil { + Retained: retained, + }); err != nil { return fail(err) } - closers = append(closers, samp) - - uniformBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + if r.uniformBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ Label: label + ".uniform", - Size: PointShadowUniformSize, + Size: uniformSize, Usage: gpu.UsageUniform | gpu.UsageCopyDst, - Retained: n.Retained, - }) - if err != nil { + Retained: retained, + }); err != nil { return fail(err) } - closers = append(closers, uniformBuf) - - casterBufSize := uint64(n.MaxCasters) * localShadowCasterSlotStride - casterBuf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + if r.casterBuf, err = dev.CreateBuffer(cx, gpu.BufferDesc{ Label: label + ".casters", Size: casterBufSize, Usage: gpu.UsageUniform | gpu.UsageCopyDst, - Retained: n.Retained, - }) - if err != nil { + Retained: retained, + }); err != nil { return fail(err) } - closers = append(closers, casterBuf) - - layout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + if r.layout, err = dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ Label: label + ".layout", Entries: []gpu.BindGroupLayoutEntry{ {Binding: 0, Visibility: gpu.StageVertex | gpu.StageFragment, Type: gpu.BindingUniform}, {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingComparisonSampler}, }, - }) - if err != nil { + }); err != nil { return fail(err) } - closers = append(closers, layout) - - bindGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + if r.bindGroup, err = dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ Label: label + ".bind_group", - Layout: layout, + Layout: r.layout, Entries: []gpu.BindGroupEntry{ - {Binding: 0, Buffer: uniformBuf, Size: PointShadowUniformSize}, - {Binding: 1, Texture: rt.Depth}, - {Binding: 2, Sampler: samp}, + {Binding: 0, Buffer: r.uniformBuf, Size: uniformSize}, + {Binding: 1, Texture: r.rt.Depth}, + {Binding: 2, Sampler: r.sampler}, }, - }) - if err != nil { + }); err != nil { return fail(err) } - closers = append(closers, bindGroup) - - casterLayout, err := dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ + if r.casterLayout, err = dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{ Label: label + ".caster_layout", Entries: []gpu.BindGroupLayoutEntry{ {Binding: 0, Visibility: gpu.StageVertex, Type: gpu.BindingUniform, HasDynamicOffset: true}, }, - }) - if err != nil { + }); err != nil { return fail(err) } - closers = append(closers, casterLayout) - - casterGroup, err := dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ + if r.casterGroup, err = dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{ Label: label + ".caster_group", - Layout: casterLayout, + Layout: r.casterLayout, Entries: []gpu.BindGroupEntry{ - {Binding: 0, Buffer: casterBuf, Offset: 0, Size: localShadowCasterDataSize}, + {Binding: 0, Buffer: r.casterBuf, Offset: 0, Size: localShadowCasterDataSize}, }, - }) - if err != nil { + }); err != nil { return fail(err) } - closers = append(closers, casterGroup) - depthMod, err := gpu.CompileWGSL(localShadowDepthWGSL) if err != nil { return fail(err) } - depthPipe, err := dev.CreatePipeline(cx, gpu.PipelineDesc{ + if r.depthPipe, err = dev.CreatePipeline(cx, gpu.PipelineDesc{ Label: label + ".depth_pipe", Vertex: gpu.ShaderStage{Module: depthMod, EntryPoint: "vs_local_shadow_depth"}, - Layouts: []*gpu.BindGroupLayout{casterLayout}, + Layouts: []*gpu.BindGroupLayout{r.casterLayout}, VertexBuffers: []gpu.VertexBufferLayout{MeshVertexLayout()}, Primitive: gpu.PrimitiveState{ Topology: gpu.TopologyTriangleList, FrontFace: gpu.FrontCCW, - CullMode: n.CullMode, + CullMode: cull, }, DepthStencil: &gpu.DepthStencilState{ Format: gpu.FormatDepth32Float, DepthWrite: true, DepthCompare: gpu.CompareLess, }, - Retained: n.Retained, - }) - if err != nil { + Retained: retained, + }); err != nil { return fail(err) } + return r, nil +} - return &PointShadowMap{ - cfg: n, - atlasW: atlasW, - atlasH: atlasH, - rt: rt, - sampler: samp, - uniformBuf: uniformBuf, - casterBuf: casterBuf, - layout: layout, - bindGroup: bindGroup, - casterLayout: casterLayout, - casterGroup: casterGroup, - depthPipe: depthPipe, - }, nil +func (r *localShadowResources) valid() bool { + return r.rt != nil && r.rt.Valid() && + r.sampler != nil && r.sampler.Valid() && + r.uniformBuf != nil && r.uniformBuf.Valid() && + r.casterBuf != nil && r.casterBuf.Valid() && + r.layout != nil && r.layout.Valid() && + r.bindGroup != nil && r.bindGroup.Valid() && + r.casterLayout != nil && r.casterLayout.Valid() && + r.casterGroup != nil && r.casterGroup.Valid() && + r.depthPipe != nil && r.depthPipe.Valid() } -// Update validates light, computes all six cube-face view-projection matrices, -// and uploads the point shadow uniform buffer on dev without heap allocations. -func (p *PointShadowMap) Update(dev *gpu.Device, light PointShadowLight) error { - if p == nil || !p.Valid() { - return fmt.Errorf("%w: point shadow map is not valid", ErrInvalidLocalShadow) +func (r *localShadowResources) close() error { + var err error + closeOne := func(c interface{ Close() error }) { + err = errors.Join(err, c.Close()) } - if err := light.Validate(); err != nil { + if r.depthPipe != nil { + closeOne(r.depthPipe) + } + if r.casterGroup != nil { + closeOne(r.casterGroup) + } + if r.casterLayout != nil { + closeOne(r.casterLayout) + } + if r.bindGroup != nil { + closeOne(r.bindGroup) + } + if r.layout != nil { + closeOne(r.layout) + } + if r.casterBuf != nil { + closeOne(r.casterBuf) + } + if r.uniformBuf != nil { + closeOne(r.uniformBuf) + } + if r.sampler != nil { + closeOne(r.sampler) + } + if r.rt != nil { + closeOne(r.rt) + } + return err +} + +// drawCaster writes lightVP and model into caster slot and records mesh with that slot bound. +func (r *localShadowResources) drawCaster(dev *gpu.Device, pass *gpu.RenderPass, scratch []byte, slot uint32, lightVP, model math3d.Mat4, mesh *GPUMesh) { + offset := uint64(slot) * localShadowCasterSlotStride + encodeLocalShadowCaster(scratch, lightVP, model) + dev.WriteBuffer(r.casterBuf, offset, scratch) + pass.SetBindGroup(0, r.casterGroup, uint32(offset)) + mesh.Draw(pass) +} + +// SpotShadowMap manages a depth-only perspective 2D shadow map, its depth caster pipeline and its sampling bind group for the first spot light of a [LightRig]. +// +// Create it once when the GPU device is ready (Retained: true survives device loss), call [SpotShadowMap.Update] with the rig's spot light, record casters between [SpotShadowMap.BeginShadowPass] and pass.End(), and bind [SpotShadowMap.BindGroup] at [LocalShadowGroup] when drawing with [NewLitPBRSpotShadowPipeline]. Its resources belong to the [*core.Scope] passed to [NewSpotShadowMap]. +type SpotShadowMap struct { + cfg SpotShadowConfig + res localShadowResources + uniforms SpotShadowUniform + updated bool + passDev *gpu.Device + casterSlot uint32 + uniformBytes [SpotShadowUniformSize]byte + casterScratch [localShadowCasterDataSize]byte +} + +// NewSpotShadowMap creates a depth-only perspective spot shadow map and its GPU resources scoped to cx. Invalid configuration, a resolution above the device's MaxTextureDimension2D, or a caster buffer above its MaxBufferSize returns an error wrapping [ErrInvalidLocalShadow]; device errors are returned as [gpu.Error]. +func NewSpotShadowMap(cx *core.Scope, dev *gpu.Device, cfg SpotShadowConfig) (*SpotShadowMap, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + n := cfg.Normalized() + if maxDim := dev.Limits().MaxTextureDimension2D; maxDim > 0 && n.Resolution > maxDim { + return nil, fmt.Errorf("%w: spot resolution %d exceeds MaxTextureDimension2D %d", ErrInvalidLocalShadow, n.Resolution, maxDim) + } + if n.Label == "" { + n.Label = "render3d.spot_shadow" + } + res, err := newLocalShadowResources(cx, dev, n.Label, n.Resolution, n.Resolution, SpotShadowUniformSize, uint64(n.MaxCasters), n.Filter, n.CullMode, n.Retained) + if err != nil { + return nil, err + } + return &SpotShadowMap{cfg: n, res: res}, nil +} + +// Update computes the shadow projection for the [LightRig] spot light light (see [NewSpotShadowUniform]) and writes the uniform buffer on dev without heap allocations. +func (s *SpotShadowMap) Update(dev *gpu.Device, light SpotLight) error { + if s == nil || !s.Valid() { + return fmt.Errorf("%w: spot shadow map is not valid", ErrInvalidLocalShadow) + } + if dev == nil { + return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + u, err := NewSpotShadowUniform(light, s.cfg) + if err != nil { return err } + s.uniforms = u + s.updated = true + dev.WriteBuffer(s.res.uniformBuf, 0, s.uniforms.Encode(s.uniformBytes[:])) + return nil +} + +// Uniforms returns the last spot shadow uniform data written via [SpotShadowMap.Update]. +func (s *SpotShadowMap) Uniforms() SpotShadowUniform { + if s == nil { + return SpotShadowUniform{} + } + return s.uniforms +} + +// Config returns the normalized [SpotShadowConfig]. +func (s *SpotShadowMap) Config() SpotShadowConfig { + if s == nil { + return SpotShadowConfig{} + } + return s.cfg +} + +// MaxCasters returns the number of [SpotShadowMap.DrawCaster] calls one shadow pass accepts. +func (s *SpotShadowMap) MaxCasters() uint32 { + if s == nil { + return 0 + } + return s.cfg.MaxCasters +} + +// RenderTarget returns the underlying depth-only [gpu.RenderTarget]. +func (s *SpotShadowMap) RenderTarget() *gpu.RenderTarget { + if s == nil { + return nil + } + return s.res.rt +} + +// DepthTexture returns the underlying Depth32Float [gpu.Texture]. +func (s *SpotShadowMap) DepthTexture() *gpu.Texture { + if s == nil || s.res.rt == nil { + return nil + } + return s.res.rt.Depth +} + +// Sampler returns the comparison [gpu.Sampler] bound in [SpotShadowMap.BindGroup]. +func (s *SpotShadowMap) Sampler() *gpu.Sampler { + if s == nil { + return nil + } + return s.res.sampler +} + +// Layout returns the bind group layout for sampling this spot shadow map (binding 0: SpotShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison). +func (s *SpotShadowMap) Layout() *gpu.BindGroupLayout { + if s == nil { + return nil + } + return s.res.layout +} + +// BindGroup returns the bind group to set at [LocalShadowGroup], or at the group passed to [SpotShadowWGSLForGroup], during the lit render pass. +func (s *SpotShadowMap) BindGroup() *gpu.BindGroup { + if s == nil { + return nil + } + return s.res.bindGroup +} + +// ByteSize returns the GPU memory held by the depth texture and uniform buffers. +func (s *SpotShadowMap) ByteSize() uint64 { + if s == nil || s.res.uniformBuf == nil || s.res.casterBuf == nil { + return 0 + } + depthBytes := uint64(s.cfg.Resolution) * uint64(s.cfg.Resolution) * 4 + return depthBytes + s.res.uniformBuf.Size() + s.res.casterBuf.Size() +} + +// Valid reports whether all underlying GPU resources are open and live. +func (s *SpotShadowMap) Valid() bool { + return s != nil && s.res.valid() +} + +// BeginShadowPass resets the caster slot cursor, begins a depth-only render pass on target (a [*gpu.Encoder] or [*gpu.Frame]) clearing the spot shadow map to 1.0, sets the full viewport and scissor, and binds the depth pipeline. Record at most one shadow pass per submission. It returns nil when s, dev or target is nil or s is invalid, so check the result before drawing casters and calling End. +func (s *SpotShadowMap) BeginShadowPass(dev *gpu.Device, target ShadowPassTarget) *gpu.RenderPass { + if s == nil || dev == nil || target == nil || !s.Valid() { + return nil + } + pass := target.BeginRenderPass(gpu.RenderPassDesc{ + Label: s.cfg.Label + ".pass", + DepthStencil: &gpu.DepthStencilAttachment{ + Texture: s.res.rt.Depth, + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreStore, + ClearDepth: 1.0, + }, + }) + if pass == nil { + return nil + } + s.passDev = dev + s.casterSlot = 0 + r := s.cfg.Resolution + pass.SetViewport(0, 0, float32(r), float32(r), 0, 1) + pass.SetScissor(0, 0, int32(r), int32(r)) + pass.SetPipeline(s.res.depthPipe) + return pass +} + +// DrawCaster records a shadow caster draw for mesh transformed by model inside the pass started by [SpotShadowMap.BeginShadowPass]. Each call uses its own 256-byte dynamic-offset uniform slot, so casters drawn in one pass never overwrite each other's transforms. It returns false and draws nothing when an argument is invalid, [SpotShadowMap.Update] has not been called yet, or [SpotShadowMap.MaxCasters] casters were already drawn in this pass. +func (s *SpotShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) bool { + if s == nil || pass == nil || s.passDev == nil || !s.updated || !s.Valid() || !mesh.Valid() { + return false + } + if s.casterSlot >= s.cfg.MaxCasters { + return false + } + s.res.drawCaster(s.passDev, pass, s.casterScratch[:], s.casterSlot, s.uniforms.ViewProj, model, mesh) + s.casterSlot++ + return true +} + +// Close releases all GPU resources owned by s. It is safe to call on a nil receiver or more than once. +func (s *SpotShadowMap) Close() error { + if s == nil { + return nil + } + s.passDev = nil + return s.res.close() +} + +// PointShadowMap manages an omnidirectional shadow for the first point light of a [LightRig]: the six 90-degree cube faces packed into one 3x2 Depth32Float atlas, its caster pipeline and its sampling bind group. +// +// Call [PointShadowMap.Update] with the rig's point light, record casters for each face to refresh between [PointShadowMap.BeginFacePass] and pass.End(), and bind [PointShadowMap.BindGroup] at [LocalShadowGroup] when drawing with [NewLitPBRPointShadowPipeline]. +type PointShadowMap struct { + cfg PointShadowConfig + atlasW uint32 + atlasH uint32 + res localShadowResources + uniforms PointShadowUniform + updated bool + passDev *gpu.Device + faceViewProj [PointShadowFaceCount]math3d.Mat4 + activeFace gpu.CubeFace + faceSlot [PointShadowFaceCount]uint32 + uniformBytes [PointShadowUniformSize]byte + casterScratch [localShadowCasterDataSize]byte +} + +// NewPointShadowMap creates a 3x2 Depth32Float atlas point shadow map and its GPU resources scoped to cx. Invalid configuration, an atlas above the device's MaxTextureDimension2D, or a caster buffer above its MaxBufferSize returns an error wrapping [ErrInvalidLocalShadow]; device errors are returned as [gpu.Error]. +func NewPointShadowMap(cx *core.Scope, dev *gpu.Device, cfg PointShadowConfig) (*PointShadowMap, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + n := cfg.Normalized() + atlasW, atlasH := n.AtlasSize() + if maxDim := dev.Limits().MaxTextureDimension2D; maxDim > 0 && (atlasW > maxDim || atlasH > maxDim) { + return nil, fmt.Errorf("%w: point shadow atlas %dx%d exceeds MaxTextureDimension2D %d", ErrInvalidLocalShadow, atlasW, atlasH, maxDim) + } + if n.Label == "" { + n.Label = "render3d.point_shadow" + } + res, err := newLocalShadowResources(cx, dev, n.Label, atlasW, atlasH, PointShadowUniformSize, uint64(n.MaxCasters)*PointShadowFaceCount, n.Filter, n.CullMode, n.Retained) + if err != nil { + return nil, err + } + return &PointShadowMap{cfg: n, atlasW: atlasW, atlasH: atlasH, res: res}, nil +} + +// Update computes the six cube-face projections for the [LightRig] point light light (see [NewPointShadowUniform]) and writes the uniform buffer on dev without heap allocations. +func (p *PointShadowMap) Update(dev *gpu.Device, light PointLight) error { + if p == nil || !p.Valid() { + return fmt.Errorf("%w: point shadow map is not valid", ErrInvalidLocalShadow) + } if dev == nil { return gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} } - proj := light.FaceProjMatrix() + u, err := NewPointShadowUniform(light, p.cfg) + if err != nil { + return err + } + p.uniforms = u for face := range gpu.CubeFace(PointShadowFaceCount) { - p.faceViewProj[face] = proj.Mul(light.FaceViewMatrix(face)) + p.faceViewProj[face] = u.FaceViewProj(face) } - p.uniforms = NewPointShadowUniform(light, p.cfg) - dev.WriteBuffer(p.uniformBuf, 0, p.uniforms.Encode(p.uniformBytes[:])) + p.updated = true + dev.WriteBuffer(p.res.uniformBuf, 0, p.uniforms.Encode(p.uniformBytes[:])) return nil } @@ -1381,8 +1085,7 @@ func (p *PointShadowMap) Uniforms() PointShadowUniform { return p.uniforms } -// FaceViewProj returns the 90-degree perspective view-projection matrix for cube -// face (0..5). Returns identity for a nil receiver or out-of-range face. +// FaceViewProj returns the view-projection matrix of cube face (0..5) from the last [PointShadowMap.Update]. It returns identity for a nil receiver or an out-of-range face. func (p *PointShadowMap) FaceViewProj(face gpu.CubeFace) math3d.Mat4 { if p == nil || face >= PointShadowFaceCount { return math3d.Mat4Identity() @@ -1390,16 +1093,15 @@ func (p *PointShadowMap) FaceViewProj(face gpu.CubeFace) math3d.Mat4 { return p.faceViewProj[face] } -// FaceViewport returns the pixel rectangle (x, y, width, height) inside the 3x2 -// depth atlas assigned to cube face (0..5). +// FaceViewport returns the pixel rectangle (x, y, width, height) inside the 3x2 depth atlas assigned to cube face (0..5). func (p *PointShadowMap) FaceViewport(face gpu.CubeFace) (x, y, width, height uint32) { if p == nil || face >= PointShadowFaceCount { return 0, 0, 0, 0 } col := face % PointShadowAtlasCols row := face / PointShadowAtlasCols - res := p.cfg.FaceResolution - return col * res, row * res, res, res + r := p.cfg.FaceResolution + return col * r, row * r, r, r } // Config returns the normalized [PointShadowConfig]. @@ -1410,6 +1112,14 @@ func (p *PointShadowMap) Config() PointShadowConfig { return p.cfg } +// MaxCasters returns the number of [PointShadowMap.DrawCaster] calls one face pass accepts. +func (p *PointShadowMap) MaxCasters() uint32 { + if p == nil { + return 0 + } + return p.cfg.MaxCasters +} + // AtlasWidth returns the full width of the 3x2 depth atlas (3 * FaceResolution). func (p *PointShadowMap) AtlasWidth() uint32 { if p == nil { @@ -1431,15 +1141,15 @@ func (p *PointShadowMap) RenderTarget() *gpu.RenderTarget { if p == nil { return nil } - return p.rt + return p.res.rt } // DepthTexture returns the underlying Depth32Float 3x2 atlas [gpu.Texture]. func (p *PointShadowMap) DepthTexture() *gpu.Texture { - if p == nil || p.rt == nil { + if p == nil || p.res.rt == nil { return nil } - return p.rt.Depth + return p.res.rt.Depth } // Sampler returns the comparison [gpu.Sampler] bound in [PointShadowMap.BindGroup]. @@ -1447,203 +1157,97 @@ func (p *PointShadowMap) Sampler() *gpu.Sampler { if p == nil { return nil } - return p.sampler + return p.res.sampler } -// Layout returns the bind group layout for sampling this point shadow map -// (binding 0: PointShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison). +// Layout returns the bind group layout for sampling this point shadow map (binding 0: PointShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison). func (p *PointShadowMap) Layout() *gpu.BindGroupLayout { if p == nil { return nil } - return p.layout + return p.res.layout } -// BindGroup returns the bind group to set at [LocalShadowGroup] (or any group slot -// matching [PointShadowMap.Layout]) during the lit render pass. +// BindGroup returns the bind group to set at [LocalShadowGroup], or at the group passed to [PointShadowWGSLForGroup], during the lit render pass. func (p *PointShadowMap) BindGroup() *gpu.BindGroup { if p == nil { return nil } - return p.bindGroup + return p.res.bindGroup } // ByteSize returns the GPU memory held by the 3x2 depth atlas and uniform buffers. func (p *PointShadowMap) ByteSize() uint64 { - if p == nil { + if p == nil || p.res.uniformBuf == nil || p.res.casterBuf == nil { return 0 } depthBytes := uint64(p.atlasW) * uint64(p.atlasH) * 4 - return depthBytes + p.uniformBuf.Size() + p.casterBuf.Size() + return depthBytes + p.res.uniformBuf.Size() + p.res.casterBuf.Size() } // Valid reports whether all underlying GPU resources are open and live. func (p *PointShadowMap) Valid() bool { - return p != nil && - p.rt != nil && p.rt.Valid() && - p.sampler != nil && p.sampler.Valid() && - p.uniformBuf != nil && p.uniformBuf.Valid() && - p.casterBuf != nil && p.casterBuf.Valid() && - p.layout != nil && p.layout.Valid() && - p.bindGroup != nil && p.bindGroup.Valid() && - p.casterLayout != nil && p.casterLayout.Valid() && - p.casterGroup != nil && p.casterGroup.Valid() && - p.depthPipe != nil && p.depthPipe.Valid() -} - -// BeginFacePass begins a depth-only render pass targeting cube face (0..5) in the -// 3x2 depth atlas. Calling with face == 0 clears the entire atlas depth buffer to -// 1.0 and resets the caster dynamic-offset slot counter; faces 1..5 preserve -// previously rendered tiles using [gpu.LoadLoad]. Viewport and scissor are locked -// to the face's tile so geometry cannot bleed into neighboring faces. -func (p *PointShadowMap) BeginFacePass(rec LocalShadowPassRecorder, face gpu.CubeFace) *gpu.RenderPass { - if p == nil || rec == nil || !p.Valid() || face >= PointShadowFaceCount { + return p != nil && p.res.valid() +} + +// BeginFacePass begins a depth-only render pass on target (a [*gpu.Encoder] or [*gpu.Frame]) for cube face (0..5) of the 3x2 depth atlas, resets that face's caster slots, binds the depth pipeline, and locks viewport and scissor to the face's tile so geometry cannot bleed into neighboring faces. +// +// Face 0 clears the whole atlas to 1.0 and faces 1..5 keep what is already there ([gpu.LoadLoad]). Refreshing only some faces in a frame (for example skipping faces whose casters did not move) therefore works as long as face 0 is either refreshed together with every other face or not refreshed at all. Each face has its own [PointShadowMap.MaxCasters] slots, so faces may be recorded in any order; record each face at most once per submission. It returns nil when p, dev or target is nil, p is invalid, or face is out of range. +func (p *PointShadowMap) BeginFacePass(dev *gpu.Device, target ShadowPassTarget, face gpu.CubeFace) *gpu.RenderPass { + if p == nil || dev == nil || target == nil || !p.Valid() || face >= PointShadowFaceCount { return nil } loadOp := gpu.LoadLoad if face == 0 { loadOp = gpu.LoadClear - p.casterSlot = 0 } - p.activeFace = face - pass := rec.BeginRenderPass(gpu.RenderPassDesc{ + pass := target.BeginRenderPass(gpu.RenderPassDesc{ Label: fmt.Sprintf("%s.face%d", p.cfg.Label, face), DepthStencil: &gpu.DepthStencilAttachment{ - Texture: p.rt.Depth, + Texture: p.res.rt.Depth, DepthLoadOp: loadOp, DepthStoreOp: gpu.StoreStore, ClearDepth: 1.0, }, }) + if pass == nil { + return nil + } + p.passDev = dev + p.activeFace = face + p.faceSlot[face] = 0 vx, vy, vw, vh := p.FaceViewport(face) pass.SetViewport(float32(vx), float32(vy), float32(vw), float32(vh), 0, 1) pass.SetScissor(int32(vx), int32(vy), int32(vw), int32(vh)) - pass.SetPipeline(p.depthPipe) + pass.SetPipeline(p.res.depthPipe) return pass } -// DrawCaster records a shadow caster draw for mesh transformed by model into the -// currently active cube face pass started by [PointShadowMap.BeginFacePass]. -func (p *PointShadowMap) DrawCaster(dev *gpu.Device, pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) { - if p == nil || dev == nil || pass == nil || !p.Valid() || !mesh.Valid() { - return +// DrawCaster records a shadow caster draw for mesh transformed by model into the face pass most recently started by [PointShadowMap.BeginFacePass]. It returns false and draws nothing when an argument is invalid, [PointShadowMap.Update] has not been called yet, or [PointShadowMap.MaxCasters] casters were already drawn into this face. +func (p *PointShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) bool { + if p == nil || pass == nil || p.passDev == nil || !p.updated || !p.Valid() || !mesh.Valid() { + return false } - if p.casterSlot >= p.cfg.MaxCasters { - return + face := p.activeFace + if p.faceSlot[face] >= p.cfg.MaxCasters { + return false } - offset := uint64(p.casterSlot) * localShadowCasterSlotStride - p.casterSlot++ - encodeLocalShadowCaster(p.casterScratch[:], p.faceViewProj[p.activeFace], model) - dev.WriteBuffer(p.casterBuf, offset, p.casterScratch[:]) - pass.SetBindGroup(0, p.casterGroup, uint32(offset)) - mesh.Draw(pass) + slot := uint32(face)*p.cfg.MaxCasters + p.faceSlot[face] + p.res.drawCaster(p.passDev, pass, p.casterScratch[:], slot, p.faceViewProj[face], model, mesh) + p.faceSlot[face]++ + return true } -// Close releases all GPU resources owned by p. It is safe to call on a nil -// receiver or more than once. +// Close releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once. func (p *PointShadowMap) Close() error { if p == nil { return nil } - var err error - for _, c := range []interface{ Close() error }{ - p.depthPipe, - p.casterGroup, - p.casterLayout, - p.bindGroup, - p.layout, - p.casterBuf, - p.uniformBuf, - p.sampler, - p.rt, - } { - if c != nil { - err = errors.Join(err, c.Close()) - } - } - return err -} - -// LocalShadowLitPipelineOptions configures [NewSpotShadowLitPipeline] and -// [NewPointShadowLitPipeline]. -type LocalShadowLitPipelineOptions struct { - Label string - ColorFormat gpu.TextureFormat // defaults to dev.SurfaceFormat() - DepthFormat gpu.TextureFormat // optional; when non-zero enables depth testing with CompareLess - CullMode gpu.CullMode // default gpu.CullNone - Retained bool -} - -// NewSpotShadowLitPipeline compiles [SpotShadowWGSL] with [CameraWGSL] and -// builds a ready-to-use shadowed spot-lighting pipeline consuming -// [MeshVertexLayout] with cameraLayout at [CameraGroup] (0) and spotLayout at -// [LocalShadowGroup] (1). -func NewSpotShadowLitPipeline(cx *core.Scope, dev *gpu.Device, cameraLayout, spotLayout *gpu.BindGroupLayout, opts LocalShadowLitPipelineOptions) (*gpu.Pipeline, error) { - return newLocalShadowLitPipeline(cx, dev, cameraLayout, spotLayout, opts, spotShadowLitShaderWGSL, "vs_spot_lit", "fs_spot_lit", "render3d.spot_shadow_lit") -} - -// NewPointShadowLitPipeline compiles [PointShadowWGSL] with [CameraWGSL] and -// builds a ready-to-use shadowed omnidirectional point-lighting pipeline -// consuming [MeshVertexLayout] with cameraLayout at [CameraGroup] (0) and -// pointLayout at [LocalShadowGroup] (1). -func NewPointShadowLitPipeline(cx *core.Scope, dev *gpu.Device, cameraLayout, pointLayout *gpu.BindGroupLayout, opts LocalShadowLitPipelineOptions) (*gpu.Pipeline, error) { - return newLocalShadowLitPipeline(cx, dev, cameraLayout, pointLayout, opts, pointShadowLitShaderWGSL, "vs_point_lit", "fs_point_lit", "render3d.point_shadow_lit") -} - -func newLocalShadowLitPipeline( - cx *core.Scope, - dev *gpu.Device, - cameraLayout, shadowLayout *gpu.BindGroupLayout, - opts LocalShadowLitPipelineOptions, - wgslSrc, vsEntry, fsEntry, defaultLabel string, -) (*gpu.Pipeline, error) { - if dev == nil { - return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} - } - if cameraLayout == nil || !cameraLayout.Valid() || shadowLayout == nil || !shadowLayout.Valid() { - return nil, gpu.Error{Code: gpu.ErrInvalidDescriptor, Message: "render3d: invalid bind group layout"} - } - if !localShadowValidCull(opts.CullMode) { - return nil, fmt.Errorf("%w: invalid CullMode %d", ErrInvalidLocalShadow, opts.CullMode) - } - mod, err := gpu.CompileWGSL(wgslSrc) - if err != nil { - return nil, err - } - colorFmt := opts.ColorFormat - if colorFmt == gpu.FormatUndefined { - colorFmt = dev.SurfaceFormat() - } - label := opts.Label - if label == "" { - label = defaultLabel - } - desc := gpu.PipelineDesc{ - Label: label, - Vertex: gpu.ShaderStage{Module: mod, EntryPoint: vsEntry}, - Fragment: gpu.ShaderStage{Module: mod, EntryPoint: fsEntry}, - Layouts: []*gpu.BindGroupLayout{cameraLayout, shadowLayout}, - VertexBuffers: []gpu.VertexBufferLayout{MeshVertexLayout()}, - Primitive: gpu.PrimitiveState{ - Topology: gpu.TopologyTriangleList, - FrontFace: gpu.FrontCCW, - CullMode: opts.CullMode, - }, - Targets: []gpu.ColorTargetState{{Format: colorFmt, WriteMask: gpu.ColorWriteAll}}, - Retained: opts.Retained, - } - if opts.DepthFormat != gpu.FormatUndefined { - desc.DepthStencil = &gpu.DepthStencilState{ - Format: opts.DepthFormat, - DepthWrite: true, - DepthCompare: gpu.CompareLess, - } - } - return dev.CreatePipeline(cx, desc) + p.passDev = nil + return p.res.close() } -// DecodeDepth32Float decodes tightly packed little-endian float32 depth texels -// returned by [gpu.Device.ReadTexture] on a [gpu.FormatDepth32Float] texture. +// DecodeDepth32Float decodes tightly packed little-endian float32 depth texels returned by [gpu.Device.ReadTexture] on a [gpu.FormatDepth32Float] texture. func DecodeDepth32Float(raw []byte) []float32 { n := len(raw) / 4 out := make([]float32, n) @@ -1653,16 +1257,14 @@ func DecodeDepth32Float(raw []byte) []float32 { return out } -// EvaluateSpotShadow evaluates the CPU reference shadow visibility in [0, 1] -// matching sample_spot_shadow in [SpotShadowWGSL] against a row-major -// res x res Depth32Float buffer. +// EvaluateSpotShadow is the CPU reference of sample_spot_shadow in [SpotShadowWGSL]: the spot light's visibility in [0, 1] at worldPos against a row-major res x res Depth32Float buffer, such as [DecodeDepth32Float] of the [SpotShadowMap.DepthTexture] readback. func EvaluateSpotShadow(u SpotShadowUniform, depth []float32, res uint32, worldPos, worldNormal math3d.Vec3) float32 { if res == 0 || len(depth) < int(res)*int(res) { return 1 } - n := worldNormal - if n.LenSq() > 1e-12 { - n = n.Norm() + n := math3d.Vec3{} + if worldNormal.LenSq() > 1e-12 { + n = worldNormal.Norm() } biased := worldPos.Add(n.Scale(u.NormalBias)) clip := u.ViewProj.MulVec4(biased.Vec4(1)) @@ -1699,43 +1301,7 @@ func EvaluateSpotShadow(u SpotShadowUniform, depth []float32, res uint32, worldP return sum / 9.0 } -// EvaluateSpotLighting evaluates the CPU reference shadowed spot lighting color -// matching evaluate_spot_lighting in [SpotShadowWGSL]. -func EvaluateSpotLighting(u SpotShadowUniform, depth []float32, res uint32, worldPos, worldNormal, albedo math3d.Vec3) math3d.Vec3 { - n := worldNormal.Norm() - toLight := u.Position.Sub(worldPos) - dist := toLight.Len() - ambient := math3d.Vec3{X: albedo.X * u.Ambient.X, Y: albedo.Y * u.Ambient.Y, Z: albedo.Z * u.Ambient.Z} - if dist <= 1e-4 || dist >= u.Range { - return ambient - } - lDir := toLight.Scale(1 / dist) - ndl := max(n.Dot(lDir), float32(0)) - if ndl <= 0 { - return ambient - } - cosTheta := lDir.Neg().Dot(u.Direction) - coneT := localShadowClamp((cosTheta-u.CosOuter)/max(u.CosInner-u.CosOuter, float32(1e-4)), 0, 1) - cone := coneT * coneT * (3 - 2*coneT) - if cone <= 0 { - return ambient - } - ratio := dist / u.Range - r2 := ratio * ratio - win := localShadowClamp(1-r2*r2, 0, 1) - atten := (win * win) / max(dist*dist, float32(0.01)) - vis := EvaluateSpotShadow(u, depth, res, worldPos, n) - k := ndl * cone * atten * vis - return math3d.Vec3{ - X: ambient.X + albedo.X*u.ColorIntensity.X*k, - Y: ambient.Y + albedo.Y*u.ColorIntensity.Y*k, - Z: ambient.Z + albedo.Z*u.ColorIntensity.Z*k, - } -} - -// PointShadowSelectFace projects light-to-fragment vector v onto the dominant -// cube face (0..5) and returns the face index, face-local UV in [0, 1]^2, and -// positive major-axis distance matching [PointShadowWGSL]. +// PointShadowSelectFace projects light-to-fragment vector v onto the dominant cube face (0..5) and returns the face index, face-local UV in [0, 1]^2, and positive major-axis distance matching [PointShadowWGSL]. func PointShadowSelectFace(v math3d.Vec3) (face gpu.CubeFace, localU, localV, axisDist float32) { ax, ay, az := localShadowAbs(v.X), localShadowAbs(v.Y), localShadowAbs(v.Z) var xView, yView float32 @@ -1773,26 +1339,24 @@ func PointShadowSelectFace(v math3d.Vec3) (face gpu.CubeFace, localU, localV, ax return face, localU, localV, axisDist } -// EvaluatePointShadow evaluates the CPU reference omnidirectional shadow -// visibility in [0, 1] matching sample_point_shadow in [PointShadowWGSL] against -// a row-major (3*faceRes) x (2*faceRes) Depth32Float atlas buffer. +// EvaluatePointShadow is the CPU reference of sample_point_shadow in [PointShadowWGSL]: the point light's visibility in [0, 1] at worldPos against a row-major (3*faceRes) x (2*faceRes) Depth32Float atlas buffer, such as [DecodeDepth32Float] of the [PointShadowMap.DepthTexture] readback. func EvaluatePointShadow(u PointShadowUniform, atlasDepth []float32, faceRes uint32, worldPos, worldNormal math3d.Vec3) float32 { atlasW := int(faceRes * PointShadowAtlasCols) atlasH := int(faceRes * PointShadowAtlasRows) if faceRes == 0 || len(atlasDepth) < atlasW*atlasH { return 1 } - n := worldNormal - if n.LenSq() > 1e-12 { - n = n.Norm() + n := math3d.Vec3{} + if worldNormal.LenSq() > 1e-12 { + n = worldNormal.Norm() } biased := worldPos.Add(n.Scale(u.NormalBias)) v := biased.Sub(u.Position) face, localU, localV, axisDist := PointShadowSelectFace(v) - if axisDist <= u.Near || axisDist >= u.Range { + if axisDist <= u.Near || axisDist >= u.Far { return 1 } - ndcZ := (u.Range / (u.Range - u.Near)) * (1.0 - u.Near/axisDist) + ndcZ := (u.Far / (u.Far - u.Near)) * (1.0 - u.Near/axisDist) refDepth := localShadowClamp(ndcZ-u.DepthBias, 0, 1) invRes := u.InvFaceResolution if invRes <= 0 { @@ -1822,34 +1386,6 @@ func EvaluatePointShadow(u PointShadowUniform, atlasDepth []float32, faceRes uin return sum / 9.0 } -// EvaluatePointLighting evaluates the CPU reference shadowed point lighting color -// matching evaluate_point_lighting in [PointShadowWGSL]. -func EvaluatePointLighting(u PointShadowUniform, atlasDepth []float32, faceRes uint32, worldPos, worldNormal, albedo math3d.Vec3) math3d.Vec3 { - n := worldNormal.Norm() - toLight := u.Position.Sub(worldPos) - dist := toLight.Len() - ambient := math3d.Vec3{X: albedo.X * u.Ambient.X, Y: albedo.Y * u.Ambient.Y, Z: albedo.Z * u.Ambient.Z} - if dist <= 1e-4 || dist >= u.Range { - return ambient - } - lDir := toLight.Scale(1 / dist) - ndl := max(n.Dot(lDir), float32(0)) - if ndl <= 0 { - return ambient - } - ratio := dist / u.Range - r2 := ratio * ratio - win := localShadowClamp(1-r2*r2, 0, 1) - atten := (win * win) / max(dist*dist, float32(0.01)) - vis := EvaluatePointShadow(u, atlasDepth, faceRes, worldPos, n) - k := ndl * atten * vis - return math3d.Vec3{ - X: ambient.X + albedo.X*u.ColorIntensity.X*k, - Y: ambient.Y + albedo.Y*u.ColorIntensity.Y*k, - Z: ambient.Z + albedo.Z*u.ColorIntensity.Z*k, - } -} - func localShadowCompareDepth2D(depth []float32, w, h int, u, v, refDepth float32, linear bool) float32 { u = localShadowClamp(u, 0, 1) v = localShadowClamp(v, 0, 1) diff --git a/packages/game/render3d/local_shadows_test.go b/packages/game/render3d/local_shadows_test.go index decc3457..801a6639 100644 --- a/packages/game/render3d/local_shadows_test.go +++ b/packages/game/render3d/local_shadows_test.go @@ -22,15 +22,9 @@ const ( localShadowTestHeight = 96 ) -var ( - localShadowTestClear = core.RGB(0x0c1018) - localShadowTestAlbedo = math3d.Vec3{X: 0.85, Y: 0.85, Z: 0.85} -) +var localShadowTestClear = core.RGB(0x0c1018) -// localShadowTestSubdividedQuad builds a grid of subdivisions x subdivisions -// triangles spanning center +/- uAxis*halfU +/- vAxis*halfV with outward normal. -// Subdividing large floors and walls ensures triangles never straddle w <= 0 of -// a point light's cube-face frustum in the software rasterizer. +// localShadowTestSubdividedQuad builds a grid of subdivisions x subdivisions triangles spanning center +/- uAxis*halfU +/- vAxis*halfV with outward normal. Subdividing large floors and walls ensures triangles never straddle w <= 0 of a point light's cube-face frustum in the software rasterizer. func localShadowTestSubdividedQuad(center, uAxis, vAxis, normal math3d.Vec3, halfU, halfV float32, subdiv int) render3d.Mesh { var m render3d.Mesh n := normal.Norm() @@ -59,8 +53,7 @@ func localShadowTestSubdividedQuad(center, uAxis, vAxis, normal math3d.Vec3, hal return m } -// localShadowTestBoxMesh builds a CCW outward-facing box mesh centered at center -// with half extents half. +// localShadowTestBoxMesh builds a CCW outward-facing box mesh centered at center with half extents half. func localShadowTestBoxMesh(center, half math3d.Vec3) render3d.Mesh { type face struct{ n, u, v math3d.Vec3 } faces := [...]face{ @@ -206,234 +199,305 @@ func localShadowTestRGBDiff(a, b [3]uint8) int { return maxD } -func TestSpotShadowConfigAndLightValidation(t *testing.T) { - def := render3d.DefaultSpotShadowConfig() - if err := def.Validate(); err != nil { +var ( + localShadowFloorMat = render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.85, Y: 0.85, Z: 0.85}, Roughness: 0.9} + localShadowPillarMat = render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.88, Y: 0.42, Z: 0.30}, Roughness: 0.6} + localShadowAmbient = render3d.AmbientLight{Color: math3d.Vec3{X: 0.08, Y: 0.09, Z: 0.12}, Intensity: 1} + + localShadowTestSpot = render3d.SpotLight{ + Position: math3d.Vec3{X: -2.4, Y: 3.6, Z: 2.3}, + Direction: math3d.Vec3{X: 2.5, Y: -3.5, Z: -2.5}, + Color: math3d.Vec3{X: 1.0, Y: 0.92, Z: 0.78}, + Intensity: 45, + Range: 14, + InnerConeAngle: math3d.DegToRad(26), + OuterConeAngle: math3d.DegToRad(44), + } + localShadowTestPoint = render3d.PointLight{ + Position: math3d.Vec3{X: 0.0, Y: 1.8, Z: 0.0}, + Color: math3d.Vec3{X: 1.0, Y: 0.94, Z: 0.85}, + Intensity: 25, + Range: 12, + } +) + +// localShadowExpected returns the sRGB 8-bit color the lit PBR local shadow pipelines draw at wp for material mat under rig with visibility vis, from the CPU references ShadePointVisibility and LinearToSRGB. +func localShadowExpected(cam *scene3d.Camera, wp, n math3d.Vec3, mat render3d.PBRMaterial, rig render3d.LightRig, vis render3d.LightVisibility) [3]uint8 { + e := cam.Eye() + eye := math3d.Vec3{X: e.X, Y: e.Y, Z: e.Z} + return localShadowTestColorToRGB8(render3d.LinearToSRGB(render3d.ShadePointVisibility(wp, n, eye.Sub(wp), mat, rig, vis))) +} + +// localShadowDraw is one receiver drawn in the lit pass: a mesh with its own per-draw model matrix and material. +type localShadowDraw struct { + mesh *render3d.GPUMesh + buf *render3d.PBRDrawBuffer +} + +func localShadowDrawBuffers(t *testing.T, cx *core.Scope, dev *gpu.Device, retained bool, meshes []*render3d.GPUMesh, uniforms []render3d.PBRDrawUniform) []localShadowDraw { + t.Helper() + var layout *gpu.BindGroupLayout + draws := make([]localShadowDraw, len(meshes)) + for i, u := range uniforms { + db, err := render3d.NewPBRDrawBuffer(cx, dev, layout, u, retained) + if err != nil { + t.Fatalf("NewPBRDrawBuffer[%d]: %v", i, err) + } + if layout == nil { + layout = db.Layout() + } + draws[i] = localShadowDraw{mesh: meshes[i], buf: db} + } + if cx == nil { + t.Cleanup(func() { + for _, d := range draws { + _ = d.buf.Close() + } + }) + } + return draws +} + +func localShadowUpload(t *testing.T, cx *core.Scope, dev *gpu.Device, label string, m render3d.Mesh, retained bool) *render3d.GPUMesh { + t.Helper() + gm, err := render3d.UploadMesh(cx, dev, m, render3d.MeshUpload{Label: label, Retained: retained}) + if err != nil { + t.Fatalf("UploadMesh %s: %v", label, err) + } + if cx == nil { + t.Cleanup(func() { _ = gm.Close() }) + } + return gm +} + +func localShadowMainPass(target render3d.ShadowPassTarget) *gpu.RenderPass { + return target.BeginRenderPass(gpu.RenderPassDesc{ + Label: "local-shadow-main", + ColorAttachments: []gpu.ColorAttachment{{ + LoadOp: gpu.LoadClear, + StoreOp: gpu.StoreStore, + ClearColor: localShadowTestClear, + }}, + DepthStencil: &gpu.DepthStencilAttachment{ + DepthLoadOp: gpu.LoadClear, + DepthStoreOp: gpu.StoreDiscard, + ClearDepth: 1.0, + }, + }) +} + +func localShadowDrawReceivers(pass *gpu.RenderPass, pipe *gpu.Pipeline, camBuf *render3d.CameraBuffer, lightBuf *render3d.GPULightBuffer, shadow *gpu.BindGroup, draws []localShadowDraw) { + pass.SetPipeline(pipe) + pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + pass.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) + pass.SetBindGroup(render3d.LocalShadowGroup, shadow) + for _, d := range draws { + pass.SetBindGroup(render3d.PBRDrawGroup, d.buf.BindGroup()) + d.mesh.Draw(pass) + } +} + +func TestLocalShadowConfigValidation(t *testing.T) { + spotDef := render3d.DefaultSpotShadowConfig() + if err := spotDef.Validate(); err != nil { t.Fatalf("DefaultSpotShadowConfig.Validate: %v", err) } - if def.Resolution != 1024 || def.Filter != render3d.LocalShadowFilterPCF3x3 { - t.Fatalf("unexpected default spot config: %+v", def) + if spotDef.Resolution != 1024 || spotDef.Filter != render3d.LocalShadowFilterPCF3x3 || spotDef.Near != render3d.DefaultLocalShadowNear || spotDef.Far != render3d.DefaultLocalShadowFar { + t.Fatalf("unexpected default spot config: %+v", spotDef) } if render3d.LocalShadowFilterHard.String() != "hard" || render3d.LocalShadowFilterPCF3x3.String() != "pcf3x3" { - t.Fatalf("unexpected filter string names") + t.Fatal("unexpected filter string names") + } + if render3d.LocalShadowGroup != render3d.ShadowGroup { + t.Fatalf("LocalShadowGroup = %d, want ShadowGroup %d", render3d.LocalShadowGroup, render3d.ShadowGroup) } - badConfigs := []render3d.SpotShadowConfig{ + badSpot := []render3d.SpotShadowConfig{ {DepthBias: -0.01}, {DepthBias: float32(math.NaN())}, {NormalBias: -0.1}, {NormalBias: float32(math.Inf(1))}, {Filter: render3d.LocalShadowFilter(99)}, {CullMode: gpu.CullMode(99)}, + {Near: -1}, + {Near: 5, Far: 4}, + {Far: float32(math.Inf(1))}, + {MaxCasters: render3d.MaxLocalShadowCasters + 1}, } - for i, cfg := range badConfigs { + for i, cfg := range badSpot { if err := cfg.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { - t.Errorf("badConfigs[%d] = %v, want ErrInvalidLocalShadow", i, err) - } - } - - if _, err := render3d.NewSpotShadowMap(nil, nil, def); !errors.Is(err, gpu.ErrDeviceLost) { - t.Fatalf("nil device error = %v, want gpu.ErrDeviceLost", err) - } - - sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) - t.Cleanup(sr.Close) - dev := sr.Device() - if _, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{ - Resolution: dev.Limits().MaxTextureDimension2D + 1, - }); !errors.Is(err, render3d.ErrInvalidLocalShadow) { - t.Fatalf("oversized spot resolution error = %v, want ErrInvalidLocalShadow", err) - } - - validLight := render3d.SpotShadowLight{ - Position: math3d.Vec3{Y: 4}, - Direction: math3d.Vec3{Y: -1}, - Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, - Intensity: 10, - Near: 0.1, - Range: 12, - InnerConeAngle: math3d.DegToRad(20), - OuterConeAngle: math3d.DegToRad(35), - } - if err := validLight.Validate(); err != nil { - t.Fatalf("valid spot light failed: %v", err) - } - - badLights := []render3d.SpotShadowLight{ - {Position: math3d.Vec3{X: float32(math.NaN())}, Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, - {Direction: math3d.Vec3Zero(), Near: 0.1, Range: 10, OuterConeAngle: 0.5}, - {Direction: math3d.Vec3{Y: -1}, Color: math3d.Vec3{X: -1}, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, - {Direction: math3d.Vec3{Y: -1}, Ambient: math3d.Vec3{Y: -0.1}, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, - {Direction: math3d.Vec3{Y: -1}, Intensity: -1, Near: 0.1, Range: 10, OuterConeAngle: 0.5}, - {Direction: math3d.Vec3{Y: -1}, Near: 0, Range: 10, OuterConeAngle: 0.5}, - {Direction: math3d.Vec3{Y: -1}, Near: 5, Range: 5, OuterConeAngle: 0.5}, - {Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, OuterConeAngle: 0}, - {Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, OuterConeAngle: math.Pi / 2}, - {Direction: math3d.Vec3{Y: -1}, Near: 0.1, Range: 10, InnerConeAngle: 0.6, OuterConeAngle: 0.5}, - } - for i, l := range badLights { - if err := l.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { - t.Errorf("badLights[%d] = %v, want ErrInvalidLocalShadow", i, err) + t.Errorf("badSpot[%d] = %v, want ErrInvalidLocalShadow", i, err) } } -} -func TestPointShadowConfigAndLightValidation(t *testing.T) { - def := render3d.DefaultPointShadowConfig() - if err := def.Validate(); err != nil { + pointDef := render3d.DefaultPointShadowConfig() + if err := pointDef.Validate(); err != nil { t.Fatalf("DefaultPointShadowConfig.Validate: %v", err) } - aw, ah := def.AtlasSize() - if aw != 3*512 || ah != 2*512 { + if aw, ah := pointDef.AtlasSize(); aw != 3*512 || ah != 2*512 { t.Fatalf("default atlas size = %dx%d, want %dx%d", aw, ah, 3*512, 2*512) } - - badConfigs := []render3d.PointShadowConfig{ + badPoint := []render3d.PointShadowConfig{ {DepthBias: -0.01}, {NormalBias: float32(math.NaN())}, {Filter: render3d.LocalShadowFilter(42)}, {CullMode: gpu.CullMode(42)}, + {Near: 2, Far: 1}, + {MaxCasters: render3d.MaxLocalShadowCasters + 1}, } - for i, cfg := range badConfigs { + for i, cfg := range badPoint { if err := cfg.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { - t.Errorf("badConfigs[%d] = %v, want ErrInvalidLocalShadow", i, err) + t.Errorf("badPoint[%d] = %v, want ErrInvalidLocalShadow", i, err) } } - if _, err := render3d.NewPointShadowMap(nil, nil, def); !errors.Is(err, gpu.ErrDeviceLost) { - t.Fatalf("nil device error = %v, want gpu.ErrDeviceLost", err) + if _, err := render3d.NewSpotShadowMap(nil, nil, spotDef); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("spot nil device error = %v, want gpu.ErrDeviceLost", err) + } + if _, err := render3d.NewPointShadowMap(nil, nil, pointDef); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("point nil device error = %v, want gpu.ErrDeviceLost", err) } - sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) t.Cleanup(sr.Close) dev := sr.Device() - if _, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{ - FaceResolution: dev.Limits().MaxTextureDimension2D/3 + 1, - }); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + if _, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{Resolution: dev.Limits().MaxTextureDimension2D + 1}); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("oversized spot resolution error = %v, want ErrInvalidLocalShadow", err) + } + if _, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{FaceResolution: dev.Limits().MaxTextureDimension2D/3 + 1}); !errors.Is(err, render3d.ErrInvalidLocalShadow) { t.Fatalf("oversized point atlas error = %v, want ErrInvalidLocalShadow", err) } + if _, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{Resolution: 16, MaxCasters: render3d.MaxLocalShadowCasters + 1}); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("spot MaxCasters above cap error = %v, want ErrInvalidLocalShadow", err) + } +} + +func TestLocalShadowUniformsFromLightRigLights(t *testing.T) { + cfg := render3d.SpotShadowConfig{Resolution: 256, Near: 0.2, Far: 30, DepthBias: 0.002, NormalBias: 0.03, Filter: render3d.LocalShadowFilterPCF3x3} - badLights := []render3d.PointShadowLight{ - {Position: math3d.Vec3{Z: float32(math.Inf(-1))}, Near: 0.1, Range: 10}, - {Color: math3d.Vec3{Z: -1}, Near: 0.1, Range: 10}, - {Ambient: math3d.Vec3{X: -0.2}, Near: 0.1, Range: 10}, - {Intensity: -2, Near: 0.1, Range: 10}, - {Near: 0, Range: 10}, - {Near: 4, Range: 2}, + // A spot light with a Range projects to that range; one with Range 0 (unbounded) projects to cfg.Far. + u, err := render3d.NewSpotShadowUniform(localShadowTestSpot, cfg) + if err != nil { + t.Fatalf("NewSpotShadowUniform: %v", err) } - for i, l := range badLights { - if err := l.Validate(); !errors.Is(err, render3d.ErrInvalidLocalShadow) { - t.Errorf("badPointLights[%d] = %v, want ErrInvalidLocalShadow", i, err) - } + if want := render3d.SpotShadowViewProj(localShadowTestSpot, 0.2, localShadowTestSpot.Range); u.ViewProj != want { + t.Fatalf("ViewProj with Range = %v, want %v", u.ViewProj, want) + } + unbounded := localShadowTestSpot + unbounded.Range = 0 + u0, err := render3d.NewSpotShadowUniform(unbounded, cfg) + if err != nil { + t.Fatalf("NewSpotShadowUniform(Range 0): %v", err) + } + if want := render3d.SpotShadowViewProj(unbounded, 0.2, 30); u0.ViewProj != want { + t.Fatalf("ViewProj with Range 0 = %v, want far plane %v", u0.ViewProj, cfg.Far) + } + // The cone apex maps to the shadow map center and the cone edge to its border. + dir := localShadowTestSpot.Direction.Norm() + center := u.ViewProj.MulVec4(localShadowTestSpot.Position.Add(dir.Scale(5)).Vec4(1)) + if math.Abs(float64(center.X/center.W)) > 1e-4 || math.Abs(float64(center.Y/center.W)) > 1e-4 { + t.Fatalf("cone axis projects to (%v, %v), want (0, 0)", center.X/center.W, center.Y/center.W) + } + + wide := localShadowTestSpot + wide.OuterConeAngle = math.Pi / 2 // valid for a LightRig, too wide for one perspective map + if _, err := render3d.NewSpotShadowUniform(wide, cfg); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("wide cone error = %v, want ErrInvalidLocalShadow", err) + } + short := localShadowTestSpot + short.Range = 0.1 + if _, err := render3d.NewSpotShadowUniform(short, cfg); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("Range below Near error = %v, want ErrInvalidLocalShadow", err) + } + broken := localShadowTestSpot + broken.Direction = math3d.Vec3{} + if _, err := render3d.NewSpotShadowUniform(broken, cfg); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("zero direction error = %v, want ErrInvalidLight", err) + } + + pcfg := render3d.PointShadowConfig{FaceResolution: 128, Near: 0.15, Far: 40, DepthBias: 0.001, NormalBias: 0.02} + pu, err := render3d.NewPointShadowUniform(localShadowTestPoint, pcfg) + if err != nil { + t.Fatalf("NewPointShadowUniform: %v", err) + } + if pu.Far != localShadowTestPoint.Range || pu.Near != 0.15 || pu.Position != localShadowTestPoint.Position { + t.Fatalf("point uniform = %+v, want Far = Range", pu) + } + pl := localShadowTestPoint + pl.Range = 0 + if pu0, err := render3d.NewPointShadowUniform(pl, pcfg); err != nil || pu0.Far != 40 { + t.Fatalf("NewPointShadowUniform(Range 0) = %+v, %v; want Far 40", pu0, err) + } + pl.Range = 0.1 + if _, err := render3d.NewPointShadowUniform(pl, pcfg); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("point Range below Near error = %v, want ErrInvalidLocalShadow", err) + } + pl.Intensity = -1 + if _, err := render3d.NewPointShadowUniform(pl, pcfg); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("invalid point light error = %v, want ErrInvalidLight", err) } } -func TestSpotShadowUniformEncodeZeroAlloc(t *testing.T) { - light := render3d.SpotShadowLight{ - Position: math3d.Vec3{X: -2, Y: 4, Z: 3}, - Direction: math3d.Vec3{X: 1, Y: -2, Z: -1}, - Color: math3d.Vec3{X: 1, Y: 0.9, Z: 0.7}, - Intensity: 12, - Near: 0.2, - Range: 15, - InnerConeAngle: math3d.DegToRad(20), - OuterConeAngle: math3d.DegToRad(40), - Ambient: math3d.Vec3{X: 0.05, Y: 0.06, Z: 0.08}, - } - cfg := render3d.SpotShadowConfig{ - Resolution: 256, - DepthBias: 0.002, - NormalBias: 0.03, - Filter: render3d.LocalShadowFilterPCF3x3, +func TestLocalShadowUniformEncodeZeroAlloc(t *testing.T) { + u, err := render3d.NewSpotShadowUniform(localShadowTestSpot, render3d.SpotShadowConfig{Resolution: 256, DepthBias: 0.002, NormalBias: 0.03, Filter: render3d.LocalShadowFilterPCF3x3}) + if err != nil { + t.Fatal(err) } - u := render3d.NewSpotShadowUniform(light, cfg) var buf [render3d.SpotShadowUniformSize + 8]byte out := u.Encode(buf[:]) - if len(out) != render3d.SpotShadowUniformSize || render3d.SpotShadowUniformSize != 144 { - t.Fatalf("encoded %d bytes, want 144", len(out)) + if len(out) != render3d.SpotShadowUniformSize || render3d.SpotShadowUniformSize != 80 { + t.Fatalf("spot encoded %d bytes, want 80", len(out)) } - f := func(i int) float32 { return math.Float32frombits(binary.LittleEndian.Uint32(out[4*i:])) } + f := func(b []byte, i int) float32 { return math.Float32frombits(binary.LittleEndian.Uint32(b[4*i:])) } for i := range 16 { - if f(i) != u.ViewProj[i] { - t.Fatalf("ViewProj[%d] = %v, want %v", i, f(i), u.ViewProj[i]) + if f(out, i) != u.ViewProj[i] { + t.Fatalf("ViewProj[%d] = %v, want %v", i, f(out, i), u.ViewProj[i]) } } - if f(16) != -2 || f(17) != 4 || f(18) != 3 || f(19) != 15 { - t.Fatalf("position_range mismatch: %v %v %v %v", f(16), f(17), f(18), f(19)) - } - if f(28) != 0.002 || f(29) != 0.03 || f(30) != 1.0/256.0 || f(31) != 1 { - t.Fatalf("params mismatch: %v %v %v %v", f(28), f(29), f(30), f(31)) - } - if f(32) != 0.05 || f(33) != 0.06 || f(34) != 0.08 || f(35) != 0.2 { - t.Fatalf("ambient_near mismatch: %v %v %v %v", f(32), f(33), f(34), f(35)) + if f(out, 16) != 0.002 || f(out, 17) != 0.03 || f(out, 18) != 1.0/256.0 || f(out, 19) != 1 { + t.Fatalf("spot params = %v %v %v %v", f(out, 16), f(out, 17), f(out, 18), f(out, 19)) } - if allocs := testing.AllocsPerRun(100, func() { u.Encode(buf[:]) }); allocs != 0 { t.Fatalf("SpotShadowUniform.Encode allocated %v times", allocs) } - func() { - defer func() { - if recover() == nil { - t.Fatal("Encode with short slice did not panic") - } - }() - u.Encode(make([]byte, render3d.SpotShadowUniformSize-1)) - }() -} -func TestPointShadowUniformEncodeZeroAlloc(t *testing.T) { - light := render3d.PointShadowLight{ - Position: math3d.Vec3{X: 1, Y: 2, Z: -3}, - Color: math3d.Vec3{X: 1, Y: 0.8, Z: 0.6}, - Intensity: 10, - Near: 0.15, - Range: 14, - Ambient: math3d.Vec3{X: 0.04, Y: 0.05, Z: 0.06}, - } - cfg := render3d.PointShadowConfig{ - FaceResolution: 128, - DepthBias: 0.001, - NormalBias: 0.02, - Filter: render3d.LocalShadowFilterHard, - } - u := render3d.NewPointShadowUniform(light, cfg) - var buf [render3d.PointShadowUniformSize + 8]byte - out := u.Encode(buf[:]) - if len(out) != render3d.PointShadowUniformSize || render3d.PointShadowUniformSize != 64 { - t.Fatalf("encoded %d bytes, want 64", len(out)) - } - f := func(i int) float32 { return math.Float32frombits(binary.LittleEndian.Uint32(out[4*i:])) } - if f(0) != 1 || f(1) != 2 || f(2) != -3 || f(3) != 14 { - t.Fatalf("position_range mismatch: %v %v %v %v", f(0), f(1), f(2), f(3)) - } - if f(4) != 10 || f(5) != 8 || f(6) != 6 || f(7) != 0.15 { - t.Fatalf("color_near mismatch: %v %v %v %v", f(4), f(5), f(6), f(7)) + pu, err := render3d.NewPointShadowUniform(render3d.PointLight{Position: math3d.Vec3{X: 1, Y: 2, Z: -3}, Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, Intensity: 3, Range: 14}, render3d.PointShadowConfig{FaceResolution: 128, Near: 0.15, DepthBias: 0.001, NormalBias: 0.02, Filter: render3d.LocalShadowFilterHard}) + if err != nil { + t.Fatal(err) } - if f(8) != 0.001 || f(9) != 0.02 || f(10) != 1.0/128.0 || f(11) != 0 { - t.Fatalf("params mismatch: %v %v %v %v", f(8), f(9), f(10), f(11)) + var pbuf [render3d.PointShadowUniformSize + 8]byte + pout := pu.Encode(pbuf[:]) + if len(pout) != render3d.PointShadowUniformSize || render3d.PointShadowUniformSize != 48 { + t.Fatalf("point encoded %d bytes, want 48", len(pout)) } - if f(12) != 0.04 || f(13) != 0.05 || f(14) != 0.06 || f(15) != 0 { - t.Fatalf("ambient_pad mismatch: %v %v %v %v", f(12), f(13), f(14), f(15)) + want := [12]float32{1, 2, -3, 14, 0.001, 0.02, 1.0 / 128.0, 0, 0.15, 0, 0, 0} + for i, w := range want { + if f(pout, i) != w { + t.Fatalf("point float %d = %v, want %v", i, f(pout, i), w) + } } - - if allocs := testing.AllocsPerRun(100, func() { u.Encode(buf[:]) }); allocs != 0 { + if allocs := testing.AllocsPerRun(100, func() { pu.Encode(pbuf[:]) }); allocs != 0 { t.Fatalf("PointShadowUniform.Encode allocated %v times", allocs) } - func() { - defer func() { - if recover() == nil { - t.Fatal("Encode with short slice did not panic") - } + + for name, enc := range map[string]func(){ + "spot": func() { u.Encode(make([]byte, render3d.SpotShadowUniformSize-1)) }, + "point": func() { pu.Encode(make([]byte, render3d.PointShadowUniformSize-1)) }, + } { + func() { + defer func() { + if recover() == nil { + t.Fatalf("%s Encode with short slice did not panic", name) + } + }() + enc() }() - u.Encode(make([]byte, render3d.PointShadowUniformSize-1)) - }() + } } func TestPointShadowFaceProjectionConsistency(t *testing.T) { - light := render3d.PointShadowLight{ - Position: math3d.Vec3{X: 1.5, Y: -0.75, Z: 2.25}, - Near: 0.2, - Range: 16.0, + u, err := render3d.NewPointShadowUniform(render3d.PointLight{Position: math3d.Vec3{X: 1.5, Y: -0.75, Z: 2.25}, Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, Intensity: 1, Range: 16}, render3d.PointShadowConfig{Near: 0.2}) + if err != nil { + t.Fatal(err) } probes := []struct { offset math3d.Vec3 @@ -446,32 +510,37 @@ func TestPointShadowFaceProjectionConsistency(t *testing.T) { {math3d.Vec3{X: 1.2, Y: -0.6, Z: 3.8}, gpu.CubeFacePosZ}, {math3d.Vec3{X: -1.3, Y: 1.5, Z: -4.6}, gpu.CubeFaceNegZ}, } - for _, tc := range probes { - face, u, v, axisDist := render3d.PointShadowSelectFace(tc.offset) + face, fu, fv, axisDist := render3d.PointShadowSelectFace(tc.offset) if face != tc.wantFace { t.Fatalf("offset %v selected face %d, want %d", tc.offset, face, tc.wantFace) } - world := light.Position.Add(tc.offset) - vp := light.FaceViewProj(face) - clip := vp.MulVec4(world.Vec4(1)) + clip := u.FaceViewProj(face).MulVec4(u.Position.Add(tc.offset).Vec4(1)) if clip.W <= 0 { t.Fatalf("face %d clip.W = %v, want > 0", face, clip.W) } - ndcX, ndcY, ndcZ := clip.X/clip.W, clip.Y/clip.W, clip.Z/clip.W - gotU := ndcX*0.5 + 0.5 - gotV := 0.5 - ndcY*0.5 - wantZ := (light.Range / (light.Range - light.Near)) * (1.0 - light.Near/axisDist) - if math.Abs(float64(u-gotU)) > 1e-5 || math.Abs(float64(v-gotV)) > 1e-5 { - t.Errorf("face %d UV mismatch: select=(%f,%f), proj=(%f,%f)", face, u, v, gotU, gotV) + gotU := clip.X/clip.W*0.5 + 0.5 + gotV := 0.5 - clip.Y/clip.W*0.5 + wantZ := (u.Far / (u.Far - u.Near)) * (1.0 - u.Near/axisDist) + if math.Abs(float64(fu-gotU)) > 1e-5 || math.Abs(float64(fv-gotV)) > 1e-5 { + t.Errorf("face %d UV mismatch: select=(%f,%f), proj=(%f,%f)", face, fu, fv, gotU, gotV) } - if math.Abs(float64(ndcZ-wantZ)) > 1e-5 { - t.Errorf("face %d depth mismatch: analytic=%f, proj=%f", face, wantZ, ndcZ) + if math.Abs(float64(clip.Z/clip.W-wantZ)) > 1e-5 { + t.Errorf("face %d depth mismatch: analytic=%f, proj=%f", face, wantZ, clip.Z/clip.W) } } } -func localShadowTestRenderSpotScene(t *testing.T, filter render3d.LocalShadowFilter) (*image.RGBA, []float32, render3d.SpotShadowUniform, *scene3d.Camera) { +type localShadowSpotResult struct { + img *image.RGBA + depth []float32 + uniform render3d.SpotShadowUniform + cam *scene3d.Camera + rig render3d.LightRig +} + +// localShadowTestRenderSpotScene draws a floor and two pillars, all with their own model matrices, lit by the first spot light of a LightRig through LitPBRSpotShadowWGSL. +func localShadowTestRenderSpotScene(t *testing.T, filter render3d.LocalShadowFilter) localShadowSpotResult { t.Helper() const shadowRes = 128 @@ -485,8 +554,16 @@ func localShadowTestRenderSpotScene(t *testing.T, filter render3d.LocalShadowFil } t.Cleanup(func() { _ = camBuf.Close() }) + rig := render3d.LightRig{Ambient: localShadowAmbient, Spot: []render3d.SpotLight{localShadowTestSpot}} + lightBuf, err := render3d.NewLightBuffer(nil, dev, rig, render3d.LightBufferOptions{Label: "spot-lights"}) + if err != nil { + t.Fatalf("NewLightBuffer: %v", err) + } + t.Cleanup(func() { _ = lightBuf.Close() }) + spotShadow, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{ Resolution: shadowRes, + Near: 0.2, DepthBias: 0.002, NormalBias: 0.025, Filter: filter, @@ -497,177 +574,131 @@ func localShadowTestRenderSpotScene(t *testing.T, filter render3d.LocalShadowFil } t.Cleanup(func() { _ = spotShadow.Close() }) - litPipe, err := render3d.NewSpotShadowLitPipeline(nil, dev, camBuf.Layout(), spotShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ - DepthFormat: gpu.FormatDepth24Plus, - CullMode: gpu.CullBack, + floor := localShadowUpload(t, nil, dev, "floor", localShadowTestSubdividedQuad(math3d.Vec3Zero(), math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}, math3d.Vec3Up(), 4.5, 4.5, 6), false) + unitBox := localShadowUpload(t, nil, dev, "unit-box", localShadowTestBoxMesh(math3d.Vec3Zero(), math3d.Vec3{X: 0.5, Y: 0.5, Z: 0.5}), false) + pillar1Model := math3d.Translate(math3d.Vec3{X: -0.2, Y: 0.9, Z: 0.1}).Mul(math3d.Scale(math3d.Vec3{X: 0.9, Y: 1.8, Z: 0.9})) + pillar2Model := math3d.Translate(math3d.Vec3{X: 1.15, Y: 0.65, Z: -0.95}).Mul(math3d.Scale(math3d.Vec3{X: 0.7, Y: 1.3, Z: 0.7})) + draws := localShadowDrawBuffers(t, nil, dev, false, + []*render3d.GPUMesh{floor, unitBox, unitBox}, + []render3d.PBRDrawUniform{ + render3d.NewPBRDrawUniform(math3d.Mat4Identity(), localShadowFloorMat), + render3d.NewPBRDrawUniform(pillar1Model, localShadowPillarMat), + render3d.NewPBRDrawUniform(pillar2Model, localShadowPillarMat), + }) + + litPipe, err := render3d.NewLitPBRPipelineWithOptions(nil, dev, camBuf.Layout(), lightBuf.Layout(), draws[0].buf.Layout(), render3d.LitPBRPipelineOptions{ + ColorFormat: gpu.FormatRGBA8Unorm, + DepthFormat: gpu.FormatDepth24Plus, + SpotShadowLayout: spotShadow.Layout(), }) if err != nil { - t.Fatalf("NewSpotShadowLitPipeline: %v", err) + t.Fatalf("NewLitPBRPipelineWithOptions(SpotShadowLayout): %v", err) } t.Cleanup(func() { _ = litPipe.Close() }) - floorMesh := localShadowTestSubdividedQuad( - math3d.Vec3{Y: 0}, - math3d.Vec3{X: 1}, - math3d.Vec3{Z: -1}, - math3d.Vec3Up(), - 4.5, 4.5, 6, - ) - pillar1 := localShadowTestBoxMesh(math3d.Vec3{X: -0.2, Y: 0.9, Z: 0.1}, math3d.Vec3{X: 0.45, Y: 0.9, Z: 0.45}) - pillar2Local := localShadowTestBoxMesh(math3d.Vec3Zero(), math3d.Vec3{X: 0.35, Y: 0.65, Z: 0.35}) - pillar2Model := math3d.Translate(math3d.Vec3{X: 1.15, Y: 0.65, Z: -0.95}) - pillar2World := localShadowTestBoxMesh(math3d.Vec3{X: 1.15, Y: 0.65, Z: -0.95}, math3d.Vec3{X: 0.35, Y: 0.65, Z: 0.35}) - - gpuFloor, err := render3d.UploadMesh(nil, dev, floorMesh, render3d.MeshUpload{Label: "floor"}) - if err != nil { - t.Fatalf("UploadMesh floor: %v", err) - } - t.Cleanup(func() { _ = gpuFloor.Close() }) - gpuPillar1, err := render3d.UploadMesh(nil, dev, pillar1, render3d.MeshUpload{Label: "pillar1"}) - if err != nil { - t.Fatalf("UploadMesh pillar1: %v", err) - } - t.Cleanup(func() { _ = gpuPillar1.Close() }) - gpuPillar2Local, err := render3d.UploadMesh(nil, dev, pillar2Local, render3d.MeshUpload{Label: "pillar2-local"}) - if err != nil { - t.Fatalf("UploadMesh pillar2Local: %v", err) - } - t.Cleanup(func() { _ = gpuPillar2Local.Close() }) - gpuScene, err := render3d.UploadMesh(nil, dev, localShadowTestMergeMeshes(floorMesh, pillar1, pillar2World), render3d.MeshUpload{Label: "spot-scene"}) - if err != nil { - t.Fatalf("UploadMesh scene: %v", err) - } - t.Cleanup(func() { _ = gpuScene.Close() }) - - light := render3d.SpotShadowLight{ - Position: math3d.Vec3{X: -2.4, Y: 3.6, Z: 2.3}, - Direction: math3d.Vec3{X: 2.5, Y: -3.5, Z: -2.5}.Norm(), - Color: math3d.Vec3{X: 1.0, Y: 0.92, Z: 0.78}, - Intensity: 20.0, - Near: 0.2, - Range: 14.0, - InnerConeAngle: math3d.DegToRad(26), - OuterConeAngle: math3d.DegToRad(44), - Ambient: math3d.Vec3{X: 0.08, Y: 0.09, Z: 0.12}, - } - if err := spotShadow.Update(dev, light); err != nil { + if err := spotShadow.Update(dev, localShadowTestSpot); err != nil { t.Fatalf("spotShadow.Update: %v", err) } - cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0.4, Y: 4.8, Z: 5.0}, math3d.DegToRad(48), float32(localShadowTestWidth)/float32(localShadowTestHeight), 0.1, 30) cam.LookAt(math3d.Vec3{X: 0.35, Y: 0.3, Z: -0.35}, math3d.Vec3Up()) camBuf.WriteCamera(cam) enc := dev.BeginEncoder() - // Pass 1: depth-only spot shadow pass with multiple casters using distinct model transforms. - sp := spotShadow.BeginShadowPass(enc) - spotShadow.DrawCaster(dev, sp, gpuPillar1, math3d.Mat4Identity()) - spotShadow.DrawCaster(dev, sp, gpuPillar2Local, pillar2Model) + sp := spotShadow.BeginShadowPass(dev, enc) + if sp == nil { + t.Fatal("BeginShadowPass returned nil") + } + for i, m := range []math3d.Mat4{pillar1Model, pillar2Model} { + if !spotShadow.DrawCaster(sp, unitBox, m) { + t.Fatalf("DrawCaster %d returned false", i) + } + } sp.End() - - // Pass 2: lit main pass sampling spot shadow map. - mp := enc.BeginRenderPass(gpu.RenderPassDesc{ - Label: "spot-lit-main", - ColorAttachments: []gpu.ColorAttachment{{ - LoadOp: gpu.LoadClear, - StoreOp: gpu.StoreStore, - ClearColor: localShadowTestClear, - }}, - DepthStencil: &gpu.DepthStencilAttachment{ - DepthLoadOp: gpu.LoadClear, - DepthStoreOp: gpu.StoreDiscard, - ClearDepth: 1.0, - }, - }) - mp.SetPipeline(litPipe) - mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) - mp.SetBindGroup(render3d.LocalShadowGroup, spotShadow.BindGroup()) - gpuScene.Draw(mp) + mp := localShadowMainPass(enc) + localShadowDrawReceivers(mp, litPipe, camBuf, lightBuf, spotShadow.BindGroup(), draws) mp.End() - dev.Submit(enc.Finish()) + sr.WaitIdle() if err := sr.LastError(); err != nil { t.Fatalf("software renderer error: %v", err) } depth := localShadowTestReadDepth(t, dev, spotShadow.DepthTexture(), shadowRes, shadowRes) - return sr.Image(), depth, spotShadow.Uniforms(), cam + return localShadowSpotResult{img: sr.Image(), depth: depth, uniform: spotShadow.Uniforms(), cam: cam, rig: rig} } func TestSpotShadowMatchesReferenceAndGolden(t *testing.T) { - pcfImg, pcfDepth, pcfUniform, cam := localShadowTestRenderSpotScene(t, render3d.LocalShadowFilterPCF3x3) - hardImg, hardDepth, hardUniform, _ := localShadowTestRenderSpotScene(t, render3d.LocalShadowFilterHard) + pcf := localShadowTestRenderSpotScene(t, render3d.LocalShadowFilterPCF3x3) + hard := localShadowTestRenderSpotScene(t, render3d.LocalShadowFilterHard) - localShadowTestAssertGolden(t, "local_shadow_spot", pcfImg) + localShadowTestAssertGolden(t, "local_shadow_spot", pcf.img) - // Probe analytic visibility & GPU-vs-CPU color agreement across lit, shadowed, and out-of-cone points. probes := []struct { name string world math3d.Vec3 - normal math3d.Vec3 wantVisLo float32 wantVisHi float32 }{ - {"lit-floor-in-front", math3d.Vec3{X: -1.1, Y: 0, Z: 1.0}, math3d.Vec3Up(), 0.95, 1.0}, - {"shadowed-floor-behind-pillar1", math3d.Vec3{X: 0.7, Y: 0, Z: -0.7}, math3d.Vec3Up(), 0.0, 0.05}, - {"shadowed-floor-behind-pillar2", math3d.Vec3{X: 1.7, Y: 0, Z: -1.5}, math3d.Vec3Up(), 0.0, 0.05}, - {"lit-floor-side", math3d.Vec3{X: -1.4, Y: 0, Z: -0.9}, math3d.Vec3Up(), 0.95, 1.0}, + {"lit-floor-in-front", math3d.Vec3{X: -1.1, Y: 0, Z: 1.0}, 0.95, 1.0}, + {"shadowed-floor-behind-pillar1", math3d.Vec3{X: 0.7, Y: 0, Z: -0.7}, 0.0, 0.05}, + {"shadowed-floor-behind-pillar2", math3d.Vec3{X: 1.7, Y: 0, Z: -1.5}, 0.0, 0.05}, + {"lit-floor-side", math3d.Vec3{X: -1.4, Y: 0, Z: -0.9}, 0.95, 1.0}, } - - for _, tc := range probes { - cpuVis := render3d.EvaluateSpotShadow(pcfUniform, pcfDepth, 128, tc.world, tc.normal) - if cpuVis < tc.wantVisLo || cpuVis > tc.wantVisHi { - t.Errorf("%s: CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, cpuVis, tc.wantVisLo, tc.wantVisHi) - } - cpuCol := localShadowTestColorToRGB8(render3d.EvaluateSpotLighting(pcfUniform, pcfDepth, 128, tc.world, tc.normal, localShadowTestAlbedo)) - gpuCol, px, py, ok := localShadowTestSamplePixel(pcfImg, cam, tc.world) - if !ok { - t.Fatalf("%s: probe %v outside view", tc.name, tc.world) - } - if diff := localShadowTestRGBDiff(gpuCol, cpuCol); diff > 10 { - t.Errorf("%s at (%d,%d): GPU=%v vs CPU=%v (max diff %d)", tc.name, px, py, gpuCol, cpuCol, diff) - } - - hardVis := render3d.EvaluateSpotShadow(hardUniform, hardDepth, 128, tc.world, tc.normal) - if hardVis < tc.wantVisLo || hardVis > tc.wantVisHi { - t.Errorf("%s (hard): CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, hardVis, tc.wantVisLo, tc.wantVisHi) - } - hardGPU, _, _, _ := localShadowTestSamplePixel(hardImg, cam, tc.world) - hardCPU := localShadowTestColorToRGB8(render3d.EvaluateSpotLighting(hardUniform, hardDepth, 128, tc.world, tc.normal, localShadowTestAlbedo)) - if diff := localShadowTestRGBDiff(hardGPU, hardCPU); diff > 10 { - t.Errorf("%s (hard): GPU=%v vs CPU=%v (max diff %d)", tc.name, hardGPU, hardCPU, diff) + up := math3d.Vec3Up() + for _, r := range []struct { + name string + res localShadowSpotResult + }{{"pcf", pcf}, {"hard", hard}} { + for _, tc := range probes { + vis := render3d.EvaluateSpotShadow(r.res.uniform, r.res.depth, 128, tc.world, up) + if vis < tc.wantVisLo || vis > tc.wantVisHi { + t.Errorf("%s %s: CPU visibility = %.3f, want in [%.2f, %.2f]", r.name, tc.name, vis, tc.wantVisLo, tc.wantVisHi) + } + want := localShadowExpected(r.res.cam, tc.world, up, localShadowFloorMat, r.res.rig, render3d.LightVisibility{Directional0: 1, Point0: 1, Spot0: vis}) + got, px, py, ok := localShadowTestSamplePixel(r.res.img, r.res.cam, tc.world) + if !ok { + t.Fatalf("%s: probe %v outside view", tc.name, tc.world) + } + if diff := localShadowTestRGBDiff(got, want); diff > 10 { + t.Errorf("%s %s at (%d,%d): GPU=%v vs CPU=%v (max diff %d)", r.name, tc.name, px, py, got, want, diff) + } } } - // Verify lit floor is markedly brighter than shadowed floor behind both casters. - litPx, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -1.1, Y: 0, Z: 1.0}) - shad1Px, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 0.7, Y: 0, Z: -0.7}) - shad2Px, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 1.7, Y: 0, Z: -1.5}) + // The shadow removes the spot light's contribution: lit floor is markedly brighter than floor behind either pillar. + litPx, _, _, _ := localShadowTestSamplePixel(pcf.img, pcf.cam, math3d.Vec3{X: -1.1, Y: 0, Z: 1.0}) + shad1Px, _, _, _ := localShadowTestSamplePixel(pcf.img, pcf.cam, math3d.Vec3{X: 0.7, Y: 0, Z: -0.7}) + shad2Px, _, _, _ := localShadowTestSamplePixel(pcf.img, pcf.cam, math3d.Vec3{X: 1.7, Y: 0, Z: -1.5}) if int(litPx[0]) < int(shad1Px[0])+80 || int(litPx[0]) < int(shad2Px[0])+80 { t.Fatalf("expected strong shadow contrast: lit=%v shad1=%v shad2=%v", litPx, shad1Px, shad2Px) } - // Verify Hard vs PCF3x3: scanning across the shadow edge produces intermediate - // visibility values strictly in (0, 1) for PCF3x3 and only 0 or 1 for Hard. + // Hard shadows are binary; PCF 3x3 produces a penumbra along the shadow edge. pcfPenumbra := 0 for i := range 60 { - x := float32(-0.5) + float32(i)*0.04 - pt := math3d.Vec3{X: x, Y: 0, Z: -0.7} - hv := render3d.EvaluateSpotShadow(hardUniform, hardDepth, 128, pt, math3d.Vec3Up()) - if hv != 0 && hv != 1 { + pt := math3d.Vec3{X: float32(-0.5) + float32(i)*0.04, Y: 0, Z: -0.7} + if hv := render3d.EvaluateSpotShadow(hard.uniform, hard.depth, 128, pt, up); hv != 0 && hv != 1 { t.Fatalf("hard shadow returned non-binary visibility %v at %v", hv, pt) } - pv := render3d.EvaluateSpotShadow(pcfUniform, pcfDepth, 128, pt, math3d.Vec3Up()) - if pv > 0.05 && pv < 0.95 { + if pv := render3d.EvaluateSpotShadow(pcf.uniform, pcf.depth, 128, pt, up); pv > 0.05 && pv < 0.95 { pcfPenumbra++ } } if pcfPenumbra == 0 { - t.Errorf("expected PCF3x3 to produce smooth intermediate penumbra taps along shadow boundary") + t.Error("expected PCF3x3 to produce intermediate penumbra taps along the shadow boundary") } } -func localShadowTestRenderPointScene(t *testing.T, filter render3d.LocalShadowFilter) (*image.RGBA, []float32, render3d.PointShadowUniform, *scene3d.Camera) { +type localShadowPointResult struct { + img *image.RGBA + depth []float32 + uniform render3d.PointShadowUniform + cam *scene3d.Camera + rig render3d.LightRig +} + +// localShadowTestRenderPointScene draws an open room corner with three blockers lit by the first point light of a LightRig through LitPBRPointShadowWGSL. +func localShadowTestRenderPointScene(t *testing.T, filter render3d.LocalShadowFilter) localShadowPointResult { t.Helper() const faceRes = 64 @@ -681,8 +712,16 @@ func localShadowTestRenderPointScene(t *testing.T, filter render3d.LocalShadowFi } t.Cleanup(func() { _ = camBuf.Close() }) + rig := render3d.LightRig{Ambient: localShadowAmbient, Point: []render3d.PointLight{localShadowTestPoint}} + lightBuf, err := render3d.NewLightBuffer(nil, dev, rig, render3d.LightBufferOptions{Label: "point-lights"}) + if err != nil { + t.Fatalf("NewLightBuffer: %v", err) + } + t.Cleanup(func() { _ = lightBuf.Close() }) + pointShadow, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{ FaceResolution: faceRes, + Near: 0.15, DepthBias: 0.0025, NormalBias: 0.03, Filter: filter, @@ -693,129 +732,75 @@ func localShadowTestRenderPointScene(t *testing.T, filter render3d.LocalShadowFi } t.Cleanup(func() { _ = pointShadow.Close() }) - litPipe, err := render3d.NewPointShadowLitPipeline(nil, dev, camBuf.Layout(), pointShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ - DepthFormat: gpu.FormatDepth24Plus, - CullMode: gpu.CullBack, + floor := localShadowTestSubdividedQuad(math3d.Vec3Zero(), math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}, math3d.Vec3Up(), 3.2, 3.2, 8) + backWall := localShadowTestSubdividedQuad(math3d.Vec3{Y: 2.0, Z: -3.0}, math3d.Vec3{X: 1}, math3d.Vec3{Y: 1}, math3d.Vec3{Z: 1}, 3.2, 2.0, 6) + rightWall := localShadowTestSubdividedQuad(math3d.Vec3{X: 3.0, Y: 2.0}, math3d.Vec3{Z: 1}, math3d.Vec3{Y: 1}, math3d.Vec3{X: -1}, 3.2, 2.0, 6) + room := localShadowUpload(t, nil, dev, "room", localShadowTestMergeMeshes(floor, backWall, rightWall), false) + unitBox := localShadowUpload(t, nil, dev, "unit-box", localShadowTestBoxMesh(math3d.Vec3Zero(), math3d.Vec3{X: 0.5, Y: 0.5, Z: 0.5}), false) + + // Three blockers along distinct cube faces (+X, -Z and -Y relative to the light at (0, 1.8, 0)). + blockers := []math3d.Mat4{ + math3d.Translate(math3d.Vec3{X: 1.45, Y: 1.45, Z: 0.1}).Mul(math3d.Scale(math3d.Vec3{X: 0.7, Y: 1.1, Z: 0.9})), + math3d.Translate(math3d.Vec3{X: -0.1, Y: 1.45, Z: -1.45}).Mul(math3d.Scale(math3d.Vec3{X: 0.9, Y: 1.1, Z: 0.7})), + math3d.Translate(math3d.Vec3{X: -0.85, Y: 0.75, Z: 0.75}).Mul(math3d.Scale(math3d.Vec3{X: 0.9, Y: 0.7, Z: 0.9})), + } + meshes := []*render3d.GPUMesh{room} + uniforms := []render3d.PBRDrawUniform{render3d.NewPBRDrawUniform(math3d.Mat4Identity(), localShadowFloorMat)} + for _, m := range blockers { + meshes = append(meshes, unitBox) + uniforms = append(uniforms, render3d.NewPBRDrawUniform(m, localShadowPillarMat)) + } + draws := localShadowDrawBuffers(t, nil, dev, false, meshes, uniforms) + + litPipe, err := render3d.NewLitPBRPipelineWithOptions(nil, dev, camBuf.Layout(), lightBuf.Layout(), draws[0].buf.Layout(), render3d.LitPBRPipelineOptions{ + ColorFormat: gpu.FormatRGBA8Unorm, + DepthFormat: gpu.FormatDepth24Plus, + PointShadowLayout: pointShadow.Layout(), }) if err != nil { - t.Fatalf("NewPointShadowLitPipeline: %v", err) + t.Fatalf("NewLitPBRPipelineWithOptions(PointShadowLayout): %v", err) } t.Cleanup(func() { _ = litPipe.Close() }) - // Open room corner: subdivided floor (y=0), back wall (z=-3.0, normal +Z), right wall (x=3.0, normal -X). - floor := localShadowTestSubdividedQuad( - math3d.Vec3{X: 0, Y: 0, Z: 0}, - math3d.Vec3{X: 1}, - math3d.Vec3{Z: -1}, - math3d.Vec3Up(), - 3.2, 3.2, 8, - ) - backWall := localShadowTestSubdividedQuad( - math3d.Vec3{X: 0, Y: 2.0, Z: -3.0}, - math3d.Vec3{X: 1}, - math3d.Vec3{Y: 1}, - math3d.Vec3{Z: 1}, - 3.2, 2.0, 6, - ) - rightWall := localShadowTestSubdividedQuad( - math3d.Vec3{X: 3.0, Y: 2.0, Z: 0}, - math3d.Vec3{Z: 1}, - math3d.Vec3{Y: 1}, - math3d.Vec3{X: -1}, - 3.2, 2.0, 6, - ) - - // Three blockers placed along distinct cube faces (+X, -Z, and -Y relative to light at (0, 1.8, 0)). - blockerPosX := localShadowTestBoxMesh(math3d.Vec3{X: 1.45, Y: 1.45, Z: 0.1}, math3d.Vec3{X: 0.35, Y: 0.55, Z: 0.45}) - blockerNegZ := localShadowTestBoxMesh(math3d.Vec3{X: -0.1, Y: 1.45, Z: -1.45}, math3d.Vec3{X: 0.45, Y: 0.55, Z: 0.35}) - blockerFloorLocal := localShadowTestBoxMesh(math3d.Vec3Zero(), math3d.Vec3{X: 0.45, Y: 0.35, Z: 0.45}) - blockerFloorPos := math3d.Vec3{X: -0.85, Y: 0.75, Z: 0.75} - blockerFloorWorld := localShadowTestBoxMesh(blockerFloorPos, math3d.Vec3{X: 0.45, Y: 0.35, Z: 0.45}) - - gpuBlockerX, err := render3d.UploadMesh(nil, dev, blockerPosX, render3d.MeshUpload{Label: "blocker-x"}) - if err != nil { - t.Fatalf("UploadMesh blockerX: %v", err) - } - t.Cleanup(func() { _ = gpuBlockerX.Close() }) - gpuBlockerZ, err := render3d.UploadMesh(nil, dev, blockerNegZ, render3d.MeshUpload{Label: "blocker-z"}) - if err != nil { - t.Fatalf("UploadMesh blockerZ: %v", err) - } - t.Cleanup(func() { _ = gpuBlockerZ.Close() }) - gpuBlockerFloor, err := render3d.UploadMesh(nil, dev, blockerFloorLocal, render3d.MeshUpload{Label: "blocker-y"}) - if err != nil { - t.Fatalf("UploadMesh blockerFloor: %v", err) - } - t.Cleanup(func() { _ = gpuBlockerFloor.Close() }) - gpuRoom, err := render3d.UploadMesh(nil, dev, localShadowTestMergeMeshes( - floor, backWall, rightWall, blockerPosX, blockerNegZ, blockerFloorWorld, - ), render3d.MeshUpload{Label: "point-room"}) - if err != nil { - t.Fatalf("UploadMesh room: %v", err) - } - t.Cleanup(func() { _ = gpuRoom.Close() }) - - light := render3d.PointShadowLight{ - Position: math3d.Vec3{X: 0.0, Y: 1.8, Z: 0.0}, - Color: math3d.Vec3{X: 1.0, Y: 0.94, Z: 0.85}, - Intensity: 14.0, - Near: 0.15, - Range: 12.0, - Ambient: math3d.Vec3{X: 0.07, Y: 0.08, Z: 0.11}, - } - if err := pointShadow.Update(dev, light); err != nil { + if err := pointShadow.Update(dev, localShadowTestPoint); err != nil { t.Fatalf("pointShadow.Update: %v", err) } - cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: -3.8, Y: 4.3, Z: 4.4}, math3d.DegToRad(50), float32(localShadowTestWidth)/float32(localShadowTestHeight), 0.1, 30) cam.LookAt(math3d.Vec3{X: 0.5, Y: 1.0, Z: -0.5}, math3d.Vec3Up()) camBuf.WriteCamera(cam) enc := dev.BeginEncoder() - // Render all 6 omnidirectional cube faces into the 3x2 depth atlas. for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { - fp := pointShadow.BeginFacePass(enc, face) - pointShadow.DrawCaster(dev, fp, gpuBlockerX, math3d.Mat4Identity()) - pointShadow.DrawCaster(dev, fp, gpuBlockerZ, math3d.Mat4Identity()) - pointShadow.DrawCaster(dev, fp, gpuBlockerFloor, math3d.Translate(blockerFloorPos)) + fp := pointShadow.BeginFacePass(dev, enc, face) + if fp == nil { + t.Fatalf("BeginFacePass(%d) returned nil", face) + } + for i, m := range blockers { + if !pointShadow.DrawCaster(fp, unitBox, m) { + t.Fatalf("face %d DrawCaster %d returned false", face, i) + } + } fp.End() } - - mp := enc.BeginRenderPass(gpu.RenderPassDesc{ - Label: "point-lit-main", - ColorAttachments: []gpu.ColorAttachment{{ - LoadOp: gpu.LoadClear, - StoreOp: gpu.StoreStore, - ClearColor: localShadowTestClear, - }}, - DepthStencil: &gpu.DepthStencilAttachment{ - DepthLoadOp: gpu.LoadClear, - DepthStoreOp: gpu.StoreDiscard, - ClearDepth: 1.0, - }, - }) - mp.SetPipeline(litPipe) - mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) - mp.SetBindGroup(render3d.LocalShadowGroup, pointShadow.BindGroup()) - gpuRoom.Draw(mp) + mp := localShadowMainPass(enc) + localShadowDrawReceivers(mp, litPipe, camBuf, lightBuf, pointShadow.BindGroup(), draws) mp.End() - dev.Submit(enc.Finish()) + sr.WaitIdle() if err := sr.LastError(); err != nil { t.Fatalf("software renderer error: %v", err) } depth := localShadowTestReadDepth(t, dev, pointShadow.DepthTexture(), pointShadow.AtlasWidth(), pointShadow.AtlasHeight()) - return sr.Image(), depth, pointShadow.Uniforms(), cam + return localShadowPointResult{img: sr.Image(), depth: depth, uniform: pointShadow.Uniforms(), cam: cam, rig: rig} } func TestPointShadowMatchesReferenceAndGolden(t *testing.T) { - pcfImg, pcfDepth, pcfUniform, cam := localShadowTestRenderPointScene(t, render3d.LocalShadowFilterPCF3x3) - hardImg, hardDepth, hardUniform, _ := localShadowTestRenderPointScene(t, render3d.LocalShadowFilterHard) + pcf := localShadowTestRenderPointScene(t, render3d.LocalShadowFilterPCF3x3) + hard := localShadowTestRenderPointScene(t, render3d.LocalShadowFilterHard) - localShadowTestAssertGolden(t, "local_shadow_point", pcfImg) + localShadowTestAssertGolden(t, "local_shadow_point", pcf.img) - // Verify omnidirectional shadows across +X wall, -Z wall, and -Y floor! probes := []struct { name string world math3d.Vec3 @@ -829,53 +814,314 @@ func TestPointShadowMatchesReferenceAndGolden(t *testing.T) { {"back-wall-shadow-negZ", math3d.Vec3{X: -0.2, Y: 1.1, Z: -3.0}, math3d.Vec3{Z: 1}, gpu.CubeFaceNegZ, 0.0, 0.05}, {"back-wall-lit-negZ", math3d.Vec3{X: -2.0, Y: 2.6, Z: -3.0}, math3d.Vec3{Z: 1}, gpu.CubeFaceNegZ, 0.95, 1.0}, {"floor-shadow-negY", math3d.Vec3{X: -1.45, Y: 0.0, Z: 1.3}, math3d.Vec3Up(), gpu.CubeFaceNegY, 0.0, 0.05}, - {"floor-lit-center", math3d.Vec3{X: 0.0, Y: 0.0, Z: 0.0}, math3d.Vec3Up(), gpu.CubeFaceNegY, 0.95, 1.0}, + {"floor-lit-front", math3d.Vec3{X: 0.8, Y: 0.0, Z: 0.8}, math3d.Vec3Up(), gpu.CubeFaceNegY, 0.95, 1.0}, + } + for _, r := range []struct { + name string + res localShadowPointResult + }{{"pcf", pcf}, {"hard", hard}} { + for _, tc := range probes { + if gotFace, _, _, _ := render3d.PointShadowSelectFace(tc.world.Sub(r.res.uniform.Position)); gotFace != tc.wantFace { + t.Errorf("%s: cube face = %d, want %d", tc.name, gotFace, tc.wantFace) + } + vis := render3d.EvaluatePointShadow(r.res.uniform, r.res.depth, 64, tc.world, tc.normal) + if vis < tc.wantVisLo || vis > tc.wantVisHi { + t.Errorf("%s %s: CPU visibility = %.3f, want in [%.2f, %.2f]", r.name, tc.name, vis, tc.wantVisLo, tc.wantVisHi) + } + want := localShadowExpected(r.res.cam, tc.world, tc.normal, localShadowFloorMat, r.res.rig, render3d.LightVisibility{Directional0: 1, Point0: vis, Spot0: 1}) + got, px, py, ok := localShadowTestSamplePixel(r.res.img, r.res.cam, tc.world) + if !ok { + t.Fatalf("%s: probe %v outside view", tc.name, tc.world) + } + if diff := localShadowTestRGBDiff(got, want); diff > 12 { + t.Errorf("%s %s at (%d,%d): GPU=%v vs CPU=%v (max diff %d)", r.name, tc.name, px, py, got, want, diff) + } + } } - for _, tc := range probes { - gotFace, _, _, _ := render3d.PointShadowSelectFace(tc.world.Sub(pcfUniform.Position)) - if gotFace != tc.wantFace { - t.Errorf("%s: cube face = %d, want %d", tc.name, gotFace, tc.wantFace) + pairs := []struct { + name string + lit, shad math3d.Vec3 + }{ + {"+X wall", math3d.Vec3{X: 3.0, Y: 2.8, Z: -1.8}, math3d.Vec3{X: 3.0, Y: 1.1, Z: 0.2}}, + {"-Z wall", math3d.Vec3{X: -2.0, Y: 2.6, Z: -3.0}, math3d.Vec3{X: -0.2, Y: 1.1, Z: -3.0}}, + {"-Y floor", math3d.Vec3{X: 0.8, Y: 0.0, Z: 0.8}, math3d.Vec3{X: -1.45, Y: 0.0, Z: 1.3}}, + } + for _, p := range pairs { + litPx, _, _, _ := localShadowTestSamplePixel(pcf.img, pcf.cam, p.lit) + shadPx, _, _, _ := localShadowTestSamplePixel(pcf.img, pcf.cam, p.shad) + if int(litPx[0]) < int(shadPx[0])+40 { + t.Errorf("%s shadow contrast too low: lit=%v shad=%v", p.name, litPx, shadPx) } - cpuVis := render3d.EvaluatePointShadow(pcfUniform, pcfDepth, 64, tc.world, tc.normal) - if cpuVis < tc.wantVisLo || cpuVis > tc.wantVisHi { - t.Errorf("%s: CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, cpuVis, tc.wantVisLo, tc.wantVisHi) + } +} + +// TestLocalShadowWGSLComposesWithLightRig compiles the shadow helpers next to CameraWGSL and LightWGSL, and draws with a spot and a point shadow bound at once through the ForGroup variants, proving they share no binding with the camera, light or per-draw groups. +func TestLocalShadowWGSLComposesWithLightRig(t *testing.T) { + if render3d.SpotShadowWGSLForGroup(render3d.LocalShadowGroup) != render3d.SpotShadowWGSL { + t.Fatal("SpotShadowWGSLForGroup(LocalShadowGroup) differs from SpotShadowWGSL") + } + if render3d.PointShadowWGSLForGroup(render3d.LocalShadowGroup) != render3d.PointShadowWGSL { + t.Fatal("PointShadowWGSLForGroup(LocalShadowGroup) differs from PointShadowWGSL") + } + for name, src := range map[string]string{ + "LitPBRSpotShadowWGSL": render3d.LitPBRSpotShadowWGSL, + "LitPBRPointShadowWGSL": render3d.LitPBRPointShadowWGSL, + "Camera+Light+SpotShadowWGSL": render3d.CameraWGSL + render3d.LightWGSL + render3d.SpotShadowWGSL + "\n@fragment fn fs() -> @location(0) vec4 { return vec4(sample_spot_shadow(vec3(0.0), vec3(0.0, 1.0, 0.0))); }\n", + "Camera+Light+PointShadowWGSL": render3d.CameraWGSL + render3d.LightWGSL + render3d.PointShadowWGSL + "\n@fragment fn fs() -> @location(0) vec4 { return vec4(sample_point_shadow(vec3(0.0), vec3(0.0, 1.0, 0.0))); }\n", + "Spot(3)+Point(2) in one shader": localShadowBothWGSL, + } { + if _, err := gpu.CompileWGSL(src); err != nil { + t.Fatalf("CompileWGSL(%s): %v", name, err) } - cpuCol := localShadowTestColorToRGB8(render3d.EvaluatePointLighting(pcfUniform, pcfDepth, 64, tc.world, tc.normal, localShadowTestAlbedo)) - gpuCol, px, py, ok := localShadowTestSamplePixel(pcfImg, cam, tc.world) - if !ok { - t.Fatalf("%s: probe %v outside view", tc.name, tc.world) + } + + sr := gpu.NewSoftwareRenderer(32, 32, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + camBuf, err := render3d.NewCameraBuffer(nil, dev) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = camBuf.Close() }) + rig := render3d.LightRig{ + Ambient: localShadowAmbient, + Point: []render3d.PointLight{localShadowTestPoint}, + Spot: []render3d.SpotLight{localShadowTestSpot}, + } + lightBuf, err := render3d.NewLightBuffer(nil, dev, rig, render3d.LightBufferOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = lightBuf.Close() }) + spot, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{Resolution: 16}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = spot.Close() }) + point, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{FaceResolution: 8}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = point.Close() }) + if err := spot.Update(dev, localShadowTestSpot); err != nil { + t.Fatal(err) + } + if err := point.Update(dev, localShadowTestPoint); err != nil { + t.Fatal(err) + } + mod, err := gpu.CompileWGSL(localShadowBothWGSL) + if err != nil { + t.Fatal(err) + } + pipe, err := dev.CreatePipeline(nil, gpu.PipelineDesc{ + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs"}, + Layouts: []*gpu.BindGroupLayout{camBuf.Layout(), lightBuf.Layout(), point.Layout(), spot.Layout()}, + VertexBuffers: []gpu.VertexBufferLayout{render3d.MeshVertexLayout()}, + Primitive: gpu.PrimitiveState{Topology: gpu.TopologyTriangleList}, + Targets: []gpu.ColorTargetState{{Format: gpu.FormatRGBA8Unorm, WriteMask: gpu.ColorWriteAll}}, + DepthStencil: &gpu.DepthStencilState{Format: gpu.FormatDepth24Plus, DepthWrite: true, DepthCompare: gpu.CompareLess}, + }) + if err != nil { + t.Fatalf("CreatePipeline(spot at 3, point at 2): %v", err) + } + t.Cleanup(func() { _ = pipe.Close() }) + floor := localShadowUpload(t, nil, dev, "floor", localShadowTestSubdividedQuad(math3d.Vec3Zero(), math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}, math3d.Vec3Up(), 3, 3, 2), false) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 5, Z: 5}, math3d.DegToRad(50), 1, 0.1, 30) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + camBuf.WriteCamera(cam) + + enc := dev.BeginEncoder() + mp := localShadowMainPass(enc) + mp.SetPipeline(pipe) + mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) + mp.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) + mp.SetBindGroup(2, point.BindGroup()) + mp.SetBindGroup(render3d.LocalShadowGroup, spot.BindGroup()) + floor.Draw(mp) + mp.End() + dev.Submit(enc.Finish()) + sr.WaitIdle() + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer error: %v", err) + } +} + +// localShadowBothWGSL shades a world-space mesh with the spot shadow at group 3 and the point shadow at group 2 alongside the camera and light rig. +var localShadowBothWGSL = render3d.CameraWGSL + render3d.LightWGSL + render3d.SpotShadowWGSL + render3d.PointShadowWGSLForGroup(2) + ` +struct VsOut { + @builtin(position) clip: vec4, + @location(0) world_pos: vec3, + @location(1) world_normal: vec3, +} + +@vertex +fn vs(@location(0) pos: vec3, @location(1) normal: vec3, @location(2) uv: vec2) -> VsOut { + var out: VsOut; + out.clip = camera.view_proj * vec4(pos, 1.0); + out.world_pos = pos; + out.world_normal = normal; + return out; +} + +@fragment +fn fs(in: VsOut) -> @location(0) vec4 { + let view_dir = normalize(camera.eye.xyz - in.world_pos * camera.eye.w); + let spot_vis = sample_spot_shadow(in.world_pos, in.world_normal); + let point_vis = sample_point_shadow(in.world_pos, in.world_normal); + let lit = shade_pbr_visibility(in.world_pos, in.world_normal, view_dir, vec3(0.8, 0.8, 0.8), 0.0, 0.9, 1.0, point_vis, spot_vis); + return vec4(linear_to_srgb(lit), 1.0); +} +` + +func TestLitPBRLocalShadowPipelineOptions(t *testing.T) { + if _, err := render3d.NewLitPBRSpotShadowPipeline(nil, nil, nil, nil, nil, nil, gpu.FormatUndefined); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("NewLitPBRSpotShadowPipeline(nil dev) = %v, want ErrDeviceLost", err) + } + if _, err := render3d.NewLitPBRPointShadowPipeline(nil, nil, nil, nil, nil, nil, gpu.FormatUndefined); !errors.Is(err, gpu.ErrDeviceLost) { + t.Fatalf("NewLitPBRPointShadowPipeline(nil dev) = %v, want ErrDeviceLost", err) + } + sr := gpu.NewSoftwareRenderer(8, 8, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + camBuf, err := render3d.NewCameraBuffer(nil, dev) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = camBuf.Close() }) + lightBuf, err := render3d.NewLightBuffer(nil, dev, render3d.LightRig{}, render3d.LightBufferOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = lightBuf.Close() }) + draw, err := render3d.NewPBRDrawBuffer(nil, dev, nil, render3d.NewPBRDrawUniform(math3d.Mat4Identity(), localShadowFloorMat), false) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = draw.Close() }) + spot, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{Resolution: 16}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = spot.Close() }) + point, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{FaceResolution: 8}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = point.Close() }) + + if _, err := render3d.NewLitPBRSpotShadowPipeline(nil, dev, camBuf.Layout(), lightBuf.Layout(), draw.Layout(), nil, gpu.FormatUndefined); !errors.Is(err, gpu.ErrInvalidDescriptor) { + t.Errorf("NewLitPBRSpotShadowPipeline(nil layout) = %v, want ErrInvalidDescriptor", err) + } + if _, err := render3d.NewLitPBRPointShadowPipeline(nil, dev, camBuf.Layout(), lightBuf.Layout(), draw.Layout(), nil, gpu.FormatUndefined); !errors.Is(err, gpu.ErrInvalidDescriptor) { + t.Errorf("NewLitPBRPointShadowPipeline(nil layout) = %v, want ErrInvalidDescriptor", err) + } + for name, opts := range map[string]render3d.LitPBRPipelineOptions{ + "spot+point": {SpotShadowLayout: spot.Layout(), PointShadowLayout: point.Layout()}, + "spot+directional": {SpotShadowLayout: spot.Layout(), ShadowLayout: point.Layout()}, + "point+fog": {PointShadowLayout: point.Layout(), FogLayout: spot.Layout()}, + } { + if _, err := render3d.NewLitPBRPipelineWithOptions(nil, dev, camBuf.Layout(), lightBuf.Layout(), draw.Layout(), opts); !errors.Is(err, gpu.ErrInvalidDescriptor) { + t.Errorf("%s: err = %v, want ErrInvalidDescriptor (bind group 3 conflict)", name, err) } - if diff := localShadowTestRGBDiff(gpuCol, cpuCol); diff > 12 { - t.Errorf("%s at (%d,%d): GPU=%v vs CPU=%v (max diff %d)", tc.name, px, py, gpuCol, cpuCol, diff) + } + for name, mk := range map[string]func() (*gpu.Pipeline, error){ + "spot": func() (*gpu.Pipeline, error) { + return render3d.NewLitPBRSpotShadowPipeline(nil, dev, camBuf.Layout(), lightBuf.Layout(), draw.Layout(), spot.Layout(), gpu.FormatDepth24Plus) + }, + "point": func() (*gpu.Pipeline, error) { + return render3d.NewLitPBRPointShadowPipeline(nil, dev, camBuf.Layout(), lightBuf.Layout(), draw.Layout(), point.Layout(), gpu.FormatDepth24Plus) + }, + "spot-linear": func() (*gpu.Pipeline, error) { + return render3d.NewLitPBRPipelineWithOptions(nil, dev, camBuf.Layout(), lightBuf.Layout(), draw.Layout(), render3d.LitPBRPipelineOptions{SpotShadowLayout: spot.Layout(), LinearOutput: true}) + }, + "point-linear": func() (*gpu.Pipeline, error) { + return render3d.NewLitPBRPipelineWithOptions(nil, dev, camBuf.Layout(), lightBuf.Layout(), draw.Layout(), render3d.LitPBRPipelineOptions{PointShadowLayout: point.Layout(), LinearOutput: true}) + }, + } { + p, err := mk() + if err != nil { + t.Fatalf("%s pipeline: %v", name, err) } + _ = p.Close() + } +} + +func TestLocalShadowCasterSlots(t *testing.T) { + sr := gpu.NewSoftwareRenderer(8, 8, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + box := localShadowUpload(t, nil, dev, "box", localShadowTestBoxMesh(math3d.Vec3{Y: 0.5}, math3d.Vec3{X: 0.5, Y: 0.5, Z: 0.5}), false) + + spot, err := render3d.NewSpotShadowMap(nil, dev, render3d.SpotShadowConfig{Resolution: 16, MaxCasters: 2}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = spot.Close() }) + if spot.MaxCasters() != 2 { + t.Fatalf("MaxCasters = %d, want 2", spot.MaxCasters()) + } + + // Drawing before Update has no light projection, so it is refused. + enc := dev.BeginEncoder() + sp := spot.BeginShadowPass(dev, enc) + if spot.DrawCaster(sp, box, math3d.Mat4Identity()) { + t.Fatal("DrawCaster before Update returned true") + } + sp.End() + dev.Submit(enc.Finish()) - hardVis := render3d.EvaluatePointShadow(hardUniform, hardDepth, 64, tc.world, tc.normal) - if hardVis < tc.wantVisLo || hardVis > tc.wantVisHi { - t.Errorf("%s (hard): CPU visibility = %.3f, want in [%.2f, %.2f]", tc.name, hardVis, tc.wantVisLo, tc.wantVisHi) + if err := spot.Update(dev, localShadowTestSpot); err != nil { + t.Fatal(err) + } + for frame := range 3 { + enc := dev.BeginEncoder() + sp := spot.BeginShadowPass(dev, enc) + for i := range 2 { + if !spot.DrawCaster(sp, box, math3d.Translate(math3d.Vec3{X: float32(i)})) { + t.Fatalf("frame %d caster %d refused", frame, i) + } } - hardGPU, _, _, _ := localShadowTestSamplePixel(hardImg, cam, tc.world) - hardCPU := localShadowTestColorToRGB8(render3d.EvaluatePointLighting(hardUniform, hardDepth, 64, tc.world, tc.normal, localShadowTestAlbedo)) - if diff := localShadowTestRGBDiff(hardGPU, hardCPU); diff > 12 { - t.Errorf("%s (hard): GPU=%v vs CPU=%v (max diff %d)", tc.name, hardGPU, hardCPU, diff) + if spot.DrawCaster(sp, box, math3d.Mat4Identity()) { + t.Fatalf("frame %d: caster beyond MaxCasters accepted", frame) } + sp.End() + dev.Submit(enc.Finish()) } - // Verify strong visual shadow contrast on every shadowed face (+X wall, -Z wall, -Y floor). - wallXShad, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 3.0, Y: 1.1, Z: 0.2}) - wallXLit, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 3.0, Y: 2.8, Z: -1.8}) - wallZShad, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -0.2, Y: 1.1, Z: -3.0}) - wallZLit, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -2.0, Y: 2.6, Z: -3.0}) - floorShad, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: -1.45, Y: 0.0, Z: 1.3}) - floorLit, _, _, _ := localShadowTestSamplePixel(pcfImg, cam, math3d.Vec3{X: 0.0, Y: 0.0, Z: 0.0}) - if int(wallXLit[0]) < int(wallXShad[0])+40 { - t.Errorf("+X wall shadow contrast too low: lit=%v shad=%v", wallXLit, wallXShad) + point, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{FaceResolution: 8, MaxCasters: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = point.Close() }) + if err := point.Update(dev, localShadowTestPoint); err != nil { + t.Fatal(err) + } + // Refreshing only some faces, in any order, frame after frame never runs out of slots: each face owns its own. + for frame := range 8 { + enc := dev.BeginEncoder() + for _, face := range []gpu.CubeFace{gpu.CubeFacePosZ, gpu.CubeFaceNegX} { + fp := point.BeginFacePass(dev, enc, face) + if fp == nil { + t.Fatalf("BeginFacePass(%d) returned nil", face) + } + if !point.DrawCaster(fp, box, math3d.Mat4Identity()) { + t.Fatalf("frame %d face %d: caster refused", frame, face) + } + if point.DrawCaster(fp, box, math3d.Mat4Identity()) { + t.Fatalf("frame %d face %d: caster beyond MaxCasters accepted", frame, face) + } + fp.End() + } + dev.Submit(enc.Finish()) } - if int(wallZLit[0]) < int(wallZShad[0])+40 { - t.Errorf("-Z wall shadow contrast too low: lit=%v shad=%v", wallZLit, wallZShad) + sr.WaitIdle() + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer error: %v", err) } - if int(floorLit[0]) < int(floorShad[0])+80 { - t.Errorf("-Y floor shadow contrast too low: lit=%v shad=%v", floorLit, floorShad) + if point.BeginFacePass(dev, dev.BeginEncoder(), render3d.PointShadowFaceCount) != nil { + t.Fatal("BeginFacePass accepted an out-of-range face") } } @@ -889,45 +1135,43 @@ func localShadowTestStartGPUView(t *testing.T, retained bool, usePoint bool, ext var ( dev *gpu.Device camBuf *render3d.CameraBuffer + lightBuf *render3d.GPULightBuffer + draws []localShadowDraw spotShadow *render3d.SpotShadowMap pointShadow *render3d.PointShadowMap litPipe *gpu.Pipeline gpuCaster *render3d.GPUMesh - gpuScene *render3d.GPUMesh + gpuFloor *render3d.GPUMesh frames int ) cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 4.5, Z: 4.5}, math3d.DegToRad(50), 1.0, 0.1, 30) - cam.LookAt(math3d.Vec3{X: 0, Y: 0, Z: 0}, math3d.Vec3Up()) - - floorMesh := localShadowTestSubdividedQuad( - math3d.Vec3{Y: 0}, - math3d.Vec3{X: 1}, - math3d.Vec3{Z: -1}, - math3d.Vec3Up(), - 4.0, 4.0, 6, - ) - pillarMesh := localShadowTestBoxMesh(math3d.Vec3{X: 0, Y: 0.9, Z: 0}, math3d.Vec3{X: 0.45, Y: 0.9, Z: 0.45}) - sceneMesh := localShadowTestMergeMeshes(floorMesh, pillarMesh) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + + floorMesh := localShadowTestSubdividedQuad(math3d.Vec3Zero(), math3d.Vec3{X: 1}, math3d.Vec3{Z: -1}, math3d.Vec3Up(), 4.0, 4.0, 6) + pillarMesh := localShadowTestBoxMesh(math3d.Vec3Zero(), math3d.Vec3{X: 0.5, Y: 0.5, Z: 0.5}) + pillarModel := math3d.Translate(math3d.Vec3{Y: 0.9}).Mul(math3d.Scale(math3d.Vec3{X: 0.9, Y: 1.8, Z: 0.9})) - spotLight := render3d.SpotShadowLight{ + spotLight := render3d.SpotLight{ Position: math3d.Vec3{X: -2.0, Y: 3.2, Z: 0.0}, - Direction: math3d.Vec3{X: 2.0, Y: -3.2, Z: 0.0}.Norm(), + Direction: math3d.Vec3{X: 2.0, Y: -3.2, Z: 0.0}, Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, - Intensity: 18, - Near: 0.2, + Intensity: 30, Range: 12, InnerConeAngle: math3d.DegToRad(30), OuterConeAngle: math3d.DegToRad(45), - Ambient: math3d.Vec3{X: 0.08, Y: 0.08, Z: 0.08}, } - pointLight := render3d.PointShadowLight{ + pointLight := render3d.PointLight{ Position: math3d.Vec3{X: -2.0, Y: 2.0, Z: 0.0}, Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, - Intensity: 18, - Near: 0.15, + Intensity: 12, Range: 12, - Ambient: math3d.Vec3{X: 0.08, Y: 0.08, Z: 0.08}, + } + rig := render3d.LightRig{Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.08, Y: 0.08, Z: 0.08}, Intensity: 1}} + if usePoint { + rig.Point = []render3d.PointLight{pointLight} + } else { + rig.Spot = []render3d.SpotLight{spotLight} } opts := append([]nsgotest.Option{nsgotest.Size(64, 64), nsgotest.ManualFrames()}, extraOpts...) @@ -939,101 +1183,66 @@ func localShadowTestStartGPUView(t *testing.T, retained bool, usePoint bool, ext OnReady: func(d *gpu.Device) { dev = d var err error - camBuf, err = render3d.NewCameraBuffer(cx, d) - if err != nil { + if camBuf, err = render3d.NewCameraBuffer(cx, d); err != nil { t.Fatalf("NewCameraBuffer: %v", err) } + if lightBuf, err = render3d.NewLightBuffer(cx, d, rig, render3d.LightBufferOptions{}); err != nil { + t.Fatalf("NewLightBuffer: %v", err) + } if !retained || gpuCaster == nil { - gpuCaster, err = render3d.UploadMesh(cx, d, pillarMesh, render3d.MeshUpload{Label: "caster", Retained: retained}) - if err != nil { - t.Fatalf("UploadMesh caster: %v", err) - } - gpuScene, err = render3d.UploadMesh(cx, d, sceneMesh, render3d.MeshUpload{Label: "scene", Retained: retained}) - if err != nil { - t.Fatalf("UploadMesh scene: %v", err) - } + gpuCaster = localShadowUpload(t, cx, d, "caster", pillarMesh, retained) + gpuFloor = localShadowUpload(t, cx, d, "floor", floorMesh, retained) } + draws = localShadowDrawBuffers(t, cx, d, false, + []*render3d.GPUMesh{gpuFloor, gpuCaster}, + []render3d.PBRDrawUniform{ + render3d.NewPBRDrawUniform(math3d.Mat4Identity(), localShadowFloorMat), + render3d.NewPBRDrawUniform(pillarModel, localShadowPillarMat), + }) if usePoint { if !retained || pointShadow == nil { - pointShadow, err = render3d.NewPointShadowMap(cx, d, render3d.PointShadowConfig{ - FaceResolution: 32, - DepthBias: 0.002, - NormalBias: 0.02, - Filter: render3d.LocalShadowFilterPCF3x3, - Retained: retained, - }) - if err != nil { + if pointShadow, err = render3d.NewPointShadowMap(cx, d, render3d.PointShadowConfig{FaceResolution: 32, DepthBias: 0.002, NormalBias: 0.02, Filter: render3d.LocalShadowFilterPCF3x3, Retained: retained}); err != nil { t.Fatalf("NewPointShadowMap: %v", err) } } - litPipe, err = render3d.NewPointShadowLitPipeline(cx, d, camBuf.Layout(), pointShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ - DepthFormat: gpu.FormatDepth24Plus, - CullMode: gpu.CullBack, - }) - if err != nil { - t.Fatalf("NewPointShadowLitPipeline: %v", err) + if litPipe, err = render3d.NewLitPBRPointShadowPipeline(cx, d, camBuf.Layout(), lightBuf.Layout(), draws[0].buf.Layout(), pointShadow.Layout(), gpu.FormatDepth24Plus); err != nil { + t.Fatalf("NewLitPBRPointShadowPipeline: %v", err) } } else { if !retained || spotShadow == nil { - spotShadow, err = render3d.NewSpotShadowMap(cx, d, render3d.SpotShadowConfig{ - Resolution: 64, - DepthBias: 0.002, - NormalBias: 0.02, - Filter: render3d.LocalShadowFilterPCF3x3, - Retained: retained, - }) - if err != nil { + if spotShadow, err = render3d.NewSpotShadowMap(cx, d, render3d.SpotShadowConfig{Resolution: 64, DepthBias: 0.002, NormalBias: 0.02, Filter: render3d.LocalShadowFilterPCF3x3, Retained: retained}); err != nil { t.Fatalf("NewSpotShadowMap: %v", err) } } - litPipe, err = render3d.NewSpotShadowLitPipeline(cx, d, camBuf.Layout(), spotShadow.Layout(), render3d.LocalShadowLitPipelineOptions{ - DepthFormat: gpu.FormatDepth24Plus, - CullMode: gpu.CullBack, - }) - if err != nil { - t.Fatalf("NewSpotShadowLitPipeline: %v", err) + if litPipe, err = render3d.NewLitPBRSpotShadowPipeline(cx, d, camBuf.Layout(), lightBuf.Layout(), draws[0].buf.Layout(), spotShadow.Layout(), gpu.FormatDepth24Plus); err != nil { + t.Fatalf("NewLitPBRSpotShadowPipeline: %v", err) } } }, OnFrame: func(frame *gpu.Frame) { camBuf.WriteCamera(cam) + var shadow *gpu.BindGroup if usePoint { if err := pointShadow.Update(dev, pointLight); err != nil { t.Fatalf("pointShadow.Update: %v", err) } for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { - fp := pointShadow.BeginFacePass(frame, face) - pointShadow.DrawCaster(dev, fp, gpuCaster, math3d.Mat4Identity()) + fp := pointShadow.BeginFacePass(dev, frame, face) + pointShadow.DrawCaster(fp, gpuCaster, pillarModel) fp.End() } + shadow = pointShadow.BindGroup() } else { if err := spotShadow.Update(dev, spotLight); err != nil { t.Fatalf("spotShadow.Update: %v", err) } - sp := spotShadow.BeginShadowPass(frame) - spotShadow.DrawCaster(dev, sp, gpuCaster, math3d.Mat4Identity()) + sp := spotShadow.BeginShadowPass(dev, frame) + spotShadow.DrawCaster(sp, gpuCaster, pillarModel) sp.End() + shadow = spotShadow.BindGroup() } - mp := frame.BeginRenderPass(gpu.RenderPassDesc{ - ColorAttachments: []gpu.ColorAttachment{{ - LoadOp: gpu.LoadClear, - StoreOp: gpu.StoreStore, - ClearColor: localShadowTestClear, - }}, - DepthStencil: &gpu.DepthStencilAttachment{ - DepthLoadOp: gpu.LoadClear, - DepthStoreOp: gpu.StoreDiscard, - ClearDepth: 1.0, - }, - }) - mp.SetPipeline(litPipe) - mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) - if usePoint { - mp.SetBindGroup(render3d.LocalShadowGroup, pointShadow.BindGroup()) - } else { - mp.SetBindGroup(render3d.LocalShadowGroup, spotShadow.BindGroup()) - } - gpuScene.Draw(mp) + mp := localShadowMainPass(frame) + localShadowDrawReceivers(mp, litPipe, camBuf, lightBuf, shadow, draws) mp.End() frame.Submit() frames++ @@ -1125,11 +1334,10 @@ func TestLocalShadowsRetainedDeviceLossRestore(t *testing.T) { } func TestLocalShadowsCloseAndScopeDisposal(t *testing.T) { - // Nil safety. var nilSpot *render3d.SpotShadowMap var nilPoint *render3d.PointShadowMap - if nilSpot.Valid() || nilPoint.Valid() || nilSpot.ByteSize() != 0 || nilPoint.ByteSize() != 0 { - t.Fatal("nil shadow map should report invalid and zero byte size") + if nilSpot.Valid() || nilPoint.Valid() || nilSpot.ByteSize() != 0 || nilPoint.ByteSize() != 0 || nilSpot.MaxCasters() != 0 || nilPoint.MaxCasters() != 0 { + t.Fatal("nil shadow map should report invalid and zero sizes") } if err := nilSpot.Close(); err != nil { t.Fatalf("nil spot Close: %v", err) @@ -1137,8 +1345,10 @@ func TestLocalShadowsCloseAndScopeDisposal(t *testing.T) { if err := nilPoint.Close(); err != nil { t.Fatalf("nil point Close: %v", err) } + if nilSpot.BeginShadowPass(nil, nil) != nil || nilPoint.BeginFacePass(nil, nil, 0) != nil || nilSpot.DrawCaster(nil, nil, math3d.Mat4Identity()) || nilPoint.DrawCaster(nil, nil, math3d.Mat4Identity()) { + t.Fatal("nil shadow map recorded a pass or caster") + } - // Explicit Close idempotency & ByteSize accounting. sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) t.Cleanup(sr.Close) dev := sr.Device() @@ -1159,12 +1369,15 @@ func TestLocalShadowsCloseAndScopeDisposal(t *testing.T) { if spot.Valid() { t.Fatal("spot still valid after Close") } + if err := spot.Update(dev, localShadowTestSpot); !errors.Is(err, render3d.ErrInvalidLocalShadow) { + t.Fatalf("Update after Close = %v, want ErrInvalidLocalShadow", err) + } point, err := render3d.NewPointShadowMap(nil, dev, render3d.PointShadowConfig{FaceResolution: 32, MaxCasters: 24}) if err != nil { t.Fatalf("NewPointShadowMap: %v", err) } - if want := uint64(96*64*4) + render3d.PointShadowUniformSize + 24*256; point.ByteSize() != want { + if want := uint64(96*64*4) + render3d.PointShadowUniformSize + 6*24*256; point.ByteSize() != want { t.Fatalf("point ByteSize = %d, want %d", point.ByteSize(), want) } if err := point.Close(); err != nil { @@ -1177,7 +1390,6 @@ func TestLocalShadowsCloseAndScopeDisposal(t *testing.T) { t.Fatal("point still valid after Close") } - // Scope disposal releases both maps automatically. var ( scopedSpot *render3d.SpotShadowMap scopedPoint *render3d.PointShadowMap @@ -1190,12 +1402,10 @@ func TestLocalShadowsCloseAndScopeDisposal(t *testing.T) { Style: core.Style{Width: core.Pt(8), Height: core.Pt(8)}, OnReady: func(d *gpu.Device) { var err error - scopedSpot, err = render3d.NewSpotShadowMap(cx, d, render3d.SpotShadowConfig{Resolution: 32}) - if err != nil { + if scopedSpot, err = render3d.NewSpotShadowMap(cx, d, render3d.SpotShadowConfig{Resolution: 32}); err != nil { t.Fatalf("NewSpotShadowMap: %v", err) } - scopedPoint, err = render3d.NewPointShadowMap(cx, d, render3d.PointShadowConfig{FaceResolution: 16}) - if err != nil { + if scopedPoint, err = render3d.NewPointShadowMap(cx, d, render3d.PointShadowConfig{FaceResolution: 16}); err != nil { t.Fatalf("NewPointShadowMap: %v", err) } }, diff --git a/packages/game/render3d/testdata/golden/local_shadow_point.png b/packages/game/render3d/testdata/golden/local_shadow_point.png index fcf6e919c252a6b1b92c4b06656eab4439c5bb4e..0b4b9529c5fd3136051ef7559631dd942ad1758a 100644 GIT binary patch literal 9465 zcmVy)&eeAjBMbRF~%AcOKT%X zFckE~gIX)Cb&}{(68f?z<+t3na^m(BxW(W7`~Q?9c>hF=67clLKBP!M;;8x1m;ex5 z4Q}NQ0WUEq;4N_23jrkwRRRd{kb@EEV-679q{KWaX<+;XdfFZ(K;n&YEEgQvAj%kH zD{&502k09M{KKF7mwbbLMLqNBXE+WR4T%ti+oJCSL?l!h2nZ1TB}o#0!wW=Pj9?t} zMZf_QkR&ns5e>|Qaskt&bsYa{lmp?Iiqa4h)&?{L!B~j)#|2EBwJE~oKVw9X-PPmq zFIQu1Kt&92S|Cn|wTk0T{1|IAXaFz(%7S)ZWYcQU7Ob)q8Cyn%FvTU}tQ^h=x3>d4 z!mE)4?1R5(KgP;}Dr1TZzy+S5kHTnMt1&fT4VcP}j!Y>?PG?5awHejRQYS802pa-~XQxASX!?+NkucMW$BlK@gK-C3_0kEc_ z{$Tt;fzkL|{8&%{KrRT#1#vV+M9`;nYE?O)w9f%pfQX=nRT5@L2_XAM)UAtkq)^uRALo3mQ-1-U z0!M}YPk{Y6D+u!9{j>#PXV8>nyGkPKeUDojP4MfG1F|Vf3*IO|f?bfuZ68Aj!44G2 z9~>iO(Ck$!2_yI=6EiLoEAdC20&@MRMec~z&Ir%~G& zR_qAL02IZQeZP24yv|sSW=rsU4)A`KQx0JkV*ygq{Sb4`M@1rt1N7y1oRZ+@0RdI- z>J5O>q`26Fh$9P{FEyxuTBCY7AB0{=jWdBDuE+%C1K#rp`bKW6Yg3#pc`pWhBnc{X_Io5RGusj!ynnl3x()==mS1{U;;KUV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spot.png b/packages/game/render3d/testdata/golden/local_shadow_spot.png index 3ae58f56f41f66dca59f7f64df8419262180ee9b..2a0cfe9e5a918c94977bb44667b2748d95bb5949 100644 GIT binary patch literal 7004 zcmbuE^*bXB1-5D!e@*p0RPsLBUD!(VXHFbu4Y}Dd6kSM_VC6`I94%7igSQoN6giQT`M_ zsQf9J0>?Hf;}El>usvsl<_}#i=kqu^oP7R#EzB*iad5NN;$g;Y+05tUaP^d`{ZM!C zafved8Q}^i{2M?Q_s6U}(k0BKRm66)=jpw0k?L*?Jjq>HYT+iCq3* zHUKRkC-k3PTT=e&%_}#W^PV!u(jMp{<-UY|A+uczMGeQgKCu@h^Mabn7(p{k#l3S5 z5vovymdlXiO1`rbf|ctrE55eX&yi;ZN^Jm^yRb-Yf12O}S%Oon!x4lnk%FaDOQr%J zp^Bwks_{e1(VyEIgR#28c17{@fhQQ?bAq4)w{aau$fDf#KA{@uh0+K#LNMW+Sq!`#V{YlQ6G`yX0rvCB)vD_W^ zW1sRuW-~j9vYGR>F3NNS@+Hrif=x)AH?R5e{n29b>wz&NM`*LiI;YST>d&%5D-o{w zNbHM@h*_U0z`%E!i0-?4zomdgYK%GhmV$2)dlM)|l@vy91UO414-p4cgYP%6yjd}* zTNzTRWBN-hF!R(}Ep2|sp7B=?tqD@L?iG%BVv*I+W(vhO0o-hQpI@pie4AE0vWwgN zMCp>QkqLcJyMa5Xxq7t;0kx9JL5@mHZ&}R;fKVRxsv3CiKDT-#s`v~?VT_|A)(?^m#Vg# zi_5l4eOyn!^P@4^uI|@J3c^4VHcH}mp}cUmFP)3D3&c#<@|*hx*f3E_VTQknqRqhk z4>%wFc{y<`6L2Z+Hx`bT?rtIRd6_Z}43mbR6^{%lV)O%w9#HCaqotyJ;SPNAV47)k zAB+=A9{=WbFp%hsl7R%ggScgk;tOg5~R=NXdyiR1Q0&a3>~4X;RY zPcOh2EbVN4{$#vp4~6ZJ7V~j?gf~q46KLhre&wgUv2x>DWVLXp%x1q`9Xln%_o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u`Tb z{8x}B2vJ{-aEK|Dm!t_hEN8a7!yO<+g5q!I|6yMJhB!Kq Date: Wed, 25 Nov 2026 03:09:36 +0900 Subject: [PATCH 3/3] docs(render3d): document spot and point light shadows on the LightRig Rewrite the render3d.md section in both languages for the LightRig-based API, list the new group 3 options next to skinning, add the package overview paragraph, and update the changelog fragment and the design note. --- .../2026-11-24-render3d-local-shadows.md | 22 +++++--- changelog.d/render3d-local-shadows-255.md | 2 +- docs/en/render3d.md | 51 ++++++++++--------- docs/zh/render3d.md | 51 ++++++++++--------- packages/game/render3d/doc.go | 2 + 5 files changed, 74 insertions(+), 54 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md b/.agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md index fb6c8954..0e2ac331 100644 --- a/.agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-local-shadows.md @@ -17,12 +17,14 @@ Implementing local shadows directly on top of NSGo v0.3.0's `gpu.Device` exposes `packages/game/render3d/local_shadows.go` implements `SpotShadowMap` and `PointShadowMap` as dedicated, self-contained files (`local_shadows.go`, `local_shadows_test.go`, and golden PNGs under `testdata/golden/local_shadow_*.png`) to avoid symbol or file collisions with parallel directional/CSM/spotlight work: -- **3×2 2D `FormatDepth32Float` atlas for point lights (`PointShadowMap`)**: All six 90° cube faces (`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`) are packed into a single `(3 * FaceResolution) × (2 * FaceResolution)` depth-only `gpu.RenderTarget`. `BeginFacePass(rec, face)` clears the entire atlas on `face == 0` (`LoadClear`), preserves previous tiles on `face` 1..5 (`LoadLoad`), and locks both `SetViewport` and `SetScissor` to that face's tile so geometry cannot bleed into neighboring faces. +- **Shadows for the `LightRig`'s own lights**: the maps take main's `SpotLight` and `PointLight` (`Update(dev, light)`), not a parallel light type. The far plane is the light's `Range`, or the config's `Far` when `Range` is 0 (unbounded inverse-square falloff); the config carries `Near`. The WGSL only computes visibility (`sample_spot_shadow`, `sample_point_shadow`); lighting stays in `LightWGSL`, whose new `shade_pbr_visibility` scales directional light 0, point light 0 and spot light 0 by a visibility each (`shade_pbr_shadowed` delegates to it). `LitPBRSpotShadowWGSL` / `LitPBRPointShadowWGSL` are `LitPBRWGSL` with the matching map bound, so the per-draw model and normal matrices and the material come from `PBRDrawUniform`, and `ShadePointVisibility` is the CPU reference. +- **Bind group 3**: `LocalShadowGroup` is `ShadowGroup` (3), the slot the directional shadow, fog, IBL and skinning share after camera (0), lights (1) and per-draw data (2). `SpotShadowWGSLForGroup` / `PointShadowWGSLForGroup` move the bindings, so a custom shader can bind a spot and a point shadow at once (tested at groups 3 and 2). +- **3×2 2D `FormatDepth32Float` atlas for point lights (`PointShadowMap`)**: All six 90° cube faces (`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`) are packed into a single `(3 * FaceResolution) × (2 * FaceResolution)` depth-only `gpu.RenderTarget`. `BeginFacePass(dev, target, face)` clears the entire atlas on `face == 0` (`LoadClear`), preserves previous tiles on `face` 1..5 (`LoadLoad`), and locks both `SetViewport` and `SetScissor` to that face's tile so geometry cannot bleed into neighboring faces. - **Analytic perspective depth without a depth fragment shader**: Both spot and point shadow passes use a vertex-only depth pipeline (`vs_local_shadow_depth`) writing standard `[0, 1]` perspective depth. In `PointShadowWGSL`, `sample_point_shadow` selects the dominant cube face from `worldPos + worldNormal * normalBias - lightPos`, projects `(xView, yView, axisDist)` directly into tile-local UV, computes the exact NDC depth `(far/(far-near)) * (1 - near/axisDist)` without uploading six `mat4x4`s to the fragment shader, and clamps every tap inside `[0.51/faceRes, 1 - 0.51/faceRes]` so linear comparison and 3×3 PCF taps never sample across tile boundaries. -- **Portable WGSL and `textureSampleCompareLevel`**: `SpotShadowWGSL` and `PointShadowWGSL` avoid `exp`/`exp2`/`log2` completely (using algebraic windowed inverse-square attenuation and smooth cubic cone falloff) and call `textureSampleCompareLevel` so bounds checks and filter branches remain valid under WebGPU's strict uniformity analysis as well as WebGL 2, GLES 3.0, and the software renderer. -- **256-byte dynamic-offset caster uniform slots**: Both shadow maps allocate a `casterBuf` sized to `MaxCasters * 256` bytes and bind it with `HasDynamicOffset: true`. Each `DrawCaster(dev, pass, mesh, model)` writes `(lightViewProj, model)` to the next aligned slot and binds its dynamic offset before `mesh.Draw(pass)`, allowing multiple casters with distinct transforms in a single pass (or across all six point-light faces in one encoder/frame). -- **Recorder-agnostic passes and explicit live `*gpu.Device`**: `BeginShadowPass` and `BeginFacePass` accept `LocalShadowPassRecorder` (satisfied by both `*gpu.Encoder` and `*gpu.Frame`), and `Update` / `DrawCaster` accept `dev *gpu.Device` explicitly so `Retained: true` shadow maps survive device loss and restore cleanly. -- **Pure-Go CPU reference evaluators**: `EvaluateSpotShadow`, `EvaluateSpotLighting`, `PointShadowSelectFace`, `EvaluatePointShadow`, and `EvaluatePointLighting` mirror the WGSL math (including nearest vs linear depth comparison and clamped 3×3 PCF) for deterministic GPU-vs-CPU verification in `local_shadows_test.go`. +- **Portable WGSL and `textureSampleCompareLevel`**: `SpotShadowWGSL` and `PointShadowWGSL` avoid `exp`/`exp2`/`log2` and call `textureSampleCompareLevel` so bounds checks and filter branches remain valid under WebGPU's strict uniformity analysis as well as WebGL 2, GLES 3.0, and the software renderer. +- **256-byte dynamic-offset caster uniform slots**: the spot map allocates `MaxCasters` 256-byte slots and the point map `6 * MaxCasters`, one range per face, bound with `HasDynamicOffset: true`. `DrawCaster(pass, mesh, model)` writes `(lightViewProj, model)` to the next slot and returns false when the pass (or face) is full or `Update` has not run yet, as `DirectionalShadowMap.DrawCaster` does. `BeginFacePass` resets only its own face's slots, so refreshing a subset of faces, in any order, never exhausts the buffer. `MaxCasters` is capped at `MaxLocalShadowCasters` (4096) and the caster buffer is checked against the device's `MaxBufferSize`, both reported as `ErrInvalidLocalShadow`. +- **Same pass API as `DirectionalShadowMap`**: `BeginShadowPass(dev, target)` and `BeginFacePass(dev, target, face)` take the live `*gpu.Device` and a `ShadowPassTarget` (`*gpu.Encoder` or `*gpu.Frame`), so `Retained: true` maps survive device loss and restore. +- **Pure-Go CPU reference evaluators**: `EvaluateSpotShadow`, `PointShadowSelectFace` and `EvaluatePointShadow` mirror the WGSL math (including nearest vs linear depth comparison and clamped 3×3 PCF); with `ShadePointVisibility` they reproduce the GPU pixels in `local_shadows_test.go`. ## Alternatives considered @@ -34,6 +36,10 @@ A native cubemap depth texture lets hardware select faces and filter seamlessly Writing `length(worldPos - lightPos) / range` to `@builtin(frag_depth)` simplifies depth bias to a uniform world-space offset across all distances. It was rejected because writing `frag_depth` disables hardware early-Z optimization on every backend and requires fragment-shader execution during shadow passes, whereas analytic perspective NDC depth `(far/(far-near)) * (1 - near/axisDist)` matches the vertex-only hardware depth buffer exactly while keeping world-space `NormalBias` for grazing-angle acne suppression. +### Keep a separate light model (`SpotShadowLight`, `PointShadowLight`) with its own lighting helpers + +The first version shipped its own light structs and `evaluate_*_lighting` WGSL. It was rejected in review: it disagreed with the `LightRig` (no 1/π in the diffuse term, a different near-field clamp, `Range` required where the rig allows 0), its ready-made pipelines had no per-draw model matrix and a constant albedo, and it hard-coded `@group(1)`, which collides with `LightGroup`. Deriving the shadow from the rig's lights and multiplying visibility into the existing PBR loop keeps one lighting model. + ### Use one static caster uniform buffer overwritten per `DrawCaster` A single 128-byte uniform buffer avoids sizing a `MaxCasters * 256` slot buffer. It was rejected because `Device.WriteBuffer` executes before the submitted command buffer runs, so drawing two or more casters in the same shadow pass (or across six faces in one command encoder) would silently overwrite earlier casters' transforms with the last caster's matrix. @@ -42,7 +48,9 @@ A single 128-byte uniform buffer avoids sizing a `MaxCasters * 256` slot buffer. - **Benefits**: - Perspective spot-light and omnidirectional 6-face point-light shadows work identically on full GPU profiles and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0), with zero-allocation uniform encoding (`SpotShadowUniform.Encode`, `PointShadowUniform.Encode`), multi-caster dynamic offsets, `Retained` device-loss restoration, and exact `ByteSize()` budget reporting. - - Verified by `local_shadows_test.go` against both pure-Go CPU reference evaluators (`EvaluateSpotLighting`, `EvaluatePointLighting`) and golden reference PNGs (`local_shadow_spot.png`, `local_shadow_point.png`). + - Verified by `local_shadows_test.go` against the pure-Go references (`EvaluateSpotShadow`, `EvaluatePointShadow`, `ShadePointVisibility`) and golden reference PNGs (`local_shadow_spot.png`, `local_shadow_point.png`). - **Costs**: - `PointShadowMap`'s `3×2` atlas clamps PCF taps inside each tile boundary rather than filtering across cube-face seams, which can leave a subtle 1-texel softness discontinuity right along a cube diagonal edge; increasing `FaceResolution` minimizes it. - - `DrawCaster` caps draws per shadow submission at `MaxCasters` (default 256 for spot, 1024 for point) and silently skips excess draws rather than resizing GPU buffers mid-pass; callers with larger caster counts should raise `MaxCasters` in the config. + - Only the first spot light and the first point light of a rig can be shadowed by the ready-made pipelines, and both cannot be bound there at once because they share group 3; a custom shader binds both through the `ForGroup` variants. + - Face 0 clears the whole point atlas, so a partial refresh must either include face 0 with every other face or skip it. + - `DrawCaster` refuses draws past `MaxCasters` (default 256 per spot pass or per point face) and reports it by returning false rather than resizing GPU buffers mid-pass. diff --git a/changelog.d/render3d-local-shadows-255.md b/changelog.d/render3d-local-shadows-255.md index f02cee81..a47bcb08 100644 --- a/changelog.d/render3d-local-shadows-255.md +++ b/changelog.d/render3d-local-shadows-255.md @@ -1,3 +1,3 @@ ### Added -- `game/render3d`: perspective 2D spot-light shadow maps (`SpotShadowMap`, `SpotShadowConfig`, `SpotShadowLight`, `SpotShadowWGSL`, `NewSpotShadowLitPipeline`) and omnidirectional 3×2 depth-atlas point-light shadow maps (`PointShadowMap`, `PointShadowConfig`, `PointShadowLight`, `PointShadowWGSL`, `NewPointShadowLitPipeline`) with hard and 3×3 PCF filtering, normal/depth biasing, dynamic-offset multi-caster drawing, `Retained` device-loss restoration, and pure-Go CPU reference evaluators (`EvaluateSpotShadow`, `EvaluatePointShadow`) (#255). +- `game/render3d`: shadows for the first spot light and the first point light of a `LightRig` (#255). `SpotShadowMap` renders a perspective depth map and `PointShadowMap` packs the six cube faces into one 3x2 depth atlas, both updated from the rig's `SpotLight` / `PointLight`, with hard or 3x3 PCF filtering, depth and normal bias, several casters per pass, and `Retained` device-loss recovery. `LitPBRSpotShadowWGSL` / `LitPBRPointShadowWGSL` (`NewLitPBRSpotShadowPipeline`, `NewLitPBRPointShadowPipeline`, or `LitPBRPipelineOptions.SpotShadowLayout` / `PointShadowLayout`) draw lit PBR meshes with the shadow at bind group 3; `SpotShadowWGSL` / `PointShadowWGSL` and their `ForGroup` variants add the shadows to custom shaders, `shade_pbr_visibility` in `LightWGSL` and `ShadePointVisibility` scale the shadowed lights, and `EvaluateSpotShadow` / `EvaluatePointShadow` are the CPU references. diff --git a/docs/en/render3d.md b/docs/en/render3d.md index ca9f4fe4..eea8fe54 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -1,6 +1,6 @@ # render3d -`game/render3d` provides mesh buffers, textures and samplers, metallic-roughness PBR materials, directional shadow maps, camera uniforms, offscreen render-to-texture cameras and multi-viewport split-screen rendering, distance and height fog, and an HDR render target with a tone-mapping pass for the NSGo GPU view alongside the GPU-agnostic, zero-steady-state-allocation CPU 3D render pipeline and developer tools: frustum culling, opaque/transparent draw sorting, automatic instancing, LOD selection with hysteresis, camera-facing billboards and 3D ribbon trails, 3D debug wireframes and transform gizmos, frame profiling, and mobile/desktop GPU budgets. +`game/render3d` provides mesh buffers, textures and samplers, metallic-roughness PBR materials, directional, spot and point light shadow maps, camera uniforms, offscreen render-to-texture cameras and multi-viewport split-screen rendering, distance and height fog, and an HDR render target with a tone-mapping pass for the NSGo GPU view alongside the GPU-agnostic, zero-steady-state-allocation CPU 3D render pipeline and developer tools: frustum culling, opaque/transparent draw sorting, automatic instancing, LOD selection with hysteresis, camera-facing billboards and 3D ribbon trails, 3D debug wireframes and transform gizmos, frame profiling, and mobile/desktop GPU budgets. ```go import "github.com/nsgo-dev/game/packages/game/render3d" @@ -378,7 +378,7 @@ Three pipelines draw a `GPUSkinnedMesh`, each binding the palette at its own gro | Pipeline | Shader | Palette group | Not combinable with | | --- | --- | --- | --- | | `NewSkinnedMeshPipeline` (unlit, colored by normal) | `SkinnedMeshWGSL` | `SkinGroup` (1) | | -| `NewLitPBRPipelineWithOptions` with `LitPBRPipelineOptions.SkinLayout` (scene lights) | `LitPBRSkinnedWGSL` | `LitPBRSkinGroup` (3) | `FogLayout`, `IBLLayout`, `ShadowLayout` | +| `NewLitPBRPipelineWithOptions` with `LitPBRPipelineOptions.SkinLayout` (scene lights) | `LitPBRSkinnedWGSL` | `LitPBRSkinGroup` (3) | `FogLayout`, `IBLLayout`, `ShadowLayout`, `SpotShadowLayout`, `PointShadowLayout` | | `NewMaterialPipeline` with `MaterialPipelineOptions.SkinLayout` (glTF material with textures) | `MaterialSkinnedWGSL` | `MaterialSkinGroup` (2) | `FogLayout` | `SkinWGSL` declares the uniform block at group 1 and the portable `skin_position` / `skin_normal` vertex helpers matching CPU `SkinVertex`, for custom shaders that bind nothing else at group 1. @@ -1095,41 +1095,46 @@ _ = renderer.Draw(pass, camBuf, lmMesh, worldMat, mat) ## Point and spot light shadows (`SpotShadowMap`, `PointShadowMap`) -`SpotShadowMap` and `PointShadowMap` render depth-only `FormatDepth32Float` shadow maps for local lights and expose them alongside comparison samplers and WGSL helpers (`SpotShadowWGSL`, `PointShadowWGSL`) that run portably across Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software GPU renderer (`nsgotest.NoGPUCompute` included): - -- **Spot light shadows (`SpotShadowMap`)**: builds a square `[0, 1]`-depth perspective projection matching `SpotShadowLight.Position`, `Direction`, `OuterConeAngle` (`fovY = 2 * OuterConeAngle`), `Near`, and `Range`. `BeginShadowPass` clears depth and binds the depth-only caster pipeline; `DrawCaster` writes each caster's `(lightViewProj, model)` transform into a 256-byte dynamic-offset uniform slot so any number of casters (up to `MaxCasters`) draw in one pass without overwriting earlier transforms. -- **Omnidirectional point light shadows (`PointShadowMap`)**: packs all six 90° cube faces (`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`) into a single `3×2` `FormatDepth32Float` 2D depth atlas of size `(3 * FaceResolution) × (2 * FaceResolution)`. Calling `BeginFacePass(rec, face)` for `face` `0..5` clears the atlas on face 0, preserves earlier tiles on faces 1..5 (`LoadLoad`), and locks viewport and scissor to each face's tile. In `PointShadowWGSL`, `sample_point_shadow` selects the dominant cube face, computes analytic perspective NDC depth `(far/(far-near))*(1 - near/axisDist)` without uploading six matrices to the fragment shader, and clamps every tap inside `[0.51/faceRes, 1 - 0.51/faceRes]` so 3×3 PCF never bleeds across adjacent atlas tiles. -- **Filtering, biasing, and ready-made pipelines**: choose `LocalShadowFilterHard` (single nearest comparison tap) or `LocalShadowFilterPCF3x3` (9 linear comparison taps) with configurable `DepthBias` and `NormalBias`. `BeginShadowPass` and `BeginFacePass` accept both `*gpu.Encoder` and `*gpu.Frame` (`LocalShadowPassRecorder`). Use `NewSpotShadowLitPipeline` or `NewPointShadowLitPipeline` for quick shadowed lighting with `CameraGroup` (0) and `LocalShadowGroup` (1), or prepend `CameraWGSL` + `SpotShadowWGSL` / `PointShadowWGSL` to custom fragment shaders. -- **Device-loss recovery and CPU reference**: setting `Retained: true` recreates the depth render target, comparison sampler, uniform buffers, bind groups, and depth pipeline automatically after a device loss (`Update` and `DrawCaster` take the live `*gpu.Device` explicitly). Pure-Go evaluators `EvaluateSpotShadow`, `EvaluateSpotLighting`, `PointShadowSelectFace`, `EvaluatePointShadow`, and `EvaluatePointLighting` mirror the WGSL shaders for analytic verification, alongside golden reference renders `render3d/testdata/golden/local_shadow_spot.png` and `local_shadow_point.png` (`UPDATE_GOLDEN=1` rewrites them). +`SpotShadowMap` and `PointShadowMap` shadow the first spot light (`rig.Spot[0]`) and the first point light (`rig.Point[0]`) of a `LightRig`. They render depth-only `FormatDepth32Float` maps from the rig's own `SpotLight` and `PointLight`, and the lit PBR pipelines multiply that light's contribution by the shadow, so a shadowed light is shaded exactly like the same light in `LitPBRWGSL` (Cook-Torrance GGX, energy-conserving Lambert, `PointLightAttenuation`, glTF cone falloff). Everything runs on every NSGo backend, the WebGL 2 / OpenGL ES 3.0 profile (`nsgotest.NoGPUCompute`) and the software renderer included: ```go spot, err := render3d.NewSpotShadowMap(cx, dev, render3d.DefaultSpotShadowConfig()) -litPipe, err := render3d.NewSpotShadowLitPipeline(cx, dev, camBuf.Layout(), spot.Layout(), render3d.LocalShadowLitPipelineOptions{ - DepthFormat: gpu.FormatDepth24Plus, - CullMode: gpu.CullBack, -}) +litPipe, err := render3d.NewLitPBRSpotShadowPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBufs[0].Layout(), spot.Layout(), gpu.FormatDepth24Plus) // Each frame in OnFrame: -_ = spot.Update(dev, spotLight) -sp := spot.BeginShadowPass(frame) -spot.DrawCaster(dev, sp, pillarMesh, pillarModel) -sp.End() +_ = spot.Update(dev, rig.Spot[0]) // the light the shadow attenuates +if sp := spot.BeginShadowPass(dev, frame); sp != nil { + spot.DrawCaster(sp, pillarMesh, pillarModel) // false when the pass is full + sp.End() +} -mp := frame.BeginRenderPass(gpu.RenderPassDesc{}) +mp := frame.BeginRenderPass(gpu.RenderPassDesc{ /* color + depth */ }) mp.SetPipeline(litPipe) mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) +mp.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) mp.SetBindGroup(render3d.LocalShadowGroup, spot.BindGroup()) -sceneMesh.Draw(mp) +for i, mesh := range meshes { + mp.SetBindGroup(render3d.PBRDrawGroup, drawBufs[i].BindGroup()) // per-draw model matrix and material + mesh.Draw(mp) +} mp.End() ``` -For an omnidirectional point light, loop `face` from `0` to `render3d.PointShadowFaceCount-1`: +For a point light, update from `rig.Point[0]`, draw with `NewLitPBRPointShadowPipeline`, and render the cube faces: ```go -_ = point.Update(dev, pointLight) +_ = point.Update(dev, rig.Point[0]) for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { - fp := point.BeginFacePass(frame, face) - point.DrawCaster(dev, fp, blockerMesh, blockerModel) - fp.End() + if fp := point.BeginFacePass(dev, frame, face); fp != nil { + point.DrawCaster(fp, blockerMesh, blockerModel) + fp.End() + } } ``` + +- **Spot projection**: a square `[0, 1]`-depth perspective from the light's `Position` along its `Direction` with a field of view of `2 * OuterConeAngle` (`SpotShadowViewProj`). The far plane is the light's `Range`, or `SpotShadowConfig.Far` (default `DefaultLocalShadowFar`, 50) for a light with `Range` 0; `Near` defaults to 0.1. A cone wider than `MaxSpotShadowConeAngle` (just under 90°) cannot be projected and `Update` returns `ErrInvalidLocalShadow`. +- **Point atlas**: the six 90° cube faces are packed into one `(3 * FaceResolution) × (2 * FaceResolution)` 2D depth atlas, because NSGo cannot attach a single face of a depth cube map. `sample_point_shadow` picks the dominant face, computes the perspective depth `(far/(far-near)) * (1 - near/axisDist)` directly, and clamps every tap inside its tile so 3×3 PCF never bleeds into a neighboring face. `BeginFacePass` with face 0 clears the whole atlas and faces 1..5 keep what is there, so a partial refresh either includes face 0 with every other face or skips it. +- **Casters**: `DrawCaster` writes each caster's `(lightViewProj, model)` into its own 256-byte dynamic-offset slot, so many casters draw in one pass. `MaxCasters` (default 256, at most `MaxLocalShadowCasters`) applies per spot pass and per point face; each face has its own slots, so faces can be refreshed in any order. `DrawCaster` returns false when the pass or face is full or `Update` has not run yet. +- **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). diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 16986e1f..00a4c97a 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -1,6 +1,6 @@ # render3d -`game/render3d` 提供 NSGo GPU 视图的网格缓冲、纹理与采样器、金属度-粗糙度 PBR 材质、方向光阴影贴图、相机 uniform、离屏渲染到纹理相机与多视口分屏渲染、距离雾与高度雾,以及 HDR 渲染目标与色调映射 pass,以及与后端无关、稳态零分配的 CPU 侧 3D 渲染管线与开发工具:视锥体裁剪、不透明/半透明绘制排序、自动实例化合批、带滞回防抖动的 LOD 选择、面向相机的公告板与 3D 条带拖尾、3D 调试线框与变换手柄(Gizmo)、帧性能分析器,以及移动端/桌面端 GPU 预算检查。 +`game/render3d` 提供 NSGo GPU 视图的网格缓冲、纹理与采样器、金属度-粗糙度 PBR 材质、方向光、聚光灯与点光源阴影贴图、相机 uniform、离屏渲染到纹理相机与多视口分屏渲染、距离雾与高度雾,以及 HDR 渲染目标与色调映射 pass,以及与后端无关、稳态零分配的 CPU 侧 3D 渲染管线与开发工具:视锥体裁剪、不透明/半透明绘制排序、自动实例化合批、带滞回防抖动的 LOD 选择、面向相机的公告板与 3D 条带拖尾、3D 调试线框与变换手柄(Gizmo)、帧性能分析器,以及移动端/桌面端 GPU 预算检查。 ```go import "github.com/nsgo-dev/game/packages/game/render3d" @@ -378,7 +378,7 @@ morph.Draw(pass) | 管线 | 着色器 | 骨骼矩阵组 | 不能同时使用 | | --- | --- | --- | --- | | `NewSkinnedMeshPipeline`(无光照,按法线着色) | `SkinnedMeshWGSL` | `SkinGroup`(1) | | -| `NewLitPBRPipelineWithOptions` 加 `LitPBRPipelineOptions.SkinLayout`(场景光源) | `LitPBRSkinnedWGSL` | `LitPBRSkinGroup`(3) | `FogLayout`、`IBLLayout`、`ShadowLayout` | +| `NewLitPBRPipelineWithOptions` 加 `LitPBRPipelineOptions.SkinLayout`(场景光源) | `LitPBRSkinnedWGSL` | `LitPBRSkinGroup`(3) | `FogLayout`、`IBLLayout`、`ShadowLayout`、`SpotShadowLayout`、`PointShadowLayout` | | `NewMaterialPipeline` 加 `MaterialPipelineOptions.SkinLayout`(带纹理的 glTF 材质) | `MaterialSkinnedWGSL` | `MaterialSkinGroup`(2) | `FogLayout` | `SkinWGSL` 在第 1 组声明 uniform 数据块,以及与 CPU `SkinVertex` 一致的 `skin_position` / `skin_normal` 顶点辅助函数,供第 1 组不绑定其他资源的自定义着色器使用。 @@ -1095,41 +1095,46 @@ _ = renderer.Draw(pass, camBuf, lmMesh, worldMat, mat) ## 点光源与聚光灯阴影(`SpotShadowMap`、`PointShadowMap`) -`SpotShadowMap` 与 `PointShadowMap` 为局部光源渲染纯深度 `FormatDepth32Float` 阴影贴图,并提供比较采样器与可移植 WGSL 辅助代码(`SpotShadowWGSL`、`PointShadowWGSL`),可在 Metal、Direct3D 11、OpenGL 3.3、WebGPU、WebGL 2、OpenGL ES 3.0 及软件 GPU 渲染器(包括 `nsgotest.NoGPUCompute`)上一致运行: - -- **聚光灯阴影(`SpotShadowMap`)**:根据 `SpotShadowLight.Position`、`Direction`、`OuterConeAngle`(`fovY = 2 * OuterConeAngle`)、`Near` 与 `Range` 构建正方形 `[0, 1]` 深度透视投影。`BeginShadowPass` 清除深度并绑定纯深度投射管线;`DrawCaster` 将每个投射体的 `(lightViewProj, model)` 写入 256 字节对齐的动态偏移 uniform 槽位,使单次通道内可连续绘制多个投射体(上限 `MaxCasters`)而不互相覆盖。 -- **全向点光源阴影(`PointShadowMap`)**:将 6 个 90° 立方体贴图面(`gpu.CubeFacePosX`..`gpu.CubeFaceNegZ`)打包进一张尺寸为 `(3 * FaceResolution) × (2 * FaceResolution)` 的 `3×2` `FormatDepth32Float` 2D 深度图集。对 `face` `0..5` 调用 `BeginFacePass(rec, face)` 时,第 0 面清除整个图集,第 1..5 面通过 `LoadLoad` 保留已渲染的瓦片,并将视口与裁剪矩形严格锁定到当前面瓦片内。在 `PointShadowWGSL` 中,`sample_point_shadow` 选取主轴方向面,以解析公式 `(far/(far-near))*(1 - near/axisDist)` 计算透视 NDC 深度(无需向片元着色器上传 6 个矩阵),并将每次采样钳制在 `[0.51/faceRes, 1 - 0.51/faceRes]` 内,确保 3×3 PCF 不会跨瓦片渗色。 -- **滤波、偏移与开箱即用管线**:支持 `LocalShadowFilterHard`(单次最近邻比较采样)与 `LocalShadowFilterPCF3x3`(9 次线性比较采样),并可配置 `DepthBias` 与 `NormalBias`。`BeginShadowPass` 与 `BeginFacePass` 同时接受 `*gpu.Encoder` 与 `*gpu.Frame`(`LocalShadowPassRecorder`)。可直接用 `NewSpotShadowLitPipeline` / `NewPointShadowLitPipeline` 搭配 `CameraGroup`(0)和 `LocalShadowGroup`(1)渲染带阴影光照,或在自定义片元着色器前拼接 `CameraWGSL` 与 `SpotShadowWGSL` / `PointShadowWGSL`。 -- **设备丢失恢复与 CPU 参考实现**:开启 `Retained: true` 后,设备丢失恢复时 NSGo 会自动重建深度渲染目标、比较采样器、uniform 缓冲、绑定组与深度管线(`Update` 与 `DrawCaster` 显式接收存活的 `*gpu.Device`)。纯 Go 评估函数 `EvaluateSpotShadow`、`EvaluateSpotLighting`、`PointShadowSelectFace`、`EvaluatePointShadow` 与 `EvaluatePointLighting` 与 WGSL 着色器逐项对应,便于解析校验,并附带参考渲染图 `render3d/testdata/golden/local_shadow_spot.png` 与 `local_shadow_point.png`(`UPDATE_GOLDEN=1` 可重写)。 +`SpotShadowMap` 与 `PointShadowMap` 为 `LightRig` 的第一盏聚光灯(`rig.Spot[0]`)和第一盏点光源(`rig.Point[0]`)生成阴影。它们根据光照组自身的 `SpotLight` 与 `PointLight` 渲染纯深度 `FormatDepth32Float` 阴影贴图,带阴影的 PBR 管线再把该光源的贡献乘以阴影可见度,因此带阴影的光源与 `LitPBRWGSL` 中同一光源的着色完全一致(Cook-Torrance GGX、能量守恒的 Lambert、`PointLightAttenuation`、glTF 锥角衰减)。所有功能在每个 NSGo 后端上都能运行,包括 WebGL 2 / OpenGL ES 3.0 配置(`nsgotest.NoGPUCompute`)与软件渲染器: ```go spot, err := render3d.NewSpotShadowMap(cx, dev, render3d.DefaultSpotShadowConfig()) -litPipe, err := render3d.NewSpotShadowLitPipeline(cx, dev, camBuf.Layout(), spot.Layout(), render3d.LocalShadowLitPipelineOptions{ - DepthFormat: gpu.FormatDepth24Plus, - CullMode: gpu.CullBack, -}) +litPipe, err := render3d.NewLitPBRSpotShadowPipeline(cx, dev, camBuf.Layout(), lightBuf.Layout(), drawBufs[0].Layout(), spot.Layout(), gpu.FormatDepth24Plus) // 每帧在 OnFrame 中: -_ = spot.Update(dev, spotLight) -sp := spot.BeginShadowPass(frame) -spot.DrawCaster(dev, sp, pillarMesh, pillarModel) -sp.End() +_ = spot.Update(dev, rig.Spot[0]) // 阴影作用的光源 +if sp := spot.BeginShadowPass(dev, frame); sp != nil { + spot.DrawCaster(sp, pillarMesh, pillarModel) // 通道已满时返回 false + sp.End() +} -mp := frame.BeginRenderPass(gpu.RenderPassDesc{}) +mp := frame.BeginRenderPass(gpu.RenderPassDesc{ /* 颜色 + 深度 */ }) mp.SetPipeline(litPipe) mp.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup()) +mp.SetBindGroup(render3d.LightGroup, lightBuf.BindGroup()) mp.SetBindGroup(render3d.LocalShadowGroup, spot.BindGroup()) -sceneMesh.Draw(mp) +for i, mesh := range meshes { + mp.SetBindGroup(render3d.PBRDrawGroup, drawBufs[i].BindGroup()) // 每次绘制的模型矩阵与材质 + mesh.Draw(mp) +} mp.End() ``` -对于全向点光源,遍历 `face` 从 `0` 到 `render3d.PointShadowFaceCount-1`: +点光源则用 `rig.Point[0]` 更新,用 `NewLitPBRPointShadowPipeline` 绘制,并渲染各个立方体面: ```go -_ = point.Update(dev, pointLight) +_ = point.Update(dev, rig.Point[0]) for face := range gpu.CubeFace(render3d.PointShadowFaceCount) { - fp := point.BeginFacePass(frame, face) - point.DrawCaster(dev, fp, blockerMesh, blockerModel) - fp.End() + if fp := point.BeginFacePass(dev, frame, face); fp != nil { + point.DrawCaster(fp, blockerMesh, blockerModel) + fp.End() + } } ``` + +- **聚光灯投影**:从光源 `Position` 沿 `Direction` 看出的正方形 `[0, 1]` 深度透视投影,视场角为 `2 * OuterConeAngle`(`SpotShadowViewProj`)。远平面取光源的 `Range`;`Range` 为 0 的光源取 `SpotShadowConfig.Far`(默认 `DefaultLocalShadowFar`,即 50);`Near` 默认为 0.1。锥角超过 `MaxSpotShadowConeAngle`(略小于 90°)时无法投影,`Update` 返回 `ErrInvalidLocalShadow`。 +- **点光源图集**:6 个 90° 立方体面打包进一张 `(3 * FaceResolution) × (2 * FaceResolution)` 的 2D 深度图集,因为 NSGo 无法把深度立方体贴图的单个面作为附件。`sample_point_shadow` 选取主轴方向的面,直接计算透视深度 `(far/(far-near)) * (1 - near/axisDist)`,并把每次采样钳制在所属瓦片内,使 3×3 PCF 不会渗入相邻面。`BeginFacePass` 渲染第 0 面时清除整个图集,第 1..5 面保留已有内容,因此只刷新部分面时,要么连同其他所有面一起刷新第 0 面,要么不刷新第 0 面。 +- **投射体**:`DrawCaster` 把每个投射体的 `(lightViewProj, model)` 写入各自的 256 字节动态偏移槽位,因此一个通道可以绘制多个投射体。`MaxCasters`(默认 256,最大 `MaxLocalShadowCasters`)对聚光灯按每个通道计算,对点光源按每个面计算;每个面有自己的槽位,因此各面可以按任意顺序刷新。通道或面已满、或尚未调用 `Update` 时,`DrawCaster` 返回 false。 +- **滤波与偏移**:`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` 可重写)进行比较。 diff --git a/packages/game/render3d/doc.go b/packages/game/render3d/doc.go index 17e22cd7..0568a0c5 100644 --- a/packages/game/render3d/doc.go +++ b/packages/game/render3d/doc.go @@ -66,6 +66,8 @@ // // [GPUFogBuffer] (#254) keeps a [Fog] (linear, exponential or exponential-squared distance fog, analytical exponential height fog, or both) in a uniform buffer. [NewLitPBRFogPipeline] draws [LitPBRWGSL]'s lighting with fog with the buffer at [FogGroup], and [NewMaterialPipeline] does the same for materials when [MaterialPipelineOptions].FogLayout is set, with the buffer at [MaterialFogGroup]. [FogWGSL] holds the shader functions for custom shaders, and [Fog.Apply] with [FogCameraPos] is the matching CPU reference. // +// [SpotShadowMap] and [PointShadowMap] (#255) shadow the first spot light and the first point light of a [LightRig]: a perspective depth map for the spot cone and a 3x2 depth atlas holding the six cube faces of the point light, updated from the rig's [SpotLight] and [PointLight]. [NewLitPBRSpotShadowPipeline] and [NewLitPBRPointShadowPipeline] draw [LitPBRWGSL]'s lighting with the map bound at [LocalShadowGroup]; [SpotShadowWGSL] and [PointShadowWGSL] (or [SpotShadowWGSLForGroup] and [PointShadowWGSLForGroup] at another group) add the shadow to custom shaders, and [EvaluateSpotShadow], [EvaluatePointShadow] and [ShadePointVisibility] are the matching CPU references. +// // [SkyboxPipeline] (#253) draws a [GPUCubemap] as a background behind opaque geometry, and [GPUIBLBuffer] holds an environment's [IrradianceSH] diffuse irradiance and [PrefilterEnvironment] specular cubemap for image-based lighting. [NewLitPBRIBLPipeline] adds that lighting to [LitPBRWGSL]'s with the buffer at [IBLGroup], [IBLWGSL] holds the shader functions for custom shaders, and [EvaluateIBL] is the matching CPU reference. // // The CPU culling, LOD, sorting, instancing, gizmo, debug, statistics, and budget pipeline stays deterministic, pure Go, and independent of the GPU view, so it runs the same in headless tests and servers; the camera, light, mesh, texture, and sampler helpers are the parts that talk to [gpu.Device].