Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Agent Note: Clustered Forward Lighting in render3d

Status: implemented

## Problem

`render3d` needs to render scenes with hundreds of local point and spot lights without leaving forward rendering, and without breaking mobile and browser targets (WebGL 2 / OpenGL ES 3.0) that lack compute shaders and storage buffers (`Features.Compute == false`, `Features.StorageBuffers == false`, simulated in tests via `nsgotest.NoGPUCompute`).

The scene lighting model already exists: `light.go` defines `LightRig` (ambient, up to 4 directional, 16 point and 8 spot lights) at `LightGroup` binding 0, the Cook-Torrance `pbr_brdf`, `point_light_attenuation`, `spot_cone_attenuation`, `shade_pbr`, and `LitPBRWGSL` with sRGB output. Clustered lights must combine with that rig in one shader and look identical to rig lights, not introduce a second shading model or a second binding at `@group(1) @binding(0)`.

Constraints:

- NSGo v0.3.0's software GPU VM (headless `nsgotest`, `gpu.NewSoftwareRenderer`) has no case for `log`, `log2`, `exp` or `exp2` in `evalCall` (`internal/driver/gpu_software.go`) and silently returns zero, so the textbook `floor(log2(z / near) * scale)` slice formula would shade every fragment from slice 0 in software tests. Upstream main still lacks them.
- WebGL 2 and OpenGL ES 3.0 disallow storage buffers, so the system must fall back to uniform buffers when `DeviceSupportsClusteredLighting(dev)` is false.
- Retained GPU resources survive device loss by retargeting buffers; holding a stale `*gpu.Device` breaks updates after `RestoreGPUDevice`.

## Decision

`packages/game/render3d/clustered.go` makes `ClusteredLightSystem` own the whole `LightGroup` bind group:

- **One light group, one shading model**: binding 0 is the `LightRig` uniform `LightWGSL` declares, encoded with `packLightUniforms` / `LightUniforms.Encode`; binding 1 is the cluster parameters (clustered) or the fallback light array (fallback); bindings 2 to 4 are the light, cell and index storage buffers. `ClusteredBindingsWGSL` and `ClusteredFallbackBindingsWGSL` are `LightWGSL` plus those bindings and `shade_pbr_clustered`, which returns `shade_pbr` plus each local light through `pbr_brdf`, `point_light_attenuation` and `spot_cone_attenuation`. `ClusteredLitWGSL` / `ClusteredFallbackWGSL` are `LitPBRWGSL` with `shade_pbr_clustered`, writing `linear_to_srgb`, and `NewClusteredLitPBRPipeline` builds them with `newLitPBRPipeline`. `Bind(pass)` matches `GPULightBuffer.Bind`.
- **Lights from the existing types**: `ClusterLight` stays as the packed record the grid bins, but `ClusterLightFromPoint` / `ClusterLightFromSpot` build it from `PointLight` / `SpotLight`, and `EvaluateLightAttenuation` reuses `PointLightAttenuation` and `SpotConeAttenuation` (with the same `minSpotConeCosDelta`). Clustering needs a bounding sphere, so `Range` must be positive: the converters derive one for `Range == 0` (where `Intensity * max(Color) / d^2` falls to `ClusterRangeCutoff`, 1/256), and `Update` returns an error for an invalid light instead of dropping it.
- **Zero-allocation CPU clustering (`ClusterGrid`)**: logarithmic depth splits for perspective, linear for orthographic, cluster AABBs cached by `(proj, near, far)`, conservative tile and slice bounds, sphere-vs-AABB plus cone rejection for spot lights, and packed offsets and indices with no steady-state allocations. Overflow past `MaxLights` or `MaxLightsPerCluster` drops lights in input order and is reported in the stats.
- **Binary-search depth slicing in WGSL**: up to 65 slice boundaries in a 17 × `vec4<f32>` uniform table and a fixed 6-step binary search, instead of `log2` / `exp`.
- **Fallback selection**: `SelectFallbackLights` frustum-culls light bounding spheres before ranking, so off-screen lights never take one of the 16 uniform slots, and sorts with `slices.SortFunc` so the per-frame path allocates nothing.
- **Bounded sizes**: `Validate` caps `MaxLights` (65,536), `MaxLightsPerCluster <= MaxLights`, and index slots (`MaxClusterIndexEntries`); `NewClusteredLightSystem` refuses a storage buffer larger than the device's binding limit instead of clamping it.
- **Explicit `*gpu.Device` on `Update` / `UpdateCamera`**, as `GPUTexture` and `GPUMorphMesh` do.

## Alternatives considered

### Clustered bindings next to a separate `GPULightBuffer`

Keeping `GPULightBuffer` at group 1 and putting the cluster buffers in another group would avoid touching the rig upload, but group 2 is `PBRDrawGroup` and group 3 is a custom material's extra layout, so the clustered pass would need a fourth group that WebGL 2 pipelines with materials cannot spare. One bind group with the rig at binding 0 keeps `LightWGSL` unchanged and fits every existing pipeline layout.

### A Lambert-only clustered shader

The first version shaded clustered lights with `color * intensity * atten * ndotl` and wrote linear color. It was simpler, but a scene mixing it with `LitPBRWGSL` would be darker and inconsistent, and it duplicated the attenuation math. Reusing `pbr_brdf` costs a few more ALU operations per light and keeps one shading model.

### Compute-shader light assignment on the GPU

Assigning lights in a compute pass avoids uploading cell and index buffers, but the software GPU runs compute workgroups sequentially, native backends need atomic append counters, and capability-limited targets still need a CPU path. `ClusterGrid.AssignLights` handles 256 lights with no allocations (`BenchmarkClusterAssign256Lights`).

### `log2(view_z / near)` slice indexing in WGSL

It would save 272 bytes of uniforms, but NSGo's software VM evaluates `log2` to zero, and a split table also covers orthographic slicing.

### Packing light lists into textures for WebGL 2

Emulating storage buffers with integer textures needs `Features.ExtendedFormats` and costs texture fetches per light on mobile tile GPUs. A 16-light uniform fallback uses only core WebGL 2 / GLES 3.0 features.

## Consequences

- **Benefits**: clustered and rig lights share one BRDF, one attenuation curve and one sRGB output; GPU pixels match `ShadeClusteredPoint` / `ShadeClusteredGridPoint` on the full and `NoGPUCompute` profiles, including a 256-light scene; glTF lights with no range work through the converters.
- **Costs**: cluster assignment runs on the CPU and uploads cell and index buffers each frame. The shader-side cost of 256 lights at desktop resolution on native GPUs has not been measured here; only the software renderer and the CPU benchmark run in CI. Depth slices are capped at 64 and fallback lights at 16. The tile lookup assumes the viewport starts at the attachment origin, so callers pass `DynamicResolutionTarget.ScaledSize()` under dynamic resolution.
3 changes: 3 additions & 0 deletions changelog.d/render3d-clustered-forward-382.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- `game/render3d`: clustered forward shading for hundreds of point and spot lights. `ClusteredLightSystem` takes a `GPULightBuffer`'s place at `LightGroup`, uploads the same `LightRig` and adds `ClusterLight`s (`ClusterLightFromPoint`, `ClusterLightFromSpot`) binned by `ClusterGrid`, shaded with the same PBR BRDF through `NewClusteredLitPBRPipeline` / `ClusteredLitWGSL` or `shade_pbr_clustered` in custom shaders. On WebGL 2 and OpenGL ES 3.0 it falls back to the 16 most important visible lights in a uniform buffer (#382).
41 changes: 41 additions & 0 deletions docs/en/render3d.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ mesh.Draw(pass)

Custom 3D shaders can prepend `CameraWGSL + LightWGSL` to read `@group(1) @binding(0) var<uniform> lights: LightRigUniform` and call the portable WGSL helpers `point_light_attenuation`, `spot_cone_attenuation`, `pbr_brdf`, `shade_pbr`, and `linear_to_srgb`. `LitPBRWGSL` combines them with `MeshVertexLayout` and a per-draw `PBRDrawUniform` at `PBRDrawGroup` (group 2).

For more local lights than the rig holds, bind a `ClusteredLightSystem` at `LightGroup` instead of a `GPULightBuffer`: it uploads the same rig and adds any number of clustered point and spot lights, shaded with the same BRDF ([Clustered forward lighting](#clustered-forward-lighting-clusteredlightsystem-clustergrid)).

The shading model follows glTF 2.0 metallic-roughness PBR (dielectric `F0 = 0.04`, Schlick Fresnel, Trowbridge-Reitz GGX normal distribution, height-correlated Smith-GGX visibility, energy-conserving Lambertian diffuse, perceptual roughness floored at `0.045`, and IEC 61966-2-1 linear-to-sRGB output). `EvaluatePBR`, `ShadePoint`, `PointLightAttenuation`, `SpotConeAttenuation`, and `LinearToSRGB` implement the exact same equations on the CPU; `LightRig.AppendUniformData` and `LightUniforms.Encode` pack the uniform block without allocating. Reference tests verify GPU output pixel-for-pixel against CPU `ShadePoint`, exercise both full and WebGL 2 / GLES 3.0 (`nsgotest.NoGPUCompute`) profiles plus `Retained` device loss, and compare lit scenes against `render3d/testdata/golden/lights_pbr_scene.png`, `lights_point_falloff.png` and `spot_lights_scene.png`.

## Distance and height fog (`Fog`, `GPUFogBuffer`)
Expand Down Expand Up @@ -1177,3 +1179,42 @@ _ = stack.SetCamera(cam)
- **Depth of Field (`DepthOfFieldConfig`, `DepthOfFieldPass`)**: linearizes perspective or orthographic `[0, 1]` depth to compute a signed Circle of Confusion around `FocusDistance` ± `FocusRange`, then gathers an 18-tap two-ring disc bokeh blur that prevents blurred background pixels from bleeding across sharp in-focus silhouettes.
- **Bloom (`BloomConfig`, `BloomPass`)**: extracts bright LDR or HDR (`> 1.0`) pixels with a quadratic `Threshold` / `SoftKnee` curve, runs `BlurPasses` separable 9-tap Gaussian horizontal and vertical passes (optionally at half resolution via `HalfRes`), and composites the glow additively with `Intensity`.
- **Portability, lifecycle, and reference renders**: every pass uses fragment-only portable WGSL with explicit `textureSampleLevel` and algebraic/precomputed weights (no compute shaders or `exp`/`log2` instructions), running on both full and `nsgotest.NoGPUCompute` (WebGL 2 / OpenGL ES 3.0) profiles, supporting `Resize(dev, w, h)` and `Retained` device-loss recovery. Golden reference renders (`render3d/testdata/golden/post3d_bloom.png`, `post3d_ssao.png`, `post3d_dof.png`, and `post3d_combined.png`) verify each pass and the combined stack; `UPDATE_GOLDEN=1` rewrites them.

## Clustered forward lighting (`ClusteredLightSystem`, `ClusterGrid`)

A `LightRig` shades at most 16 point and 8 spot lights. For scenes with hundreds of local lights, `ClusteredLightSystem` takes the place of `GPULightBuffer` at `LightGroup`: it uploads the same `LightRig` (ambient, directional, and the rig's own point and spot lights) at binding 0, and bins any number of extra local lights (`ClusterLight`) into a 3D grid of screen tiles × logarithmic depth slices (default `16 × 9 × 24`, up to `512` visible lights and `64` per cluster). Each fragment then shades only the lights in its own cluster, with the same Cook-Torrance BRDF and glTF `KHR_lights_punctual` falloff as `shade_pbr`, so clustered and rig lights look identical. On targets without storage buffers or compute shaders (WebGL 2, OpenGL ES 3.0, and headless tests using `nsgotest.NoGPUCompute`) it falls back to one uniform buffer holding the `FallbackMaxLights` (default `16`) most important visible lights:

```go
sys, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig())
pipe, err := render3d.NewClusteredLitPBRPipeline(cx, dev, camBuf.Layout(), sys, drawBuf.Layout(), gpu.FormatDepth24Plus)

// Convert scene lights once; a Range of 0 (unbounded) gets a derived cutoff range.
local := make([]render3d.ClusterLight, 0, len(lamps))
for _, l := range lamps {
cl, err := render3d.ClusterLightFromPoint(l)
if err != nil {
return err
}
local = append(local, cl)
}

// Each frame, before recording draws:
camBuf.WriteCamera(cam)
stats, err := sys.UpdateCamera(frame.Device(), cam, viewW, viewH, rig, local)

pass.SetPipeline(pipe)
pass.SetBindGroup(render3d.CameraGroup, camBuf.BindGroup())
sys.Bind(pass)
pass.SetBindGroup(render3d.PBRDrawGroup, drawBuf.BindGroup())
mesh.Draw(pass)
```

- **Lights**: `ClusterLight` is a point or spot record whose `Range` must be positive, because clustering needs a bounding sphere. `ClusterLightFromPoint` and `ClusterLightFromSpot` convert a `PointLight` or `SpotLight` and, for `Range == 0`, derive the distance at which `Intensity * max(Color) / d^2` falls to `ClusterRangeCutoff` (1/256). `Update` returns an error wrapping `ErrInvalidClusterLight` for a light that fails `Validate` (including `Range == 0`) or `ErrInvalidLight` for a malformed rig, instead of dropping it. `EvaluateLightAttenuation` reuses `PointLightAttenuation` and `SpotConeAttenuation`.
- **Viewport size**: `viewW` and `viewH` must be the size of the area the pass renders, starting at its origin, because the shader finds a fragment's tile from `@builtin(position)`. Under a `DynamicResolutionTarget`, pass `ScaledSize()`, not the native size.
- **Shaders**: `NewClusteredLitPBRPipeline` compiles `ClusteredLitWGSL` or `ClusteredFallbackWGSL` (whichever matches `sys.WGSL()`), the `LitPBRWGSL` module with `shade_pbr_clustered` in place of `shade_pbr`, writing sRGB. Custom shaders prepend `CameraWGSL` and `sys.BindingsWGSL()` (`ClusteredBindingsWGSL` or `ClusteredFallbackBindingsWGSL`, both of which include `LightWGSL`) and call `shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos)`, which has the same signature on both paths.
- **CPU clustering (`ClusterGrid`)**: view-space cluster AABBs are cached by `(proj, near, far)` and reused across camera motion. `AssignLights` culls off-frustum lights, computes tight screen-tile and depth-slice bounds, tests sphere-vs-AABB (plus conservative cone-vs-AABB rejection for spot lights), and packs `Offsets` and `LightIndices` with zero steady-state allocations. Lights beyond `MaxLights`, and lights beyond `MaxLightsPerCluster` in one cell, are dropped in input order (`TruncatedLights`, `TruncatedClusters`), so put important lights first when a scene can exceed either cap.
- **Fallback selection**: `SelectFallbackLights` drops lights whose bounding sphere is outside the view frustum, then ranks the rest by power, range and distance to the camera. In fallback mode `CulledLights` counts lights outside the frustum or without power, and `TruncatedLights` the visible lights the cap left out.
- **Depth-slice lookup**: the shader finds a fragment's depth slice with a 6-step binary search over a uniform split-depth table rather than `log2` and `exp`, because NSGo v0.3.0's software GPU renderer evaluates those builtins to zero.
- **CPU reference**: `ShadeClusteredPoint` is `ShadePoint` plus every clustered light, and `ShadeClusteredGridPoint` uses only the lights of the fragment's cluster, exactly as the GPU does. Tests compare GPU pixels against them on the full and `NoGPUCompute` profiles, including a 256-light scene.
- **Limits**: `Validate` caps `MaxLights` at `MaxClusterLights` (65,536), keeps `MaxLightsPerCluster` at or below `MaxLights`, and caps index slots (`TilesX * TilesY * SlicesZ * MaxLightsPerCluster`) at `MaxClusterIndexEntries`; `NewClusteredLightSystem` returns `ErrInvalidClusterConfig` when a storage buffer would exceed the device's `MaxStorageBufferBindingSize`.
- **Lifecycle**: set `ClusterConfig.Retained` to restore buffers across GPU device loss; `ByteSize()` reports GPU buffer bytes for `RenderStats` and budgets, and `Close()` releases resources eagerly.
Loading
Loading