diff --git a/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md b/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md new file mode 100644 index 00000000..8bb704c3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-24-render3d-clustered-forward.md @@ -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` 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. diff --git a/changelog.d/render3d-clustered-forward-382.md b/changelog.d/render3d-clustered-forward-382.md new file mode 100644 index 00000000..250b6662 --- /dev/null +++ b/changelog.d/render3d-clustered-forward-382.md @@ -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). diff --git a/docs/en/render3d.md b/docs/en/render3d.md index 5ffff73f..3d93b6fd 100644 --- a/docs/en/render3d.md +++ b/docs/en/render3d.md @@ -137,6 +137,8 @@ mesh.Draw(pass) Custom 3D shaders can prepend `CameraWGSL + LightWGSL` to read `@group(1) @binding(0) var 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`) @@ -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. diff --git a/docs/zh/render3d.md b/docs/zh/render3d.md index 28ea7d55..bb620ad3 100644 --- a/docs/zh/render3d.md +++ b/docs/zh/render3d.md @@ -137,6 +137,8 @@ mesh.Draw(pass) 自定义 3D 着色器只需在开头拼接 `CameraWGSL + LightWGSL`,即可访问 `@group(1) @binding(0) var lights: LightRigUniform` 并调用可移植 WGSL 函数 `point_light_attenuation`、`spot_cone_attenuation`、`pbr_brdf`、`shade_pbr` 与 `linear_to_srgb`。`LitPBRWGSL` 将它们与 `MeshVertexLayout` 及位于 `PBRDrawGroup`(第 2 组)的逐绘制 `PBRDrawUniform` 组合为完整管线。 +如果局部光源多于 rig 的容量,请在 `LightGroup` 上绑定 `ClusteredLightSystem` 来代替 `GPULightBuffer`:它上传同一个 rig,并加入任意数量的集群点光源和聚光灯,使用同一个 BRDF 着色([集群前向光照](#集群前向光照clusteredlightsystemclustergrid))。 + 着色模型遵循 glTF 2.0 金属度-粗糙度 PBR(电介质 `F0 = 0.04`、Schlick 菲涅尔、Trowbridge-Reitz GGX 法线分布、高度相关 Smith-GGX 可见度项、能量守恒 Lambert 漫反射、感知粗糙度下限 `0.045`,以及 IEC 61966-2-1 线性到 sRGB 输出)。`EvaluatePBR`、`ShadePoint`、`PointLightAttenuation`、`SpotConeAttenuation` 与 `LinearToSRGB` 在 CPU 上实现完全一致的公式;`LightRig.AppendUniformData` 与 `LightUniforms.Encode` 零分配打包 uniform 块。测试逐像素比对 GPU 渲染结果与 CPU `ShadePoint`,覆盖完整能力与 WebGL 2 / GLES 3.0(`nsgotest.NoGPUCompute`)配置及 `Retained` 设备丢失恢复,并将光照场景与 `render3d/testdata/golden/lights_pbr_scene.png`、`lights_point_falloff.png` 和 `spot_lights_scene.png` 参考图比对。 ## 距离雾与高度雾(`Fog`、`GPUFogBuffer`) @@ -1177,3 +1179,42 @@ _ = stack.SetCamera(cam) - **景深(`DepthOfFieldConfig`、`DepthOfFieldPass`)**:支持透视与正交 `[0, 1]` 深度线性化,围绕 `FocusDistance` ± `FocusRange` 计算带符号弥散圆(CoC),并通过 18 采样双环圆盘散景模糊平滑虚化近景与远景,同时阻止背景模糊色溢入清晰的焦内轮廓。 - **泛光(`BloomConfig`、`BloomPass`)**:用二次软拐点阈值曲线(`Threshold`、`SoftKnee`)提取 LDR 或 HDR(`> 1.0`)高亮像素,执行 `BlurPasses` 轮可分离 9 采样高斯横纵模糊(可通过 `HalfRes` 启用半分辨率以获得更宽柔和光晕),再以 `Intensity` 加法混合回场景。 - **跨后端兼容性、生命周期与参考渲染**:所有通道均使用纯片元可移植 WGSL、显式 `textureSampleLevel` 以及代数/预计算权重(不依赖计算着色器,也不使用 `exp`/`log2` 指令),同时兼容完整能力与 `nsgotest.NoGPUCompute`(WebGL 2 / OpenGL ES 3.0)配置,并支持 `Resize(dev, w, h)` 与 `Retained` 设备丢失恢复。黄金参考图(`render3d/testdata/golden/post3d_bloom.png`、`post3d_ssao.png`、`post3d_dof.png` 与 `post3d_combined.png`)用于验证各个独立通道与组合栈;设置 `UPDATE_GOLDEN=1` 可重写参考图。 + +## 集群前向光照(`ClusteredLightSystem`、`ClusterGrid`) + +`LightRig` 最多着色 16 个点光源和 8 个聚光灯。对于有数百个局部光源的场景,`ClusteredLightSystem` 在 `LightGroup` 上取代 `GPULightBuffer`:它在绑定 0 上传同一个 `LightRig`(环境光、方向光以及 rig 自身的点光源和聚光灯),并把任意数量的额外局部光源(`ClusterLight`)分配到由屏幕图块 × 对数深度切片组成的三维网格中(默认 `16 × 9 × 24`,最多 `512` 个可见光源、每个集群 `64` 个)。每个片元只着色自己所在集群的光源,使用与 `shade_pbr` 相同的 Cook-Torrance BRDF 和 glTF `KHR_lights_punctual` 衰减,因此集群光源与 rig 光源的效果完全一致。在不支持存储缓冲区或计算着色器的目标上(WebGL 2、OpenGL ES 3.0,以及使用 `nsgotest.NoGPUCompute` 的无头测试),它回退为单个 uniform 缓冲区,存放 `FallbackMaxLights`(默认 `16`)个最重要的可见光源: + +```go +sys, err := render3d.NewClusteredLightSystem(cx, dev, render3d.DefaultClusterConfig()) +pipe, err := render3d.NewClusteredLitPBRPipeline(cx, dev, camBuf.Layout(), sys, drawBuf.Layout(), gpu.FormatDepth24Plus) + +// 场景光源只需转换一次;Range 为 0(无界)时会推导出截止范围。 +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) +} + +// 每帧录制绘制命令之前: +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) +``` + +- **光源**:`ClusterLight` 是点光源或聚光灯记录,其 `Range` 必须为正,因为集群划分需要包围球。`ClusterLightFromPoint` 和 `ClusterLightFromSpot` 转换 `PointLight` 或 `SpotLight`;`Range == 0` 时,推导出 `Intensity * max(Color) / d^2` 降到 `ClusterRangeCutoff`(1/256)的距离。对于未通过 `Validate` 的光源(包括 `Range == 0`),`Update` 返回包装 `ErrInvalidClusterLight` 的错误;对于格式错误的 rig 返回包装 `ErrInvalidLight` 的错误,而不是丢弃它。`EvaluateLightAttenuation` 复用 `PointLightAttenuation` 和 `SpotConeAttenuation`。 +- **视口尺寸**:`viewW` 和 `viewH` 必须是该渲染通道实际渲染区域的尺寸,且区域从原点开始,因为着色器根据 `@builtin(position)` 计算片元所在的图块。使用 `DynamicResolutionTarget` 时,传入 `ScaledSize()`,而不是原生尺寸。 +- **着色器**:`NewClusteredLitPBRPipeline` 编译 `ClusteredLitWGSL` 或 `ClusteredFallbackWGSL`(与 `sys.WGSL()` 一致的那个),即把 `LitPBRWGSL` 中的 `shade_pbr` 换成 `shade_pbr_clustered` 的模块,输出 sRGB。自定义着色器在前面拼接 `CameraWGSL` 和 `sys.BindingsWGSL()`(`ClusteredBindingsWGSL` 或 `ClusteredFallbackBindingsWGSL`,两者都已包含 `LightWGSL`),并调用 `shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos)`,它在两条路径上签名相同。 +- **CPU 集群划分(`ClusterGrid`)**:视图空间的集群 AABB 按 `(proj, near, far)` 缓存,相机移动时复用。`AssignLights` 剔除视锥外的光源,计算紧凑的屏幕图块和深度切片范围,进行球体与 AABB 相交测试(聚光灯另加保守的圆锥与 AABB 剔除),并在稳态下零分配地打包 `Offsets` 和 `LightIndices`。超出 `MaxLights` 的光源,以及单个集群中超出 `MaxLightsPerCluster` 的光源,按输入顺序丢弃(`TruncatedLights`、`TruncatedClusters`),因此当场景可能超出任一上限时,请把重要光源放在前面。 +- **回退选择**:`SelectFallbackLights` 先丢弃包围球在视锥外的光源,再按功率、范围和到相机的距离对其余光源排序。回退模式下,`CulledLights` 统计视锥外或没有功率的光源,`TruncatedLights` 统计因上限而未被选中的可见光源。 +- **深度切片查找**:着色器在 uniform 切分深度表上做 6 步二分查找来确定片元的深度切片,而不使用 `log2` 和 `exp`,因为 NSGo v0.3.0 的软件 GPU 渲染器会把这些内置函数求值为零。 +- **CPU 参考实现**:`ShadeClusteredPoint` 是 `ShadePoint` 加上所有集群光源,`ShadeClusteredGridPoint` 只使用片元所在集群的光源,与 GPU 完全一致。测试在完整能力和 `NoGPUCompute` 配置下将 GPU 像素与它们比对,包括一个 256 光源的场景。 +- **上限**:`Validate` 将 `MaxLights` 限制在 `MaxClusterLights`(65,536)以内,要求 `MaxLightsPerCluster` 不超过 `MaxLights`,并将索引槽数(`TilesX * TilesY * SlicesZ * MaxLightsPerCluster`)限制在 `MaxClusterIndexEntries` 以内;当某个存储缓冲区超过设备的 `MaxStorageBufferBindingSize` 时,`NewClusteredLightSystem` 返回 `ErrInvalidClusterConfig`。 +- **生命周期**:设置 `ClusterConfig.Retained` 可在 GPU 设备丢失后恢复缓冲区;`ByteSize()` 报告 GPU 缓冲区字节数,供 `RenderStats` 和预算使用,`Close()` 立即释放资源。 diff --git a/packages/game/render3d/clustered.go b/packages/game/render3d/clustered.go new file mode 100644 index 00000000..96093013 --- /dev/null +++ b/packages/game/render3d/clustered.go @@ -0,0 +1,1600 @@ +package render3d + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + "slices" + + "github.com/nsgo-dev/game/packages/game/math3d" + "github.com/nsgo-dev/game/packages/game/scene3d" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" +) + +// Defaults and buffer layout constants for clustered forward lighting. +const ( + // DefaultClusterTilesX is the default number of horizontal screen-space tiles. + DefaultClusterTilesX = 16 + // DefaultClusterTilesY is the default number of vertical screen-space tiles. + DefaultClusterTilesY = 9 + // DefaultClusterSlicesZ is the default number of logarithmic view-space depth slices. + DefaultClusterSlicesZ = 24 + // DefaultClusterMaxLights is the default storage-buffer light capacity in clustered mode. + DefaultClusterMaxLights = 512 + // DefaultMaxLightsPerCluster is the default maximum number of lights recorded per cluster cell. + DefaultMaxLightsPerCluster = 64 + // DefaultFallbackMaxLights is the default uniform-buffer light cap for mobile / WebGL 2 / GLES 3.0 fallback. + DefaultFallbackMaxLights = 16 + + // MaxClusterSlicesZ is the maximum depth slice count supported by the uniform split-depth table (65 slice boundaries packed into 17 vec4 entries). + MaxClusterSlicesZ = 64 + // MaxFallbackLights is the uniform-buffer array capacity of [ClusteredFallbackWGSL]. + MaxFallbackLights = 16 + + // MaxClusterLights is the largest [ClusterConfig.MaxLights] accepted. + MaxClusterLights = 1 << 16 + // MaxClusterIndexEntries bounds TilesX * TilesY * SlicesZ * MaxLightsPerCluster, the number of light-index slots [ClusterGrid] preallocates (64 MiB of uint32 indices). + MaxClusterIndexEntries = 1 << 24 + + // ClusterLightGPUSize is the byte size of one GPU light record (4 vec4, 16-byte aligned in both std140 and std430). + ClusterLightGPUSize = 64 + // ClusterParamsUniformSize is the byte size of the clustered-path ClusterParams uniform block at [LightGroup] binding 1: grid_info (16) + viewport_depth (16) + 17*vec4 slice_depths (272) = 304 bytes. + ClusterParamsUniformSize = 304 + // ClusterCellGPUSize is the byte size of one cluster cell offset/count entry (vec4, 16-byte aligned across all backends). + ClusterCellGPUSize = 16 + // ClusteredFallbackUniformSize is the byte size of the fallback uniform block at [LightGroup] binding 1: info (16) + 16*ClusterLightGPUSize (1024) = 1040 bytes. + ClusteredFallbackUniformSize = 16 + MaxFallbackLights*ClusterLightGPUSize + + // ClusterRangeCutoff is the radiance below which [ClusterLightFromPoint] and [ClusterLightFromSpot] treat a light with Range 0 (unbounded, the glTF default) as finished: the derived range is sqrt(Intensity * max(Color) / ClusterRangeCutoff). + ClusterRangeCutoff = 1.0 / 256 + + clusterMinStorageBindingBytes = 64 * 1024 + minClusterLightRange = 1e-3 +) + +// Sentinel errors returned for invalid clustered lighting configuration or light data. +var ( + // ErrInvalidClusterConfig is wrapped by every error [ClusterConfig.Validate], [NewClusterGrid], and [NewClusteredLightSystem] return for malformed cluster settings. + ErrInvalidClusterConfig = errors.New("render3d: invalid cluster config") + // ErrInvalidClusterLight is wrapped by every error [ClusterLight.Validate] returns for malformed light data. + ErrInvalidClusterLight = errors.New("render3d: invalid cluster light") +) + +// ClusterLightKind selects the emission geometry of a [ClusterLight]. +type ClusterLightKind uint32 + +const ( + // ClusterLightPoint radiates isotropically within Range. + ClusterLightPoint ClusterLightKind = 0 + // ClusterLightSpot radiates within a cone around Direction with smooth inner-to-outer angular attenuation. + ClusterLightSpot ClusterLightKind = 1 +) + +// ClusterLight is the record [ClusterGrid] bins and [ClusteredLightSystem] uploads for one local point or spot light in world space. Build it from a [PointLight] or [SpotLight] with [ClusterLightFromPoint] or [ClusterLightFromSpot], or directly with [NewPointClusterLight] and [NewSpotClusterLight]. +// +// Distance falloff is [PointLightAttenuation] with Range, and spot lights also multiply by [SpotConeAttenuation], so a light shades exactly as the [PointLight] or [SpotLight] it came from. Unlike those, Range must be positive: clustering needs a bounding sphere, so a light with Range 0 (unbounded) is refused by [ClusterLight.Validate] and [ClusteredLightSystem.Update]; the converters derive a range for it from [ClusterRangeCutoff]. +type ClusterLight struct { + Kind ClusterLightKind + Position math3d.Vec3 + Range float32 + Color math3d.Vec3 + Intensity float32 + // Direction is the world-space emission axis for [ClusterLightSpot]. Normalized automatically; zero defaults to (0, -1, 0). + Direction math3d.Vec3 + // InnerConeCos and OuterConeCos are cos(innerHalfAngle) and cos(outerHalfAngle) for [ClusterLightSpot] with 1 >= InnerConeCos >= OuterConeCos >= -1. + InnerConeCos float32 + OuterConeCos float32 +} + +// ClusterLightFromPoint validates l and converts it to a [ClusterLightPoint]. When l.Range is 0 (unbounded), the range is derived as sqrt(Intensity * max(Color) / [ClusterRangeCutoff]), where the light's unwindowed radiance falls to the cutoff; the windowed falloff then reaches exactly zero there instead of trailing off forever. Errors wrap [ErrInvalidLight]. +func ClusterLightFromPoint(l PointLight) (ClusterLight, error) { + if err := l.Validate(); err != nil { + return ClusterLight{}, err + } + return NewPointClusterLight(l.Position, l.Color, l.Intensity, clusterRange(l.Range, l.Color, l.Intensity)), nil +} + +// ClusterLightFromSpot validates l and converts it to a [ClusterLightSpot] with the same cone, deriving a range for Range 0 as [ClusterLightFromPoint] does. Errors wrap [ErrInvalidLight]. +func ClusterLightFromSpot(l SpotLight) (ClusterLight, error) { + if err := l.Validate(); err != nil { + return ClusterLight{}, err + } + dir, _ := spotUnitDirection(l) + return ClusterLight{ + Kind: ClusterLightSpot, + Position: l.Position, + Range: clusterRange(l.Range, l.Color, l.Intensity), + Color: l.Color, + Intensity: l.Intensity, + Direction: dir, + InnerConeCos: float32(math.Cos(float64(l.InnerConeAngle))), + OuterConeCos: float32(math.Cos(float64(l.OuterConeAngle))), + }, nil +} + +// clusterRange returns lightRange when it is positive, and otherwise the distance at which intensity * max(color) / d^2 falls to [ClusterRangeCutoff], at least minClusterLightRange. +func clusterRange(lightRange float32, color math3d.Vec3, intensity float32) float32 { + if lightRange > 0 { + return lightRange + } + power := float64(intensity) * float64(max(color.X, color.Y, color.Z)) + return max(float32(math.Sqrt(power/ClusterRangeCutoff)), minClusterLightRange) +} + +// NewPointClusterLight returns a [ClusterLightPoint] with finite range and linear RGB color. +func NewPointClusterLight(pos, color math3d.Vec3, intensity, lightRange float32) ClusterLight { + return ClusterLight{ + Kind: ClusterLightPoint, + Position: pos, + Range: lightRange, + Color: color, + Intensity: intensity, + } +} + +// NewSpotClusterLight returns a [ClusterLightSpot] aiming along dir with inner and outer cone half-angles in radians (clamped so 0 <= inner <= outer <= pi). +func NewSpotClusterLight(pos, dir, color math3d.Vec3, intensity, lightRange, innerConeRad, outerConeRad float32) ClusterLight { + if dir.LenSq() < 1e-12 { + dir = math3d.Vec3{Y: -1} + } else { + dir = dir.Norm() + } + if innerConeRad < 0 { + innerConeRad = 0 + } + if outerConeRad < innerConeRad { + outerConeRad = innerConeRad + } + if outerConeRad > math.Pi { + outerConeRad = math.Pi + } + return ClusterLight{ + Kind: ClusterLightSpot, + Position: pos, + Range: lightRange, + Color: color, + Intensity: intensity, + Direction: dir, + InnerConeCos: float32(math.Cos(float64(innerConeRad))), + OuterConeCos: float32(math.Cos(float64(outerConeRad))), + } +} + +// Validate checks that l has finite parameters, a known kind, positive Range, non-negative Color and Intensity, and valid cone cosines for spot lights. Every error wraps [ErrInvalidClusterLight]. +func (l ClusterLight) Validate() error { + if l.Kind != ClusterLightPoint && l.Kind != ClusterLightSpot { + return fmt.Errorf("%w: unknown light kind %d", ErrInvalidClusterLight, l.Kind) + } + if !finite3(l.Position) { + return fmt.Errorf("%w: position is not finite", ErrInvalidClusterLight) + } + if !finite(l.Range) || l.Range <= 0 { + return fmt.Errorf("%w: range %v must be finite and positive (ClusterLightFromPoint and ClusterLightFromSpot derive one for an unbounded light)", ErrInvalidClusterLight, l.Range) + } + if !finite3(l.Color) || l.Color.X < 0 || l.Color.Y < 0 || l.Color.Z < 0 { + return fmt.Errorf("%w: color %v must be finite and non-negative", ErrInvalidClusterLight, l.Color) + } + if !finite(l.Intensity) || l.Intensity < 0 { + return fmt.Errorf("%w: intensity %v must be finite and non-negative", ErrInvalidClusterLight, l.Intensity) + } + if l.Kind == ClusterLightSpot { + if !finite3(l.Direction) { + return fmt.Errorf("%w: spot direction is not finite", ErrInvalidClusterLight) + } + if !finite(l.InnerConeCos) || !finite(l.OuterConeCos) { + return fmt.Errorf("%w: spot cone cosines must be finite", ErrInvalidClusterLight) + } + if l.InnerConeCos < -1 || l.InnerConeCos > 1 || l.OuterConeCos < -1 || l.OuterConeCos > 1 { + return fmt.Errorf("%w: spot cone cosines (%v, %v) out of [-1, 1]", ErrInvalidClusterLight, l.InnerConeCos, l.OuterConeCos) + } + if l.OuterConeCos > l.InnerConeCos { + return fmt.Errorf("%w: OuterConeCos (%v) exceeds InnerConeCos (%v)", ErrInvalidClusterLight, l.OuterConeCos, l.InnerConeCos) + } + } + return nil +} + +func (l ClusterLight) normalizedDir() math3d.Vec3 { + if l.Direction.LenSq() < 1e-12 { + return math3d.Vec3{Y: -1} + } + return l.Direction.Norm() +} + +func (l ClusterLight) spotScaleOffset() (scale, offset float32) { + if l.Kind != ClusterLightSpot { + return 0, 1 + } + inner := math3d.Clamp(l.InnerConeCos, -1, 1) + outer := math3d.Clamp(l.OuterConeCos, -1, inner) + denom := max(inner-outer, minSpotConeCosDelta) + scale = 1.0 / denom + offset = -outer * scale + return scale, offset +} + +func (l ClusterLight) isActive() bool { + if l.Kind != ClusterLightPoint && l.Kind != ClusterLightSpot { + return false + } + if !finite3(l.Position) || !finite(l.Range) || l.Range <= 0 { + return false + } + if !finite(l.Intensity) || l.Intensity <= 0 || !finite3(l.Color) { + return false + } + if l.Color.X <= 0 && l.Color.Y <= 0 && l.Color.Z <= 0 { + return false + } + return true +} + +// ClusterConfig configures the 3D frustum-cluster grid and its mobile uniform-buffer fallback. Zero fields use defaults from [DefaultClusterConfig]. +type ClusterConfig struct { + // TilesX is the number of screen-space horizontal tiles (default 16). + TilesX int + // TilesY is the number of screen-space vertical tiles (default 9). + TilesY int + // SlicesZ is the number of logarithmic view-space depth slices (default 24, max 64). + SlicesZ int + // MaxLights is the maximum number of visible local lights stored in clustered mode (default 512). + MaxLights int + // MaxLightsPerCluster caps how many lights can be assigned to one cluster cell (default 64). + MaxLightsPerCluster int + // FallbackMaxLights caps how many prioritized lights are uploaded in uniform-buffer fallback mode (default 16, max 16). + FallbackMaxLights int + // ForceFallback forces the uniform-buffer fallback path even on devices that support storage buffers and compute. + ForceFallback bool + // Retained keeps CPU copies of GPU buffers so NSGo recreates them after a device loss. + Retained bool + // Label prefixes GPU resource debug labels. + Label string +} + +// DefaultClusterConfig returns the standard 16x9x24 frustum-cluster grid supporting 512 lights (64 per cluster) and a 16-light mobile/WebGL 2 fallback. +func DefaultClusterConfig() ClusterConfig { + return ClusterConfig{ + TilesX: DefaultClusterTilesX, + TilesY: DefaultClusterTilesY, + SlicesZ: DefaultClusterSlicesZ, + MaxLights: DefaultClusterMaxLights, + MaxLightsPerCluster: DefaultMaxLightsPerCluster, + FallbackMaxLights: DefaultFallbackMaxLights, + } +} + +func (c ClusterConfig) withDefaults() ClusterConfig { + if c.TilesX == 0 { + c.TilesX = DefaultClusterTilesX + } + if c.TilesY == 0 { + c.TilesY = DefaultClusterTilesY + } + if c.SlicesZ == 0 { + c.SlicesZ = DefaultClusterSlicesZ + } + if c.MaxLights == 0 { + c.MaxLights = DefaultClusterMaxLights + } + if c.MaxLightsPerCluster == 0 { + c.MaxLightsPerCluster = DefaultMaxLightsPerCluster + } + if c.FallbackMaxLights == 0 { + c.FallbackMaxLights = DefaultFallbackMaxLights + } + return c +} + +// Validate checks that every field (after applying defaults to zero fields) is within supported limits. Every error wraps [ErrInvalidClusterConfig]. +func (c ClusterConfig) Validate() error { + c = c.withDefaults() + if c.TilesX < 1 || c.TilesY < 1 { + return fmt.Errorf("%w: tile grid %dx%d must be positive", ErrInvalidClusterConfig, c.TilesX, c.TilesY) + } + if c.SlicesZ < 1 || c.SlicesZ > MaxClusterSlicesZ { + return fmt.Errorf("%w: SlicesZ %d must be in [1, %d]", ErrInvalidClusterConfig, c.SlicesZ, MaxClusterSlicesZ) + } + if c.MaxLights < 1 || c.MaxLights > MaxClusterLights { + return fmt.Errorf("%w: MaxLights %d must be in [1, %d]", ErrInvalidClusterConfig, c.MaxLights, MaxClusterLights) + } + if c.MaxLightsPerCluster < 1 || c.MaxLightsPerCluster > c.MaxLights { + return fmt.Errorf("%w: MaxLightsPerCluster %d must be in [1, MaxLights %d]", ErrInvalidClusterConfig, c.MaxLightsPerCluster, c.MaxLights) + } + if c.FallbackMaxLights < 1 || c.FallbackMaxLights > MaxFallbackLights { + return fmt.Errorf("%w: FallbackMaxLights %d must be in [1, %d]", ErrInvalidClusterConfig, c.FallbackMaxLights, MaxFallbackLights) + } + totalClusters := uint64(c.TilesX) * uint64(c.TilesY) * uint64(c.SlicesZ) + if totalClusters == 0 || totalClusters > 1<<20 { + return fmt.Errorf("%w: cluster count %d out of range", ErrInvalidClusterConfig, totalClusters) + } + if entries := totalClusters * uint64(c.MaxLightsPerCluster); entries > MaxClusterIndexEntries { + return fmt.Errorf("%w: %d clusters x %d lights per cluster = %d index slots exceed MaxClusterIndexEntries (%d)", ErrInvalidClusterConfig, totalClusters, c.MaxLightsPerCluster, entries, MaxClusterIndexEntries) + } + return nil +} + +// ClusterCount returns the total number of 3D frustum clusters (TilesX * TilesY * SlicesZ) after applying defaults. +func (c ClusterConfig) ClusterCount() int { + c = c.withDefaults() + return c.TilesX * c.TilesY * c.SlicesZ +} + +// ClusterOffsetCount identifies the contiguous slice of [ClusterGrid.LightIndices] assigned to one cluster cell: indices[Offset : Offset+Count]. +type ClusterOffsetCount struct { + Offset uint32 + Count uint32 +} + +// ClusterStats reports per-frame light culling and cluster packing metrics. +type ClusterStats struct { + InputLights int + VisibleLights int + CulledLights int + ActiveClusters int + TotalAssignments int + MaxClusterLights int + AvgLightsPerActive float32 + TruncatedClusters int + TruncatedLights int +} + +// ClusterGrid builds a 3D view-space frustum cluster grid and assigns local point and spot lights to intersecting cells with zero steady-state allocations. +// +// Cluster AABBs are cached by (proj, near, far) so camera rotation/translation frames reuse the frustum cells without recomputing them. +type ClusterGrid struct { + cfg ClusterConfig + + // Cached frustum AABB parameters. + hasGrid bool + cachedProj math3d.Mat4 + cachedNear float32 + cachedFar float32 + sliceDepths [MaxClusterSlicesZ + 1]float32 + aabbs []math3d.AABB + + // Preallocated per-frame assignment scratch and packed outputs. + activeLights []ClusterLight + clusterCounts []uint32 + clusterTrunc []bool + scratchIndices []uint32 + offsets []ClusterOffsetCount + lightIndices []uint32 + lastStats ClusterStats +} + +// NewClusterGrid validates cfg and allocates reusable storage for frustum clusters and light assignment. +func NewClusterGrid(cfg ClusterConfig) (*ClusterGrid, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + cfg = cfg.withDefaults() + numClusters := cfg.ClusterCount() + return &ClusterGrid{ + cfg: cfg, + aabbs: make([]math3d.AABB, numClusters), + activeLights: make([]ClusterLight, 0, cfg.MaxLights), + clusterCounts: make([]uint32, numClusters), + clusterTrunc: make([]bool, numClusters), + scratchIndices: make([]uint32, numClusters*cfg.MaxLightsPerCluster), + offsets: make([]ClusterOffsetCount, numClusters), + lightIndices: make([]uint32, 0, numClusters*min(cfg.MaxLightsPerCluster, 16)), + }, nil +} + +// Config returns the normalized [ClusterConfig] of g. +func (g *ClusterGrid) Config() ClusterConfig { return g.cfg } + +// ClusterCount returns the total number of frustum cells (TilesX * TilesY * SlicesZ). +func (g *ClusterGrid) ClusterCount() int { return len(g.aabbs) } + +// SliceDepths returns the positive view-space depth boundaries [near .. far] of length SlicesZ+1 computed on the most recent [ClusterGrid.AssignLights] or [ClusterGrid.BuildFrustum]. +func (g *ClusterGrid) SliceDepths() []float32 { return g.sliceDepths[:g.cfg.SlicesZ+1] } + +// ClusterAABB returns the cached view-space AABB of cluster (tileX, tileY, sliceZ). +func (g *ClusterGrid) ClusterAABB(tileX, tileY, sliceZ int) math3d.AABB { + idx := g.ClusterIndex(tileX, tileY, sliceZ) + if idx < 0 || idx >= len(g.aabbs) { + return math3d.AABBEmpty() + } + return g.aabbs[idx] +} + +// ClusterIndex returns the flat linear index for cluster coordinates (tileX, tileY, sliceZ). +func (g *ClusterGrid) ClusterIndex(tileX, tileY, sliceZ int) int { + return (sliceZ*g.cfg.TilesY+tileY)*g.cfg.TilesX + tileX +} + +// ActiveLights returns the frustum-visible lights packed by the most recent [ClusterGrid.AssignLights] call (indices in [ClusterGrid.LightIndices] reference this slice). +func (g *ClusterGrid) ActiveLights() []ClusterLight { return g.activeLights } + +// Offsets returns the per-cluster offset/count table packed by the most recent [ClusterGrid.AssignLights] call. +func (g *ClusterGrid) Offsets() []ClusterOffsetCount { return g.offsets } + +// LightIndices returns the flat packed light-index list referenced by [ClusterGrid.Offsets]. +func (g *ClusterGrid) LightIndices() []uint32 { return g.lightIndices } + +// ClusterLightIndices returns the light indices assigned to cluster (tileX, tileY, sliceZ) on the last [ClusterGrid.AssignLights] call. +func (g *ClusterGrid) ClusterLightIndices(tileX, tileY, sliceZ int) []uint32 { + idx := g.ClusterIndex(tileX, tileY, sliceZ) + if idx < 0 || idx >= len(g.offsets) { + return nil + } + oc := g.offsets[idx] + end := uint64(oc.Offset) + uint64(oc.Count) + if end > uint64(len(g.lightIndices)) { + return nil + } + return g.lightIndices[oc.Offset:end] +} + +// LastStats returns the [ClusterStats] from the most recent [ClusterGrid.AssignLights] call. +func (g *ClusterGrid) LastStats() ClusterStats { return g.lastStats } + +// SliceForDepth maps a positive view-space depth viewZ to its depth slice index in [0, SlicesZ-1] using the exact same binary search over [ClusterGrid.SliceDepths] as the GPU fragment shader. +func (g *ClusterGrid) SliceForDepth(viewZ float32) int { + n := g.cfg.SlicesZ + if n <= 1 { + return 0 + } + lo, hi := 0, n-1 + for lo < hi { + mid := (lo + hi) >> 1 + if viewZ >= g.sliceDepths[mid+1] { + lo = mid + 1 + } else { + hi = mid + } + } + return lo +} + +// BuildFrustum computes view-space depth slice boundaries and per-cluster view-space AABBs for (proj, near, far), caching the result until any of those inputs change. +func (g *ClusterGrid) BuildFrustum(proj math3d.Mat4, near, far float32) bool { + if !finite(near) || !finite(far) || far <= near { + return false + } + if g.hasGrid && g.cachedProj == proj && g.cachedNear == near && g.cachedFar == far { + return true + } + invProj, ok := proj.Inverse() + if !ok { + return false + } + + slices := g.cfg.SlicesZ + useLog := near > 0 && proj[11] != 0 + if useLog { + ratio := float64(far) / float64(near) + invSlices := 1.0 / float64(slices) + g.sliceDepths[0] = near + for s := 1; s < slices; s++ { + g.sliceDepths[s] = float32(float64(near) * math.Pow(ratio, float64(s)*invSlices)) + } + g.sliceDepths[slices] = far + } else { + span := float64(far - near) + invSlices := 1.0 / float64(slices) + for s := 0; s <= slices; s++ { + g.sliceDepths[s] = float32(float64(near) + span*float64(s)*invSlices) + } + } + + txN := g.cfg.TilesX + tyN := g.cfg.TilesY + invTX := 2.0 / float32(txN) + invTY := 2.0 / float32(tyN) + + // Unproject a screen-NDC corner (nx, ny) onto view plane z = -depth using invProj. + unprojectAtDepth := func(nx, ny, depth float32) math3d.Vec3 { + z := -depth + clipZ := proj[10]*z + proj[14] + clipW := proj[11]*z + proj[15] + if clipW == 0 { + return math3d.Vec3{Z: z} + } + ndcZ := clipZ / clipW + p := invProj.TransformPoint(math3d.Vec3{X: nx, Y: ny, Z: ndcZ}) + p.Z = z + return p + } + + for s := range slices { + z0 := g.sliceDepths[s] + z1 := g.sliceDepths[s+1] + sliceBase := s * tyN * txN + for ty := range tyN { + ndcYTop := 1.0 - float32(ty)*invTY + ndcYBot := 1.0 - float32(ty+1)*invTY + rowBase := sliceBase + ty*txN + for tx := range txN { + ndcXL := -1.0 + float32(tx)*invTX + ndcXR := -1.0 + float32(tx+1)*invTX + + c0 := unprojectAtDepth(ndcXL, ndcYBot, z0) + c1 := unprojectAtDepth(ndcXR, ndcYBot, z0) + c2 := unprojectAtDepth(ndcXL, ndcYTop, z0) + c3 := unprojectAtDepth(ndcXR, ndcYTop, z0) + c4 := unprojectAtDepth(ndcXL, ndcYBot, z1) + c5 := unprojectAtDepth(ndcXR, ndcYBot, z1) + c6 := unprojectAtDepth(ndcXL, ndcYTop, z1) + c7 := unprojectAtDepth(ndcXR, ndcYTop, z1) + + minV := c0.Min(c1).Min(c2).Min(c3).Min(c4).Min(c5).Min(c6).Min(c7) + maxV := c0.Max(c1).Max(c2).Max(c3).Max(c4).Max(c5).Max(c6).Max(c7) + g.aabbs[rowBase+tx] = math3d.AABB{Min: minV, Max: maxV} + } + } + } + + g.hasGrid = true + g.cachedProj = proj + g.cachedNear = near + g.cachedFar = far + return true +} + +// AssignLights transforms lights into view space, culls lights outside the camera frustum, tests each visible light against its candidate frustum clusters (sphere-vs-AABB for all lights plus exact cone-vs-AABB rejection for spot lights), and packs compact offset/count and index arrays. +// +// Lights that fail [ClusterLight.Validate] or have no power are skipped and counted in CulledLights; [ClusteredLightSystem.Update] validates first and reports them as errors. Once MaxLights lights are visible, further lights are dropped in input order (TruncatedLights), and once a cell holds MaxLightsPerCluster lights it drops the rest in input order (TruncatedClusters), so put the most important lights first when a scene can exceed either cap. Steady-state calls perform zero heap allocations. +func (g *ClusterGrid) AssignLights(view, proj math3d.Mat4, near, far float32, lights []ClusterLight) ClusterStats { + stats := ClusterStats{InputLights: len(lights)} + g.activeLights = g.activeLights[:0] + clear(g.clusterCounts) + clear(g.clusterTrunc) + g.lightIndices = g.lightIndices[:0] + + numClusters := len(g.aabbs) + if !g.BuildFrustum(proj, near, far) || len(lights) == 0 { + clear(g.offsets) + stats.CulledLights = len(lights) + g.lastStats = stats + return stats + } + + tilesX := g.cfg.TilesX + tilesY := g.cfg.TilesY + slicesZ := g.cfg.SlicesZ + maxPerCluster := g.cfg.MaxLightsPerCluster + isPersp := proj[11] != 0 + + for i := range lights { + l := lights[i] + if !l.isActive() { + stats.CulledLights++ + continue + } + + posV := view.TransformPoint(l.Position) + sphereCenter := posV + sphereRadius := l.Range + + var dirV math3d.Vec3 + var cosOuter, sinOuter float32 + isSpot := l.Kind == ClusterLightSpot + if isSpot { + dirW := l.normalizedDir() + dirV = view.TransformDir(dirW) + if dirV.LenSq() < 1e-12 { + dirV = math3d.Vec3{Y: -1} + } else { + dirV = dirV.Norm() + } + cosOuter = math3d.Clamp(l.OuterConeCos, -1, 1) + sinSq := 1.0 - cosOuter*cosOuter + if sinSq < 0 { + sinSq = 0 + } + sinOuter = float32(math.Sqrt(float64(sinSq))) + sphereCenter, sphereRadius = spotBoundingSphere(posV, dirV, l.Range, cosOuter, sinOuter) + } + + // Quick view-space depth rejection (camera looks down -Z, positive depth = -z). + minDepth := -sphereCenter.Z - sphereRadius + maxDepth := -sphereCenter.Z + sphereRadius + if maxDepth < near || minDepth > far { + stats.CulledLights++ + continue + } + + // Tight screen-tile rectangle in [0, tilesX-1] x [0, tilesY-1]. + txMin, txMax, tyMin, tyMax, visible := projectSphereTiles(proj, isPersp, near, far, sphereCenter, sphereRadius, tilesX, tilesY) + if !visible { + stats.CulledLights++ + continue + } + + if len(g.activeLights) >= g.cfg.MaxLights { + stats.TruncatedLights++ + continue + } + + lightIdx := uint32(len(g.activeLights)) + g.activeLights = append(g.activeLights, l) + + // Tight Z-slice range via binary search on cached depth splits. + sliceMin := 0 + if minDepth > near { + sliceMin = g.SliceForDepth(minDepth) + } + sliceMax := slicesZ - 1 + if maxDepth < far { + sliceMax = g.SliceForDepth(maxDepth) + } + if sliceMax < sliceMin { + sliceMax = sliceMin + } + + rSq := sphereRadius * sphereRadius + anyCell := false + for s := sliceMin; s <= sliceMax; s++ { + sliceBase := s * tilesY * tilesX + for ty := tyMin; ty <= tyMax; ty++ { + rowBase := sliceBase + ty*tilesX + for tx := txMin; tx <= txMax; tx++ { + cIdx := rowBase + tx + box := g.aabbs[cIdx] + if !sphereIntersectsAABBSq(sphereCenter, rSq, box) { + continue + } + if isSpot && cosOuter > 0 { + if !spotConeIntersectsAABB(posV, dirV, l.Range, cosOuter, sinOuter, box) { + continue + } + } + anyCell = true + cnt := int(g.clusterCounts[cIdx]) + if cnt < maxPerCluster { + g.scratchIndices[cIdx*maxPerCluster+cnt] = lightIdx + g.clusterCounts[cIdx] = uint32(cnt + 1) + } else { + g.clusterTrunc[cIdx] = true + } + } + } + } + + if !anyCell { + // Light passed coarse screen-rect test but touched no cluster AABB. + g.activeLights = g.activeLights[:len(g.activeLights)-1] + stats.CulledLights++ + continue + } + } + + stats.VisibleLights = len(g.activeLights) + + // Compact scratch lists into contiguous lightIndices + offsets table. + var total int + for cIdx := range numClusters { + cnt := int(g.clusterCounts[cIdx]) + if g.clusterTrunc[cIdx] { + stats.TruncatedClusters++ + } + if cnt == 0 { + g.offsets[cIdx] = ClusterOffsetCount{} + continue + } + stats.ActiveClusters++ + if cnt > stats.MaxClusterLights { + stats.MaxClusterLights = cnt + } + g.offsets[cIdx] = ClusterOffsetCount{ + Offset: uint32(total), + Count: uint32(cnt), + } + total += cnt + } + + if cap(g.lightIndices) < total { + g.lightIndices = make([]uint32, total) + } else { + g.lightIndices = g.lightIndices[:total] + } + for cIdx := range numClusters { + cnt := int(g.clusterCounts[cIdx]) + if cnt == 0 { + continue + } + off := int(g.offsets[cIdx].Offset) + srcOff := cIdx * maxPerCluster + copy(g.lightIndices[off:off+cnt], g.scratchIndices[srcOff:srcOff+cnt]) + } + + stats.TotalAssignments = total + if stats.ActiveClusters > 0 { + stats.AvgLightsPerActive = float32(total) / float32(stats.ActiveClusters) + } + g.lastStats = stats + return stats +} + +// spotBoundingSphere computes the minimal bounding sphere enclosing a spotlight cone (Bart Wronski / Frostbite formulation). +func spotBoundingSphere(apex, dir math3d.Vec3, lightRange, cosOuter, sinOuter float32) (math3d.Vec3, float32) { + if cosOuter <= 0 { + return apex, lightRange + } + const cos45 = 0.70710678 + if cosOuter < cos45 { + return apex.Add(dir.Scale(lightRange * cosOuter)), lightRange * sinOuter + } + r := lightRange / (2.0 * cosOuter) + return apex.Add(dir.Scale(r)), r +} + +func sphereIntersectsAABBSq(center math3d.Vec3, radiusSq float32, b math3d.AABB) bool { + cx := math3d.Clamp(center.X, b.Min.X, b.Max.X) + cy := math3d.Clamp(center.Y, b.Min.Y, b.Max.Y) + cz := math3d.Clamp(center.Z, b.Min.Z, b.Max.Z) + dx := center.X - cx + dy := center.Y - cy + dz := center.Z - cz + return dx*dx+dy*dy+dz*dz <= radiusSq +} + +// spotConeIntersectsAABB conservatively tests whether a spotlight cone (cosOuter > 0) intersects box b by testing the cone against b's bounding sphere. Guaranteed zero false negatives. +func spotConeIntersectsAABB(apex, dir math3d.Vec3, lightRange, cosOuter, sinOuter float32, b math3d.AABB) bool { + center := b.Center() + radius := b.HalfExtents().Len() + + v := center.Sub(apex) + vLenSq := v.LenSq() + v1Len := v.Dot(dir) + + if v1Len < -radius || v1Len > lightRange+radius { + return false + } + + perpSq := vLenSq - v1Len*v1Len + if perpSq < 0 { + perpSq = 0 + } + dPerp := float32(math.Sqrt(float64(perpSq))) + + // Projection along the closest cone generator ray: if <= 0, the apex is the closest point on the cone. + if v1Len*cosOuter+dPerp*sinOuter <= 0 { + return vLenSq <= radius*radius + } + closestDist := dPerp*cosOuter - v1Len*sinOuter + return closestDist <= radius +} + +// projectSphereTiles computes a conservative [txMin..txMax] x [tyMin..tyMax] screen-tile rectangle for a view-space bounding sphere. +func projectSphereTiles(proj math3d.Mat4, isPersp bool, near, far float32, center math3d.Vec3, radius float32, tilesX, tilesY int) (txMin, txMax, tyMin, tyMax int, visible bool) { + zMax := center.Z + radius + zMin := center.Z - radius + if isPersp && zMax >= -near*1.001 { + // Sphere crosses or touches the near plane: conservatively span the full screen so near-plane clipping never produces a false negative. + return 0, tilesX - 1, 0, tilesY - 1, true + } + if zMin < -far { + zMin = -far + } + if zMax > -near { + zMax = -near + } + + xs := [2]float32{center.X - radius, center.X + radius} + ys := [2]float32{center.Y - radius, center.Y + radius} + zs := [2]float32{zMin, zMax} + + minX, maxX := float32(math.Inf(1)), float32(math.Inf(-1)) + minY, maxY := float32(math.Inf(1)), float32(math.Inf(-1)) + + for _, x := range xs { + for _, y := range ys { + for _, z := range zs { + clip := proj.MulVec4(math3d.Vec4{X: x, Y: y, Z: z, W: 1}) + if clip.W <= 1e-6 { + return 0, tilesX - 1, 0, tilesY - 1, true + } + invW := 1.0 / clip.W + nx := clip.X * invW + ny := clip.Y * invW + if nx < minX { + minX = nx + } + if nx > maxX { + maxX = nx + } + if ny < minY { + minY = ny + } + if ny > maxY { + maxY = ny + } + } + } + } + + if maxX < -1 || minX > 1 || maxY < -1 || minY > 1 { + return 0, 0, 0, 0, false + } + + txMin = clusterClampInt(int(math.Floor(float64((minX+1)*0.5*float32(tilesX)))), 0, tilesX-1) + txMax = clusterClampInt(int(math.Floor(float64((maxX+1)*0.5*float32(tilesX)))), 0, tilesX-1) + tyMin = clusterClampInt(int(math.Floor(float64((1-maxY)*0.5*float32(tilesY)))), 0, tilesY-1) + tyMax = clusterClampInt(int(math.Floor(float64((1-minY)*0.5*float32(tilesY)))), 0, tilesY-1) + return txMin, txMax, tyMin, tyMax, true +} + +func clusterClampInt(v, lo, hi int) int { + if v < lo { + return lo + } + if v > hi { + return hi + } + return v +} + +type scoredClusterLight struct { + index int + score float32 +} + +// SelectFallbackLights chooses up to maxLights local lights for the uniform-buffer fallback path (mobile, WebGL 2, OpenGL ES 3.0) and appends them to dst[:0]. +// +// Lights whose bounding sphere lies outside the view frustum of proj * view, or that fail [ClusterLight.Validate] or have no power, are dropped first, so off-screen lights never take a slot from visible ones. The rest are ranked deterministically by luminous power, range, and distance to the camera, breaking ties by input order. This allocates a scratch slice per call; [ClusteredLightSystem.Update] reuses one. +func SelectFallbackLights(dst []ClusterLight, view, proj math3d.Mat4, lights []ClusterLight, maxLights int) []ClusterLight { + dst = dst[:0] + if maxLights <= 0 || len(lights) == 0 { + return dst + } + scored := make([]scoredClusterLight, 0, len(lights)) + return selectFallbackLightsWithScratch(dst, &scored, view, proj, lights, maxLights) +} + +// clusterLightBounds returns a world-space sphere enclosing everything l can light. +func clusterLightBounds(l ClusterLight) math3d.Sphere { + if l.Kind != ClusterLightSpot { + return math3d.Sphere{Center: l.Position, Radius: l.Range} + } + cosOuter := math3d.Clamp(l.OuterConeCos, -1, 1) + sinOuter := float32(math.Sqrt(float64(max(1-cosOuter*cosOuter, 0)))) + c, r := spotBoundingSphere(l.Position, l.normalizedDir(), l.Range, cosOuter, sinOuter) + return math3d.Sphere{Center: c, Radius: r} +} + +func selectFallbackLightsWithScratch(dst []ClusterLight, scratch *[]scoredClusterLight, view, proj math3d.Mat4, lights []ClusterLight, maxLights int) []ClusterLight { + dst = dst[:0] + *scratch = (*scratch)[:0] + if maxLights <= 0 || len(lights) == 0 { + return dst + } + frustum := math3d.FrustumFromMat4(proj.Mul(view)) + cameraPos, _ := cameraPoseFromView(view) + + scored := (*scratch)[:0] + for i := range lights { + l := lights[i] + if !l.isActive() || !frustum.IntersectsSphere(clusterLightBounds(l)) { + continue + } + lum := 0.2126*l.Color.X + 0.7152*l.Color.Y + 0.0722*l.Color.Z + if lum <= 0 { + lum = max(l.Color.X, l.Color.Y, l.Color.Z) + } + distSq := l.Position.Sub(cameraPos).LenSq() + dist := float32(math.Sqrt(float64(distSq))) + // Smooth importance combining power, range coverage, and camera distance. + score := l.Intensity * lum * (l.Range * l.Range) / ((distSq + 0.25) * (1.0 + dist/max(l.Range, minClusterLightRange))) + scored = append(scored, scoredClusterLight{index: i, score: score}) + } + *scratch = scored + + slices.SortFunc(scored, compareScoredClusterLights) + keep := min(len(scored), maxLights) + for i := range keep { + dst = append(dst, lights[scored[i].index]) + } + return dst +} + +// compareScoredClusterLights orders by descending score, then ascending input index. +func compareScoredClusterLights(a, b scoredClusterLight) int { + switch { + case a.score > b.score: + return -1 + case a.score < b.score: + return 1 + } + return a.index - b.index +} + +// EvaluateLightAttenuation returns the unit direction from worldPos toward light and the light's attenuation times its Intensity: [PointLightAttenuation] with Range, times [SpotConeAttenuation] for a [ClusterLightSpot]. It returns zeros for a light with no power or an invalid record, and when worldPos coincides with the light. +func EvaluateLightAttenuation(light ClusterLight, worldPos math3d.Vec3) (dirToLight math3d.Vec3, attenuation float32) { + if !light.isActive() { + return math3d.Vec3{}, 0 + } + toLight := light.Position.Sub(worldPos) + distSq := toLight.LenSq() + if distSq <= minLightDirLenSq { + return math3d.Vec3{}, 0 + } + dirToLight = toLight.Scale(float32(1.0 / math.Sqrt(float64(distSq)))) + atten := PointLightAttenuation(distSq, light.Range) + if light.Kind == ClusterLightSpot { + scale, offset := light.spotScaleOffset() + atten *= SpotConeAttenuation(light.normalizedDir(), dirToLight, scale, offset) + } + return dirToLight, atten * light.Intensity +} + +// ShadeClusteredPoint is [ShadePoint] for rig plus every light in lights, shaded with the same Cook-Torrance BRDF ([EvaluatePBR]). It is the brute-force reference for shade_pbr_clustered in [ClusteredBindingsWGSL] and [ClusteredFallbackBindingsWGSL] when no light is culled or truncated; call [LinearToSRGB] on the result to compare it with what [ClusteredLitWGSL] writes. +func ShadeClusteredPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, lights []ClusterLight) math3d.Vec3 { + lo := ShadePoint(worldPos, normal, viewDir, mat, rig) + n, v, ok := clusterUnitNormalView(normal, viewDir) + if !ok { + return lo + } + for i := range lights { + lo = lo.Add(clusterLightRadiance(lights[i], worldPos, n, v, mat)) + } + return lo +} + +// ShadeClusteredGridPoint is [ShadeClusteredPoint] restricted to the lights grid assigned, on its last [ClusterGrid.AssignLights], to the cluster that holds worldPos in a viewportW x viewportH viewport, looked up exactly as shade_pbr_clustered in [ClusteredBindingsWGSL] looks it up. +func ShadeClusteredGridPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, grid *ClusterGrid, view, proj math3d.Mat4, viewportW, viewportH float32) math3d.Vec3 { + lo := ShadePoint(worldPos, normal, viewDir, mat, rig) + n, v, ok := clusterUnitNormalView(normal, viewDir) + if grid == nil || !ok { + return lo + } + viewPos := view.TransformPoint(worldPos) + clip := proj.MulVec4(viewPos.Vec4(1)) + if clip.W <= 1e-6 { + return lo + } + fragX := (clip.X/clip.W + 1.0) * 0.5 * viewportW + fragY := (1.0 - clip.Y/clip.W) * 0.5 * viewportH + tx := clusterClampInt(int(max(fragX, 0)/max(viewportW, 1)*float32(grid.cfg.TilesX)), 0, grid.cfg.TilesX-1) + ty := clusterClampInt(int(max(fragY, 0)/max(viewportH, 1)*float32(grid.cfg.TilesY)), 0, grid.cfg.TilesY-1) + sz := grid.SliceForDepth(-viewPos.Z) + for _, lightIdx := range grid.ClusterLightIndices(tx, ty, sz) { + lo = lo.Add(clusterLightRadiance(grid.activeLights[lightIdx], worldPos, n, v, mat)) + } + return lo +} + +func clusterUnitNormalView(normal, viewDir math3d.Vec3) (n, v math3d.Vec3, ok bool) { + nLenSq := normal.LenSq() + vLenSq := viewDir.LenSq() + if nLenSq <= minLightDirLenSq || vLenSq <= minLightDirLenSq { + return math3d.Vec3{}, math3d.Vec3{}, false + } + return normal.Scale(float32(1.0 / math.Sqrt(float64(nLenSq)))), viewDir.Scale(float32(1.0 / math.Sqrt(float64(vLenSq)))), true +} + +// clusterLightRadiance is the outgoing radiance one local light adds at worldPos for unit n and v, matching cluster_light_radiance in the clustered WGSL. +func clusterLightRadiance(l ClusterLight, worldPos, n, v math3d.Vec3, mat PBRMaterial) math3d.Vec3 { + lDir, atten := EvaluateLightAttenuation(l, worldPos) + ndotl := n.Dot(lDir) + if atten <= 0 || ndotl <= 0 { + return math3d.Vec3{} + } + brdf := EvaluatePBR(n, v, lDir, mat) + rad := l.Color.Scale(atten * ndotl) + return math3d.Vec3{X: brdf.X * rad.X, Y: brdf.Y * rad.Y, Z: brdf.Z * rad.Z} +} + +// DeviceSupportsClusteredLighting reports whether dev exposes the storage-buffer and compute capabilities needed for the clustered forward shading path. Devices without them (such as WebGL 2, OpenGL ES 3.0, or headless tests under nsgotest.NoGPUCompute) fall back to the uniform-buffer path automatically. +func DeviceSupportsClusteredLighting(dev *gpu.Device) bool { + if dev == nil { + return false + } + caps := dev.Capabilities() + return caps.Features.StorageBuffers && + caps.Features.Compute && + caps.Limits.MaxStorageBufferBindingSize >= clusterMinStorageBindingBytes +} + +// ClusteredBindingsWGSL is [LightWGSL] (the [LightRig] block at [LightGroup] binding 0 and its PBR helpers) plus the clustered forward bindings at bindings 1 to 4 of the same group and this helper: +// +// - shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos) -> vec3 +// +// It returns shade_pbr for the rig plus every local light binned into the cluster that holds the fragment, each shaded with pbr_brdf, point_light_attenuation and spot_cone_attenuation, so it matches [ShadeClusteredGridPoint]. frag_pos is the fragment's @builtin(position). Prepend [CameraWGSL], which supplies camera.view for the depth slice, and pair it with a [ClusteredLightSystem] in clustered mode; [ClusteredFallbackBindingsWGSL] declares the same helper for the fallback path. +// +// Depth slicing is a 6-step binary search over the uniform split-depth table rather than log2 and exp, because NSGo v0.3.0's software GPU VM has no log, log2, exp or exp2 builtin and silently evaluates them to zero (internal/driver/gpu_software.go, evalCall). +const ClusteredBindingsWGSL = LightWGSL + clusteredStorageWGSL + +// ClusteredFallbackBindingsWGSL is [LightWGSL] plus the fallback uniform block at [LightGroup] binding 1 and shade_pbr_clustered with the same signature as in [ClusteredBindingsWGSL], using no storage buffers or compute, for WebGL 2 and OpenGL ES 3.0 targets. frag_pos is ignored: every uploaded light is evaluated for every fragment. +const ClusteredFallbackBindingsWGSL = LightWGSL + clusteredFallbackWGSL + +// clusterLightRadianceWGSL declares the light record both paths upload and cluster_light_radiance, the outgoing radiance one local light adds, matching clusterLightRadiance. +const clusterLightRadianceWGSL = ` +struct ClusterLightGPU { + pos_range: vec4, + color_intensity: vec4, + dir_kind: vec4, + spot_params: vec4, +} + +fn cluster_light_radiance(light: ClusterLightGPU, world_pos: vec3, n: vec3, v: vec3, base_color: vec3, metallic: f32, roughness: f32) -> vec3 { + let intensity = light.color_intensity.w; + if (light.pos_range.w <= 0.0 || intensity <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + let to_light = light.pos_range.xyz - world_pos; + let dist_sq = dot(to_light, to_light); + if (dist_sq <= 1e-12) { + return vec3(0.0, 0.0, 0.0); + } + let l = to_light / sqrt(dist_sq); + var atten = point_light_attenuation(dist_sq, light.pos_range.w); + if (light.dir_kind.w > 0.5) { + atten = atten * spot_cone_attenuation(light.dir_kind.xyz, l, light.spot_params.x, light.spot_params.y); + } + let ndotl = dot(n, l); + if (atten <= 0.0 || ndotl <= 0.0) { + return vec3(0.0, 0.0, 0.0); + } + return pbr_brdf(n, v, l, base_color, metallic, roughness) * (light.color_intensity.rgb * (intensity * atten * ndotl)); +} +` + +// clusteredStorageWGSL is the storage-buffer half of [ClusteredBindingsWGSL], after [LightWGSL]. +const clusteredStorageWGSL = clusterLightRadianceWGSL + ` +struct ClusterParams { + grid_info: vec4, + viewport_depth: vec4, + slice_depths: array, 17>, +} + +@group(1) @binding(1) var cluster_params: ClusterParams; +@group(1) @binding(2) var cluster_lights: array; +@group(1) @binding(3) var cluster_cells: array>; +@group(1) @binding(4) var cluster_indices: array; + +fn cluster_slice_depth(idx: u32) -> f32 { + let v = cluster_params.slice_depths[idx / 4u]; + let lane = idx % 4u; + if (lane == 0u) { return v.x; } + if (lane == 1u) { return v.y; } + if (lane == 2u) { return v.z; } + return v.w; +} + +fn cluster_find_slice(view_z: f32) -> u32 { + let slices = cluster_params.grid_info.z; + if (slices <= 1u) { + return 0u; + } + var lo: u32 = 0u; + var hi: u32 = slices - 1u; + for (var step: u32 = 0u; step < 6u; step = step + 1u) { + if (lo < hi) { + let mid = (lo + hi) / 2u; + if (view_z >= cluster_slice_depth(mid + 1u)) { + lo = mid + 1u; + } else { + hi = mid; + } + } + } + return min(lo, slices - 1u); +} + +fn shade_pbr_clustered(world_pos: vec3, normal: vec3, view_dir: vec3, base_color: vec3, metallic: f32, roughness: f32, frag_pos: vec4) -> vec3 { + var lo = shade_pbr(world_pos, normal, view_dir, base_color, metallic, roughness); + let tiles_x = cluster_params.grid_info.x; + let tiles_y = cluster_params.grid_info.y; + if (tiles_x == 0u || tiles_y == 0u) { + return lo; + } + let n = normalize(normal); + let v = normalize(view_dir); + let vp_w = max(cluster_params.viewport_depth.x, 1.0); + let vp_h = max(cluster_params.viewport_depth.y, 1.0); + let tx = min(u32(max(frag_pos.x, 0.0) / vp_w * f32(tiles_x)), tiles_x - 1u); + let ty = min(u32(max(frag_pos.y, 0.0) / vp_h * f32(tiles_y)), tiles_y - 1u); + let view_pos = camera.view * vec4(world_pos, 1.0); + let slice_z = cluster_find_slice(-view_pos.z); + let cell = cluster_cells[(slice_z * tiles_y + ty) * tiles_x + tx]; + for (var i: u32 = 0u; i < cell.y; i = i + 1u) { + let light_idx = cluster_indices[cell.x + i]; + lo = lo + cluster_light_radiance(cluster_lights[light_idx], world_pos, n, v, base_color, metallic, roughness); + } + return lo; +} +` + +// clusteredFallbackWGSL is the uniform-buffer half of [ClusteredFallbackBindingsWGSL], after [LightWGSL]. +const clusteredFallbackWGSL = clusterLightRadianceWGSL + ` +struct FallbackLightUniform { + info: vec4, + local: array, +} + +@group(1) @binding(1) var fallback_lights: FallbackLightUniform; + +fn shade_pbr_clustered(world_pos: vec3, normal: vec3, view_dir: vec3, base_color: vec3, metallic: f32, roughness: f32, frag_pos: vec4) -> vec3 { + var lo = shade_pbr(world_pos, normal, view_dir, base_color, metallic, roughness); + let n = normalize(normal); + let v = normalize(view_dir); + let count = min(fallback_lights.info.x, 16u); + for (var i: u32 = 0u; i < count; i = i + 1u) { + lo = lo + cluster_light_radiance(fallback_lights.local[i], world_pos, n, v, base_color, metallic, roughness); + } + return lo; +} +` + +// clusteredLitFragmentWGSL is the fragment stage of [ClusteredLitWGSL] and [ClusteredFallbackWGSL]: [LitPBRWGSL]'s, with shade_pbr_clustered in place of shade_pbr. +const clusteredLitFragmentWGSL = ` +@fragment +fn fs_main(in: PBRVertexOut) -> @location(0) vec4 { + let view_dir = normalize(camera.eye.xyz - in.world_pos * camera.eye.w); + let lit = shade_pbr_clustered( + in.world_pos, + in.world_normal, + view_dir, + pbr_draw.base_color.rgb, + pbr_draw.pbr_params.x, + pbr_draw.pbr_params.y, + in.clip, + ) + pbr_draw.emissive.rgb; + return vec4(linear_to_srgb(lit), pbr_draw.base_color.a); +} +` + +// ClusteredLitWGSL is [LitPBRWGSL] with clustered local lights: the same metallic-roughness module on [CameraWGSL], [MeshVertexLayout] and a per-draw [PBRDrawUniform] at [PBRDrawGroup], whose fragment stage shades with shade_pbr_clustered from [ClusteredBindingsWGSL] and writes sRGB. [NewClusteredLitPBRPipeline] creates a pipeline from it. +const ClusteredLitWGSL = litPBRPreludeWGSL + clusteredStorageWGSL + clusteredLitFragmentWGSL + +// ClusteredFallbackWGSL is [ClusteredLitWGSL] built on [ClusteredFallbackBindingsWGSL], for devices without storage buffers or compute. +const ClusteredFallbackWGSL = litPBRPreludeWGSL + clusteredFallbackWGSL + clusteredLitFragmentWGSL + +// NewClusteredLitPBRPipeline compiles sys's ready-made shader ([ClusteredLitWGSL] or [ClusteredFallbackWGSL]) and creates the same back-face-culled pipeline as [NewLitPBRPipeline], with sys's layout at [LightGroup] in place of a [GPULightBuffer]'s. Pass depthFormat = [gpu.FormatUndefined] when rendering without a depth attachment. +func NewClusteredLitPBRPipeline(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, sys *ClusteredLightSystem, drawLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error) { + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + if sys == nil { + return nil, fmt.Errorf("%w: nil ClusteredLightSystem", ErrInvalidClusterConfig) + } + layouts := make([]*gpu.BindGroupLayout, PBRDrawGroup+1) + layouts[CameraGroup] = camLayout + layouts[LightGroup] = sys.Layout() + layouts[PBRDrawGroup] = drawLayout + return newLitPBRPipeline(cx, dev, "render3d.clustered_lit_pbr", sys.WGSL(), layouts, MeshVertexLayout(), dev.SurfaceFormat(), depthFormat) +} + +// ClusteredLightSystem owns the whole [LightGroup] bind group for clustered forward shading: the [LightRig] uniform [LightWGSL] reads at binding 0 (ambient, directional, and the rig's own point and spot lights) and the local-light buffers at bindings 1 to 4. On devices without storage buffers or compute (WebGL 2, OpenGL ES 3.0, nsgotest.NoGPUCompute) it falls back to one uniform buffer at binding 1 holding the [ClusterConfig.FallbackMaxLights] most important visible lights. +// +// Create it once the device is ready, call [ClusteredLightSystem.Update] or [ClusteredLightSystem.UpdateCamera] each frame, and draw with [NewClusteredLitPBRPipeline] or a custom shader that prepends [CameraWGSL] and [ClusteredLightSystem.BindingsWGSL], binding the system with [ClusteredLightSystem.Bind] in place of a [GPULightBuffer]. +type ClusteredLightSystem struct { + cfg ClusterConfig + fallback bool + grid *ClusterGrid + + // GPU resources (owned by the core.Scope passed to NewClusteredLightSystem). + layout *gpu.BindGroupLayout + group *gpu.BindGroup + rigBuf *gpu.Buffer // binding 0: LightRig uniform + paramsBuf *gpu.Buffer // binding 1: clustered ClusterParams uniform, or fallback FallbackLightUniform + lightsBuf *gpu.Buffer // clustered only, binding 2: storage array + cellsBuf *gpu.Buffer // clustered only, binding 3: storage array> + indicesBuf *gpu.Buffer // clustered only, binding 4: storage array + fallbackDst []ClusterLight + fallbackTmp []scoredClusterLight + lastStats ClusterStats + + // Reusable CPU upload scratch buffers (zero steady-state allocations). + rigBytes [LightUniformSize]byte + paramsBytes [ClusterParamsUniformSize]byte + fallbackData [ClusteredFallbackUniformSize]byte + lightsBytes []byte + cellsBytes []byte + indicesBytes []byte +} + +// NewClusteredLightSystem validates cfg, inspects dev's GPU capabilities, and allocates either the storage-buffer clustered lighting path or the uniform-buffer fallback path scoped to cx. In clustered mode it returns an error wrapping [ErrInvalidClusterConfig] when the light or index storage buffer cfg needs exceeds dev's MaxStorageBufferBindingSize. +func NewClusteredLightSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig) (*ClusteredLightSystem, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + if dev == nil { + return nil, gpu.Error{Code: gpu.ErrDeviceLost, Message: "render3d: nil device"} + } + cfg = cfg.withDefaults() + + label := cfg.Label + if label == "" { + label = "render3d.clustered" + } + if cfg.ForceFallback || !DeviceSupportsClusteredLighting(dev) { + return newClusteredSystem(cx, dev, cfg, label, true) + } + return newClusteredSystem(cx, dev, cfg, label, false) +} + +func newClusteredSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig, label string, fallback bool) (*ClusteredLightSystem, error) { + s := &ClusteredLightSystem{cfg: cfg, fallback: fallback} + var lightsSize, cellsSize, indicesSize uint64 + if fallback { + s.fallbackDst = make([]ClusterLight, 0, cfg.FallbackMaxLights) + s.fallbackTmp = make([]scoredClusterLight, 0, cfg.MaxLights) + } else { + grid, err := NewClusterGrid(cfg) + if err != nil { + return nil, err + } + s.grid = grid + numClusters := uint64(cfg.ClusterCount()) + lightsSize = uint64(cfg.MaxLights) * ClusterLightGPUSize + cellsSize = numClusters * ClusterCellGPUSize + indicesSize = numClusters * uint64(cfg.MaxLightsPerCluster) * 4 + if maxBind := dev.Capabilities().Limits.MaxStorageBufferBindingSize; maxBind > 0 { + for _, b := range []struct { + name string + size uint64 + }{{"lights", lightsSize}, {"cells", cellsSize}, {"indices", indicesSize}} { + if b.size > maxBind { + return nil, fmt.Errorf("%w: %s storage buffer of %d bytes exceeds the device's MaxStorageBufferBindingSize (%d); lower MaxLights, MaxLightsPerCluster or the grid size", ErrInvalidClusterConfig, b.name, b.size, maxBind) + } + } + } + } + + var toClose []interface{ Close() error } + fail := func(err error) (*ClusteredLightSystem, error) { + for i := len(toClose) - 1; i >= 0; i-- { + _ = toClose[i].Close() + } + return nil, err + } + newBuffer := func(name string, size uint64, usage gpu.BufferUsage) (*gpu.Buffer, error) { + buf, err := dev.CreateBuffer(cx, gpu.BufferDesc{ + Label: label + " " + name, + Size: size, + Usage: usage | gpu.UsageCopyDst, + Retained: cfg.Retained, + }) + if err == nil { + toClose = append(toClose, buf) + } + return buf, err + } + + var err error + if s.rigBuf, err = newBuffer("rig", LightUniformSize, gpu.UsageUniform); err != nil { + return fail(err) + } + paramsSize := uint64(ClusterParamsUniformSize) + if fallback { + paramsSize = ClusteredFallbackUniformSize + } + if s.paramsBuf, err = newBuffer("params", paramsSize, gpu.UsageUniform); err != nil { + return fail(err) + } + layoutEntries := []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageVertex | gpu.StageFragment, Type: gpu.BindingUniform}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingUniform}, + } + groupEntries := []gpu.BindGroupEntry{ + {Binding: 0, Buffer: s.rigBuf, Size: LightUniformSize}, + {Binding: 1, Buffer: s.paramsBuf, Size: paramsSize}, + } + if !fallback { + if s.lightsBuf, err = newBuffer("lights", lightsSize, gpu.UsageStorage); err != nil { + return fail(err) + } + if s.cellsBuf, err = newBuffer("cells", cellsSize, gpu.UsageStorage); err != nil { + return fail(err) + } + if s.indicesBuf, err = newBuffer("indices", indicesSize, gpu.UsageStorage); err != nil { + return fail(err) + } + layoutEntries = append(layoutEntries, + gpu.BindGroupLayoutEntry{Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + gpu.BindGroupLayoutEntry{Binding: 3, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + gpu.BindGroupLayoutEntry{Binding: 4, Visibility: gpu.StageFragment, Type: gpu.BindingStorageRead}, + ) + groupEntries = append(groupEntries, + gpu.BindGroupEntry{Binding: 2, Buffer: s.lightsBuf, Size: lightsSize}, + gpu.BindGroupEntry{Binding: 3, Buffer: s.cellsBuf, Size: cellsSize}, + gpu.BindGroupEntry{Binding: 4, Buffer: s.indicesBuf, Size: indicesSize}, + ) + s.lightsBytes = make([]byte, lightsSize) + s.cellsBytes = make([]byte, cellsSize) + s.indicesBytes = make([]byte, indicesSize) + } + + if s.layout, err = dev.CreateBindGroupLayoutDesc(cx, gpu.BindGroupLayoutDesc{Label: label + " layout", Entries: layoutEntries}); err != nil { + return fail(err) + } + toClose = append(toClose, s.layout) + if s.group, err = dev.CreateBindGroupDesc(cx, gpu.BindGroupDesc{Label: label + " group", Layout: s.layout, Entries: groupEntries}); err != nil { + return fail(err) + } + return s, nil +} + +// IsClustered reports whether s is running the storage-buffer clustered forward shading path. +func (s *ClusteredLightSystem) IsClustered() bool { return s != nil && !s.fallback } + +// IsFallback reports whether s is running the uniform-buffer mobile / WebGL 2 / GLES 3.0 fallback path. +func (s *ClusteredLightSystem) IsFallback() bool { return s != nil && s.fallback } + +// Config returns the normalized [ClusterConfig] used to construct s. +func (s *ClusteredLightSystem) Config() ClusterConfig { + if s == nil { + return ClusterConfig{} + } + return s.cfg +} + +// Grid returns the underlying [ClusterGrid] in clustered mode, or nil in fallback mode. +func (s *ClusteredLightSystem) Grid() *ClusterGrid { + if s == nil { + return nil + } + return s.grid +} + +// Layout returns the bind group layout a pipeline lists at [LightGroup]. +func (s *ClusteredLightSystem) Layout() *gpu.BindGroupLayout { + if s == nil { + return nil + } + return s.layout +} + +// BindGroup returns the bind group a render pass sets at [LightGroup]. +func (s *ClusteredLightSystem) BindGroup() *gpu.BindGroup { + if s == nil { + return nil + } + return s.group +} + +// WGSL returns the ready-made shader matching s's active path ([ClusteredLitWGSL] or [ClusteredFallbackWGSL]). +func (s *ClusteredLightSystem) WGSL() string { + if s.IsFallback() { + return ClusteredFallbackWGSL + } + return ClusteredLitWGSL +} + +// BindingsWGSL returns the [LightGroup] declarations and shade_pbr_clustered helper matching s's active path ([ClusteredBindingsWGSL] or [ClusteredFallbackBindingsWGSL]). +func (s *ClusteredLightSystem) BindingsWGSL() string { + if s.IsFallback() { + return ClusteredFallbackBindingsWGSL + } + return ClusteredBindingsWGSL +} + +// FallbackLights returns the prioritized lights uploaded on the most recent update in fallback mode (nil in clustered mode). +func (s *ClusteredLightSystem) FallbackLights() []ClusterLight { + if s == nil || !s.fallback { + return nil + } + return s.fallbackDst +} + +// LastStats returns the [ClusterStats] from the most recent [ClusteredLightSystem.Update] or [ClusteredLightSystem.UpdateCamera] call. +func (s *ClusteredLightSystem) LastStats() ClusterStats { + if s == nil { + return ClusterStats{} + } + return s.lastStats +} + +// ByteSize returns the total GPU buffer memory owned by s, for [RenderStats] and [Budget] accounting. +func (s *ClusteredLightSystem) ByteSize() uint64 { + if s == nil { + return 0 + } + var total uint64 + for _, b := range []*gpu.Buffer{s.rigBuf, s.paramsBuf, s.lightsBuf, s.cellsBuf, s.indicesBuf} { + if b != nil { + total += b.Size() + } + } + return total +} + +// Valid reports whether s's GPU resources are open and belong to a live device. +func (s *ClusteredLightSystem) Valid() bool { + if s == nil || !s.rigBuf.Valid() || !s.paramsBuf.Valid() || !s.layout.Valid() || !s.group.Valid() { + return false + } + if s.fallback { + return true + } + return s.lightsBuf.Valid() && s.cellsBuf.Valid() && s.indicesBuf.Valid() +} + +// Bind sets s's bind group at [LightGroup] on pass, like [GPULightBuffer.Bind]. It records nothing when s is not [ClusteredLightSystem.Valid]. +func (s *ClusteredLightSystem) Bind(pass *gpu.RenderPass) { + if !s.Valid() || pass == nil { + return + } + pass.SetBindGroup(LightGroup, s.group) +} + +// Update validates rig and lights, assigns lights for the frame, and uploads the rig and the resulting light buffers to dev. viewportW and viewportH are the size of the rendered area the fragment shader's @builtin(position) covers, starting at its origin: under a [DynamicResolutionTarget] pass [DynamicResolutionTarget.ScaledSize], not the native size. +// +// It returns an error wrapping [ErrInvalidLight] for a malformed rig, or [ErrInvalidClusterLight] for a light that fails [ClusterLight.Validate] (including Range 0; see [ClusterLightFromPoint]), and uploads nothing in that case. Lights with zero intensity or color are culled. +// +// In clustered mode, lights are binned into view-space frustum clusters via [ClusterGrid.AssignLights]. In fallback mode, the top [ClusterConfig.FallbackMaxLights] visible lights are selected as [SelectFallbackLights] does; CulledLights counts lights outside the frustum or without power and TruncatedLights those dropped by the cap. Steady-state calls allocate nothing beyond the copies gpu.Device.WriteBuffer queues. +func (s *ClusteredLightSystem) Update(dev *gpu.Device, view, proj math3d.Mat4, near, far, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error) { + if s == nil { + return ClusterStats{}, nil + } + if err := rig.Validate(); err != nil { + return ClusterStats{}, err + } + for i := range lights { + if err := lights[i].Validate(); err != nil { + return ClusterStats{}, fmt.Errorf("lights[%d]: %w", i, err) + } + } + upload := dev != nil && s.Valid() + if upload { + u := packLightUniforms(rig) + u.Encode(s.rigBytes[:]) + dev.WriteBuffer(s.rigBuf, 0, s.rigBytes[:]) + } + + if s.fallback { + s.fallbackDst = selectFallbackLightsWithScratch(s.fallbackDst, &s.fallbackTmp, view, proj, lights, s.cfg.FallbackMaxLights) + stats := ClusterStats{ + InputLights: len(lights), + VisibleLights: len(s.fallbackDst), + CulledLights: len(lights) - len(s.fallbackTmp), + TruncatedLights: len(s.fallbackTmp) - len(s.fallbackDst), + } + s.lastStats = stats + if upload { + encodeFallbackUniform(&s.fallbackData, s.fallbackDst) + dev.WriteBuffer(s.paramsBuf, 0, s.fallbackData[:]) + } + return stats, nil + } + + stats := s.grid.AssignLights(view, proj, near, far, lights) + s.lastStats = stats + if !upload { + return stats, nil + } + + encodeClusterParams(&s.paramsBytes, s.cfg, uint32(len(s.grid.activeLights)), viewportW, viewportH, near, far, s.grid.SliceDepths()) + dev.WriteBuffer(s.paramsBuf, 0, s.paramsBytes[:]) + + active := s.grid.activeLights + if len(active) > 0 { + for i := range active { + encodeClusterLightGPU(s.lightsBytes[i*ClusterLightGPUSize:], active[i]) + } + dev.WriteBuffer(s.lightsBuf, 0, s.lightsBytes[:len(active)*ClusterLightGPUSize]) + } + + // Every cell holds at most MaxLightsPerCluster indices, so the packed list always fits the indices buffer. + for i, oc := range s.grid.offsets { + base := i * ClusterCellGPUSize + binary.LittleEndian.PutUint32(s.cellsBytes[base+0:], oc.Offset) + binary.LittleEndian.PutUint32(s.cellsBytes[base+4:], oc.Count) + binary.LittleEndian.PutUint32(s.cellsBytes[base+8:], 0) + binary.LittleEndian.PutUint32(s.cellsBytes[base+12:], 0) + } + dev.WriteBuffer(s.cellsBuf, 0, s.cellsBytes) + + if indices := s.grid.lightIndices; len(indices) > 0 { + for i, idx := range indices { + binary.LittleEndian.PutUint32(s.indicesBytes[i*4:], idx) + } + dev.WriteBuffer(s.indicesBuf, 0, s.indicesBytes[:len(indices)*4]) + } + return stats, nil +} + +// UpdateCamera is [ClusteredLightSystem.Update] with view, projection, near, and far taken from cam. +func (s *ClusteredLightSystem) UpdateCamera(dev *gpu.Device, cam *scene3d.Camera, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error) { + if cam == nil { + return ClusterStats{}, nil + } + near := cam.Projection.Near + far := cam.Projection.Far + if near <= 0 && cam.Projection.Kind != scene3d.ProjectionOrthographic { + near = 0.1 + } + if near == 0 && far == 0 { + near, far = 0.1, 1000 + } else if far <= near { + far = near + 1000 + } + return s.Update(dev, cam.ViewMatrix(), cam.ProjMatrix(), near, far, viewportW, viewportH, rig, lights) +} + +// Close releases all GPU resources owned by s now instead of when their scope is disposed. Safe to call on nil or more than once. +func (s *ClusteredLightSystem) Close() error { + if s == nil { + return nil + } + var err error + for _, c := range []interface{ Close() error }{s.group, s.layout, s.indicesBuf, s.cellsBuf, s.lightsBuf, s.paramsBuf, s.rigBuf} { + if c == nil { + continue + } + err = errors.Join(err, c.Close()) + } + return err +} + +func cameraPoseFromView(view math3d.Mat4) (pos, forward math3d.Vec3) { + // Camera forward in world space is -row(2) of an orthonormal view matrix; camera position is -R^T * t. + if inv, ok := view.Inverse(); ok { + pos = math3d.Vec3{X: inv[12], Y: inv[13], Z: inv[14]} + forward = math3d.Vec3{X: -inv[8], Y: -inv[9], Z: -inv[10]} + if forward.LenSq() > 1e-12 { + forward = forward.Norm() + } else { + forward = math3d.Vec3Forward() + } + return pos, forward + } + return math3d.Vec3Zero(), math3d.Vec3Forward() +} + +func encodeClusterLightGPU(dst []byte, l ClusterLight) { + dir := l.normalizedDir() + scale, offset := l.spotScaleOffset() + kind := float32(0) + if l.Kind == ClusterLightSpot { + kind = 1 + } + // vec4 pos_range + clusterPutFloat32LE(dst[0:], l.Position.X) + clusterPutFloat32LE(dst[4:], l.Position.Y) + clusterPutFloat32LE(dst[8:], l.Position.Z) + clusterPutFloat32LE(dst[12:], l.Range) + // vec4 color_intensity + clusterPutFloat32LE(dst[16:], l.Color.X) + clusterPutFloat32LE(dst[20:], l.Color.Y) + clusterPutFloat32LE(dst[24:], l.Color.Z) + clusterPutFloat32LE(dst[28:], l.Intensity) + // vec4 dir_kind + clusterPutFloat32LE(dst[32:], dir.X) + clusterPutFloat32LE(dst[36:], dir.Y) + clusterPutFloat32LE(dst[40:], dir.Z) + clusterPutFloat32LE(dst[44:], kind) + // vec4 spot_params + clusterPutFloat32LE(dst[48:], scale) + clusterPutFloat32LE(dst[52:], offset) + clusterPutFloat32LE(dst[56:], l.OuterConeCos) + clusterPutFloat32LE(dst[60:], l.InnerConeCos) +} + +func encodeClusterParams(dst *[ClusterParamsUniformSize]byte, cfg ClusterConfig, lightCount uint32, viewportW, viewportH, near, far float32, sliceDepths []float32) { + clear(dst[:]) + // grid_info: vec4 + binary.LittleEndian.PutUint32(dst[0:], uint32(cfg.TilesX)) + binary.LittleEndian.PutUint32(dst[4:], uint32(cfg.TilesY)) + binary.LittleEndian.PutUint32(dst[8:], uint32(cfg.SlicesZ)) + binary.LittleEndian.PutUint32(dst[12:], lightCount) + // viewport_depth: vec4 + clusterPutFloat32LE(dst[16:], viewportW) + clusterPutFloat32LE(dst[20:], viewportH) + clusterPutFloat32LE(dst[24:], near) + clusterPutFloat32LE(dst[28:], far) + // slice_depths: array, 17> (68 float32 slots starting at byte 32) + n := min(len(sliceDepths), MaxClusterSlicesZ+1) + for i := range n { + clusterPutFloat32LE(dst[32+i*4:], sliceDepths[i]) + } +} + +func encodeFallbackUniform(dst *[ClusteredFallbackUniformSize]byte, lights []ClusterLight) { + clear(dst[:]) + n := min(len(lights), MaxFallbackLights) + binary.LittleEndian.PutUint32(dst[0:], uint32(n)) + for i := range n { + encodeClusterLightGPU(dst[16+i*ClusterLightGPUSize:], lights[i]) + } +} + +func clusterPutFloat32LE(dst []byte, v float32) { + binary.LittleEndian.PutUint32(dst, math.Float32bits(v)) +} diff --git a/packages/game/render3d/clustered_test.go b/packages/game/render3d/clustered_test.go new file mode 100644 index 00000000..c8771f5c --- /dev/null +++ b/packages/game/render3d/clustered_test.go @@ -0,0 +1,967 @@ +package render3d_test + +import ( + "errors" + "image" + "image/color" + "math" + "testing" + "time" + + "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" +) + +var clusterTestMat = render3d.PBRMaterial{BaseColor: math3d.Vec3{X: 0.9, Y: 0.9, Z: 0.9}, Roughness: 0.6} + +func clusterTestFloorMesh(half float32) render3d.Mesh { + up := math3d.Vec3Up() + return render3d.Mesh{ + Positions: []math3d.Vec3{ + {X: -half, Y: 0, Z: half}, + {X: half, Y: 0, Z: half}, + {X: half, Y: 0, Z: -half}, + {X: -half, Y: 0, Z: -half}, + }, + Normals: []math3d.Vec3{up, up, up, up}, + UVs: []math3d.Vec2{ + {X: 0, Y: 1}, + {X: 1, Y: 1}, + {X: 1, Y: 0}, + {X: 0, Y: 0}, + }, + Indices: []uint32{0, 1, 2, 0, 2, 3}, + } +} + +func clusterTest256PointLights() []render3d.ClusterLight { + lights := make([]render3d.ClusterLight, 0, 256) + palette := [...]math3d.Vec3{ + {X: 1.0, Y: 0.25, Z: 0.15}, + {X: 0.15, Y: 1.0, Z: 0.25}, + {X: 0.2, Y: 0.35, Z: 1.0}, + {X: 1.0, Y: 0.85, Z: 0.2}, + {X: 0.9, Y: 0.25, Z: 0.95}, + {X: 0.2, Y: 0.95, Z: 0.95}, + } + // 16x16 grid spanning X in [-15, 15], Z in [-15, 15] at Y = 1.25. + for gz := range 16 { + for gx := range 16 { + idx := gz*16 + gx + x := -15.0 + float32(gx)*2.0 + z := -15.0 + float32(gz)*2.0 + lights = append(lights, render3d.NewPointClusterLight(math3d.Vec3{X: x, Y: 1.25, Z: z}, palette[idx%len(palette)], 5.5, 2.8)) + } + } + return lights +} + +// clusterTestRig is a LightRig with ambient, a dim sun and one rig point light, shaded together with the clustered lights. +func clusterTestRig() render3d.LightRig { + return render3d.LightRig{ + Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.2, Y: 0.2, Z: 0.25}, Intensity: 0.2}, + Directional: []render3d.DirectionalLight{{Direction: math3d.Vec3{X: 0.3, Y: -1, Z: -0.2}, Color: math3d.Vec3{X: 1, Y: 0.95, Z: 0.9}, Intensity: 0.3}}, + Point: []render3d.PointLight{{Position: math3d.Vec3{X: 6, Y: 2, Z: 4}, Color: math3d.Vec3{X: 0.6, Y: 0.6, Z: 1}, Intensity: 4, Range: 6}}, + } +} + +func clusterTestSRGB(lin math3d.Vec3) color.RGBA { + srgb := render3d.LinearToSRGB(lin) + return color.RGBA{ + R: uint8(math.Round(float64(srgb.X) * 255)), + G: uint8(math.Round(float64(srgb.Y) * 255)), + B: uint8(math.Round(float64(srgb.Z) * 255)), + A: 255, + } +} + +func clusterTestAssertPixelNear(t *testing.T, img *image.RGBA, x, y int, want color.RGBA, tol int, label string) { + t.Helper() + got := img.RGBAAt(x, y) + diff := func(a, b uint8) int { + d := int(a) - int(b) + if d < 0 { + return -d + } + return d + } + if diff(got.R, want.R) > tol || diff(got.G, want.G) > tol || diff(got.B, want.B) > tol || diff(got.A, want.A) > tol { + t.Errorf("%s at (%d,%d): got RGBA(%d,%d,%d,%d), want RGBA(%d,%d,%d,%d) ±%d", label, x, y, got.R, got.G, got.B, got.A, want.R, want.G, want.B, want.A, tol) + } +} + +func clusterTestAssertVecNear(t *testing.T, got, want math3d.Vec3, label string) { + t.Helper() + near := func(a, b float32) bool { return math.Abs(float64(a-b)) <= 1e-4*(1+math.Abs(float64(b))) } + if !near(got.X, want.X) || !near(got.Y, want.Y) || !near(got.Z, want.Z) { + t.Fatalf("%s: got %v, want %v", label, got, want) + } +} + +// clusterTestGPU holds the camera, per-draw and pipeline resources a clustered draw needs besides the ClusteredLightSystem. +type clusterTestGPU struct { + cam *render3d.CameraBuffer + draw *render3d.PBRDrawBuffer + pipe *gpu.Pipeline +} + +func newClusterTestGPU(t *testing.T, cx *core.Scope, dev *gpu.Device, sys *render3d.ClusteredLightSystem) clusterTestGPU { + t.Helper() + camBuf, err := render3d.NewCameraBuffer(cx, dev) + if err != nil { + t.Fatalf("NewCameraBuffer: %v", err) + } + drawBuf, err := render3d.NewPBRDrawBuffer(cx, dev, nil, render3d.NewPBRDrawUniform(math3d.Mat4Identity(), clusterTestMat), false) + if err != nil { + t.Fatalf("NewPBRDrawBuffer: %v", err) + } + pipe, err := render3d.NewClusteredLitPBRPipeline(cx, dev, camBuf.Layout(), sys, drawBuf.Layout(), gpu.FormatDepth24Plus) + if err != nil { + t.Fatalf("NewClusteredLitPBRPipeline: %v", err) + } + if cx == nil { + t.Cleanup(func() { + _ = pipe.Close() + _ = drawBuf.Close() + _ = camBuf.Close() + }) + } + return clusterTestGPU{cam: camBuf, draw: drawBuf, pipe: pipe} +} + +func (g clusterTestGPU) record(pass *gpu.RenderPass, sys *render3d.ClusteredLightSystem, mesh *render3d.GPUMesh) { + pass.SetPipeline(g.pipe) + pass.SetBindGroup(render3d.CameraGroup, g.cam.BindGroup()) + sys.Bind(pass) + pass.SetBindGroup(render3d.PBRDrawGroup, g.draw.BindGroup()) + mesh.Draw(pass) +} + +func clusterTestRenderSoftware(t *testing.T, sr *gpu.SoftwareRenderer, g clusterTestGPU, sys *render3d.ClusteredLightSystem, mesh *render3d.GPUMesh) *image.RGBA { + t.Helper() + dev := sr.Device() + enc := dev.BeginEncoder() + pass := enc.BeginRenderPass(gpu.RenderPassDesc{ + ColorAttachments: []gpu.ColorAttachment{{LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore, ClearColor: core.RGB(0x000000)}}, + DepthStencil: &gpu.DepthStencilAttachment{DepthLoadOp: gpu.LoadClear, DepthStoreOp: gpu.StoreDiscard, ClearDepth: 1}, + }) + g.record(pass, sys, mesh) + pass.End() + dev.Submit(enc.Finish()) + sr.WaitIdle() + if err := sr.LastError(); err != nil { + t.Fatalf("software renderer: %v", err) + } + return sr.Image() +} + +func clusterTestWorldPointAtPixel(cam *scene3d.Camera, px, py, w, h float32) (math3d.Vec3, bool) { + // Intersect screen ray through pixel center (px+0.5, py+0.5) with Y=0 floor plane. + ray := cam.ScreenRay(px+0.5, py+0.5, w, h) + if math.Abs(float64(ray.Dir.Y)) < 1e-6 { + return math3d.Vec3{}, false + } + t := -ray.Origin.Y / ray.Dir.Y + if t <= 0 { + return math3d.Vec3{}, false + } + return ray.At(t), true +} + +func clusterTestUpdate(t *testing.T, sys *render3d.ClusteredLightSystem, dev *gpu.Device, cam *scene3d.Camera, w, h float32, rig render3d.LightRig, lights []render3d.ClusterLight) render3d.ClusterStats { + t.Helper() + stats, err := sys.UpdateCamera(dev, cam, w, h, rig, lights) + if err != nil { + t.Fatalf("UpdateCamera: %v", err) + } + return stats +} + +func TestClusterConfigAndLightValidation(t *testing.T) { + if err := (render3d.ClusterConfig{}).Validate(); err != nil { + t.Fatalf("zero ClusterConfig should apply defaults and validate: %v", err) + } + def := render3d.DefaultClusterConfig() + if got := def.ClusterCount(); got != 16*9*24 { + t.Fatalf("DefaultClusterConfig().ClusterCount() = %d, want %d", got, 16*9*24) + } + + badConfigs := []struct { + name string + cfg render3d.ClusterConfig + }{ + {"negative TilesX", render3d.ClusterConfig{TilesX: -1}}, + {"negative TilesY", render3d.ClusterConfig{TilesY: -2}}, + {"SlicesZ too large", render3d.ClusterConfig{SlicesZ: render3d.MaxClusterSlicesZ + 1}}, + {"negative SlicesZ", render3d.ClusterConfig{SlicesZ: -1}}, + {"negative MaxLights", render3d.ClusterConfig{MaxLights: -5}}, + {"MaxLights too large", render3d.ClusterConfig{MaxLights: render3d.MaxClusterLights + 1}}, + {"negative MaxLightsPerCluster", render3d.ClusterConfig{MaxLightsPerCluster: -1}}, + {"MaxLightsPerCluster above MaxLights", render3d.ClusterConfig{MaxLights: 8, MaxLightsPerCluster: 9}}, + {"index slots overflow", render3d.ClusterConfig{TilesX: 64, TilesY: 64, SlicesZ: 64, MaxLights: 4096, MaxLightsPerCluster: 4096}}, + {"FallbackMaxLights too large", render3d.ClusterConfig{FallbackMaxLights: render3d.MaxFallbackLights + 1}}, + {"negative FallbackMaxLights", render3d.ClusterConfig{FallbackMaxLights: -1}}, + } + for _, tc := range badConfigs { + t.Run(tc.name, func(t *testing.T) { + err := tc.cfg.Validate() + if !errors.Is(err, render3d.ErrInvalidClusterConfig) { + t.Fatalf("Validate() = %v, want wrapping ErrInvalidClusterConfig", err) + } + if _, err := render3d.NewClusterGrid(tc.cfg); !errors.Is(err, render3d.ErrInvalidClusterConfig) { + t.Fatalf("NewClusterGrid() = %v, want wrapping ErrInvalidClusterConfig", err) + } + }) + } + + pt := render3d.NewPointClusterLight(math3d.Vec3{Y: 2}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 3, 5) + if err := pt.Validate(); err != nil { + t.Fatalf("valid point light failed Validate: %v", err) + } + sp := render3d.NewSpotClusterLight(math3d.Vec3{Y: 3}, math3d.Vec3{Y: -1}, math3d.Vec3{X: 1}, 2, 6, 0.2, 0.5) + if err := sp.Validate(); err != nil { + t.Fatalf("valid spot light failed Validate: %v", err) + } + + badLights := []struct { + name string + l render3d.ClusterLight + }{ + {"unknown kind", render3d.ClusterLight{Kind: 99, Range: 1, Color: math3d.Vec3{X: 1}, Intensity: 1}}, + {"zero range", render3d.NewPointClusterLight(math3d.Vec3Zero(), math3d.Vec3{X: 1}, 1, 0)}, + {"NaN pos", render3d.NewPointClusterLight(math3d.Vec3{X: float32(math.NaN())}, math3d.Vec3{X: 1}, 1, 5)}, + {"negative color", render3d.NewPointClusterLight(math3d.Vec3Zero(), math3d.Vec3{X: -0.1}, 1, 5)}, + {"negative intensity", render3d.NewPointClusterLight(math3d.Vec3Zero(), math3d.Vec3{X: 1}, -1, 5)}, + {"inverted spot cones", render3d.ClusterLight{Kind: render3d.ClusterLightSpot, Range: 5, Color: math3d.Vec3{X: 1}, Intensity: 1, Direction: math3d.Vec3{Y: -1}, InnerConeCos: 0.5, OuterConeCos: 0.8}}, + {"out of range cone cos", render3d.ClusterLight{Kind: render3d.ClusterLightSpot, Range: 5, Color: math3d.Vec3{X: 1}, Intensity: 1, Direction: math3d.Vec3{Y: -1}, InnerConeCos: 1.5, OuterConeCos: 0.5}}, + } + for _, tc := range badLights { + t.Run(tc.name, func(t *testing.T) { + if err := tc.l.Validate(); !errors.Is(err, render3d.ErrInvalidClusterLight) { + t.Fatalf("Validate() = %v, want wrapping ErrInvalidClusterLight", err) + } + }) + } +} + +func TestClusterLightFromPointAndSpotMatchLightRigAttenuation(t *testing.T) { + ranged := render3d.PointLight{Position: math3d.Vec3{X: 1, Y: 2, Z: -1}, Color: math3d.Vec3{X: 1, Y: 0.5, Z: 0.25}, Intensity: 3, Range: 5} + cl, err := render3d.ClusterLightFromPoint(ranged) + if err != nil { + t.Fatalf("ClusterLightFromPoint: %v", err) + } + if cl.Kind != render3d.ClusterLightPoint || cl.Range != 5 { + t.Fatalf("ClusterLightFromPoint = %+v, want a point light with Range 5", cl) + } + spot := render3d.SpotLight{Position: math3d.Vec3{Y: 4}, Direction: math3d.Vec3{X: 0.2, Y: -1}, Color: math3d.Vec3{X: 0.5, Y: 1, Z: 0.5}, Intensity: 8, Range: 9, InnerConeAngle: 0.2, OuterConeAngle: 0.6} + cs, err := render3d.ClusterLightFromSpot(spot) + if err != nil { + t.Fatalf("ClusterLightFromSpot: %v", err) + } + for _, p := range []math3d.Vec3{{}, {X: 0.5, Z: 0.3}, {X: 1.5, Y: 0.2, Z: -1}, {X: 3}, {X: -2, Z: 2}} { + _, got := render3d.EvaluateLightAttenuation(cl, p) + want := render3d.PointLightAttenuation(ranged.Position.Sub(p).LenSq(), ranged.Range) * ranged.Intensity + if math.Abs(float64(got-want)) > 1e-5*(1+float64(want)) { + t.Fatalf("point attenuation at %v = %v, want %v", p, got, want) + } + _, got = render3d.EvaluateLightAttenuation(cs, p) + want = spot.Attenuation(p) * spot.Intensity + if math.Abs(float64(got-want)) > 1e-5*(1+float64(want)) { + t.Fatalf("spot attenuation at %v = %v, want %v", p, got, want) + } + } + + // Range 0 is unbounded in a LightRig; the converters derive the distance where the radiance falls to ClusterRangeCutoff. + unbounded := render3d.PointLight{Position: math3d.Vec3{Y: 1}, Color: math3d.Vec3{X: 0.5, Y: 1, Z: 0.25}, Intensity: 4} + cu, err := render3d.ClusterLightFromPoint(unbounded) + if err != nil { + t.Fatalf("ClusterLightFromPoint(unbounded): %v", err) + } + if want := float32(math.Sqrt(4 * 1 / render3d.ClusterRangeCutoff)); math.Abs(float64(cu.Range-want)) > 1e-3 { + t.Fatalf("derived range = %v, want %v", cu.Range, want) + } + if err := cu.Validate(); err != nil { + t.Fatalf("converted unbounded light fails Validate: %v", err) + } + unboundedSpot := spot + unboundedSpot.Range = 0 + if c, err := render3d.ClusterLightFromSpot(unboundedSpot); err != nil || c.Range <= 0 { + t.Fatalf("ClusterLightFromSpot(unbounded) = %+v, %v; want a positive range", c, err) + } + dark, err := render3d.ClusterLightFromPoint(render3d.PointLight{Color: math3d.Vec3{X: 1}}) + if err != nil || dark.Validate() != nil { + t.Fatalf("zero-intensity light converts to %+v, %v; want a valid record", dark, err) + } + + if _, err := render3d.ClusterLightFromPoint(render3d.PointLight{Color: math3d.Vec3{X: -1}, Intensity: 1}); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("invalid point light error = %v, want ErrInvalidLight", err) + } + if _, err := render3d.ClusterLightFromSpot(render3d.SpotLight{Direction: math3d.Vec3{Y: -1}, Color: math3d.Vec3{X: 1}, Intensity: 1, InnerConeAngle: 0.5, OuterConeAngle: 0.4}); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("invalid spot light error = %v, want ErrInvalidLight", err) + } +} + +func TestClusterGridLogarithmicSlicesAndBinarySearch(t *testing.T) { + grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusterGrid: %v", err) + } + near, far := float32(0.5), float32(100.0) + proj := math3d.Perspective(math3d.DegToRad(60), 16.0/9.0, near, far) + if !grid.BuildFrustum(proj, near, far) { + t.Fatal("BuildFrustum returned false for valid perspective matrix") + } + + depths := grid.SliceDepths() + if len(depths) != render3d.DefaultClusterSlicesZ+1 { + t.Fatalf("len(SliceDepths) = %d, want %d", len(depths), render3d.DefaultClusterSlicesZ+1) + } + for s := 0; s <= render3d.DefaultClusterSlicesZ; s++ { + want := float32(float64(near) * math.Pow(float64(far)/float64(near), float64(s)/float64(render3d.DefaultClusterSlicesZ))) + if math.Abs(float64(depths[s]-want)) > 1e-4*float64(want+1) { + t.Fatalf("slice depth[%d] = %v, want %v", s, depths[s], want) + } + } + + if got := grid.SliceForDepth(near * 0.5); got != 0 { + t.Fatalf("SliceForDepth(before near) = %d, want 0", got) + } + if got := grid.SliceForDepth(far * 2.0); got != render3d.DefaultClusterSlicesZ-1 { + t.Fatalf("SliceForDepth(past far) = %d, want %d", got, render3d.DefaultClusterSlicesZ-1) + } + for s := range render3d.DefaultClusterSlicesZ { + mid := 0.5 * (depths[s] + depths[s+1]) + if got := grid.SliceForDepth(mid); got != s { + t.Fatalf("SliceForDepth(mid of slice %d = %v) = %d, want %d", s, mid, got, s) + } + } + + // Orthographic projection should also build linear depth slices cleanly. + ortho := math3d.Ortho(-10, 10, -10, 10, 0.1, 50) + if !grid.BuildFrustum(ortho, 0.1, 50) { + t.Fatal("BuildFrustum returned false for orthographic matrix") + } + orthoDepths := grid.SliceDepths() + if math.Abs(float64(orthoDepths[12]-25.05)) > 1e-3 { + t.Fatalf("ortho midpoint depth = %v, want ~25.05", orthoDepths[12]) + } +} + +func TestClusterGridCullingSpotBoundsAndZeroAllocs(t *testing.T) { + grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusterGrid: %v", err) + } + + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 2, Z: 10}, math3d.DegToRad(60), 16.0/9.0, 0.5, 50) + cam.LookAt(math3d.Vec3{Y: 0, Z: 0}, math3d.Vec3Up()) + view := cam.ViewMatrix() + proj := cam.ProjMatrix() + + // 1. Lights behind camera, beyond far plane, far off to side, or zero intensity must be culled. + culledSet := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 25}, math3d.Vec3{X: 1}, 2, 3), // behind camera + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: -70}, math3d.Vec3{X: 1}, 2, 3), // beyond far + render3d.NewPointClusterLight(math3d.Vec3{X: 90, Y: 2, Z: 0}, math3d.Vec3{X: 1}, 2, 3), // outside frustum right + render3d.NewPointClusterLight(math3d.Vec3{Y: 1, Z: 0}, math3d.Vec3{X: 1}, 0, 3), // zero intensity + } + st := grid.AssignLights(view, proj, 0.5, 50, culledSet) + if st.VisibleLights != 0 || st.CulledLights != len(culledSet) || st.ActiveClusters != 0 { + t.Fatalf("expected all lights culled, got stats %+v", st) + } + + // 2. Spot light narrow cone should occupy strictly fewer clusters than an equal-range point light. + pointAtCenter := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 0}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 2, 5), + } + spotAtCenter := []render3d.ClusterLight{ + render3d.NewSpotClusterLight(math3d.Vec3{Y: 2, Z: 0}, math3d.Vec3{Y: -1}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 2, 5, math3d.DegToRad(10), math3d.DegToRad(18)), + } + ptStats := grid.AssignLights(view, proj, 0.5, 50, pointAtCenter) + spStats := grid.AssignLights(view, proj, 0.5, 50, spotAtCenter) + if spStats.ActiveClusters == 0 || spStats.ActiveClusters >= ptStats.ActiveClusters { + t.Fatalf("expected narrow spot (%d clusters) to occupy >0 and fewer clusters than equal-range point (%d clusters)", spStats.ActiveClusters, ptStats.ActiveClusters) + } + + // 3. Light straddling the camera / near plane must still assign clusters (no false negative). + nearLight := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 2, Z: 10}, math3d.Vec3{X: 1}, 2, 4), // centered on camera + } + nearStats := grid.AssignLights(view, proj, 0.5, 50, nearLight) + if nearStats.VisibleLights != 1 || nearStats.ActiveClusters == 0 { + t.Fatalf("camera-straddling light was dropped: %+v", nearStats) + } + + // 4. Steady-state 256 lights AssignLights must perform zero heap allocations. + lights256 := clusterTest256PointLights() + grid.AssignLights(view, proj, 0.5, 50, lights256) + allocs := testing.AllocsPerRun(50, func() { + grid.AssignLights(view, proj, 0.5, 50, lights256) + }) + if allocs != 0 { + t.Fatalf("steady-state AssignLights(256 lights) allocated %.2f times/op, want 0", allocs) + } +} + +func TestClusterGridTruncationKeepsInputOrder(t *testing.T) { + cfg := render3d.ClusterConfig{TilesX: 4, TilesY: 4, SlicesZ: 4, MaxLights: 4, MaxLightsPerCluster: 2} + grid, err := render3d.NewClusterGrid(cfg) + if err != nil { + t.Fatalf("NewClusterGrid: %v", err) + } + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 2, Z: 10}, math3d.DegToRad(60), 1, 0.5, 50) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + + // Ten overlapping lights in front of the camera: the grid keeps the first four (MaxLights) and every shared cell keeps the first two of those (MaxLightsPerCluster). + lights := make([]render3d.ClusterLight, 10) + for i := range lights { + lights[i] = render3d.NewPointClusterLight(math3d.Vec3{X: float32(i) * 0.01, Y: 1}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 1, 3) + } + st := grid.AssignLights(cam.ViewMatrix(), cam.ProjMatrix(), 0.5, 50, lights) + if st.VisibleLights != 4 || st.TruncatedLights != 6 || st.CulledLights != 0 { + t.Fatalf("stats = %+v, want 4 visible, 6 truncated, 0 culled", st) + } + if st.TruncatedClusters == 0 || st.MaxClusterLights != 2 { + t.Fatalf("stats = %+v, want truncated clusters holding MaxLightsPerCluster (2) lights", st) + } + for i, l := range grid.ActiveLights() { + if l.Position != lights[i].Position { + t.Fatalf("active light %d = %v, want input light %d at %v", i, l.Position, i, lights[i].Position) + } + } + for c, oc := range grid.Offsets() { + if oc.Count > 2 { + t.Fatalf("cluster %d holds %d lights, want at most 2", c, oc.Count) + } + for _, idx := range grid.LightIndices()[oc.Offset : oc.Offset+oc.Count] { + if idx > 1 { + t.Fatalf("cluster %d holds light %d, want only the first two lights in input order", c, idx) + } + } + } +} + +// TestClustered256PointLightsParity renders a floor lit by a LightRig plus 256 clustered point lights through NewClusteredLitPBRPipeline and checks that the grid lookup misses no light and that the pixels match the CPU reference. +func TestClustered256PointLightsParity(t *testing.T) { + const ( + viewW = 128 + viewH = 96 + near = float32(0.5) + far = float32(60.0) + ) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), float32(viewW)/float32(viewH), near, far) + cam.LookAt(math3d.Vec3{X: 0, Y: 0, Z: 0}, math3d.Vec3Up()) + rig := clusterTestRig() + lights := clusterTest256PointLights() + + sr := gpu.NewSoftwareRenderer(viewW, viewH, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + + if !render3d.DeviceSupportsClusteredLighting(dev) { + t.Fatal("default SoftwareRenderer must support clustered lighting") + } + sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + t.Cleanup(func() { _ = sys.Close() }) + if !sys.IsClustered() || sys.IsFallback() { + t.Fatalf("expected clustered mode on full device, got clustered=%v fallback=%v", sys.IsClustered(), sys.IsFallback()) + } + if sys.ByteSize() == 0 { + t.Fatal("expected positive GPU ByteSize") + } + + floor, err := render3d.UploadMesh(nil, dev, clusterTestFloorMesh(20), render3d.MeshUpload{Label: "floor"}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + t.Cleanup(func() { _ = floor.Close() }) + g := newClusterTestGPU(t, nil, dev, sys) + + stats := clusterTestUpdate(t, sys, dev, cam, viewW, viewH, rig, lights) + if stats.InputLights != 256 { + t.Fatalf("InputLights = %d, want 256", stats.InputLights) + } + if stats.VisibleLights < 100 || stats.ActiveClusters == 0 || stats.TruncatedLights != 0 || stats.TruncatedClusters != 0 { + t.Fatalf("expected >= 100 visible lights in active clusters with no truncation, got %+v", stats) + } + + g.cam.WriteCamera(cam) + img := clusterTestRenderSoftware(t, sr, g, sys, floor) + + view := cam.ViewMatrix() + proj := cam.ProjMatrix() + up := math3d.Vec3Up() + litSamples := 0 + for sy := 24; sy <= 80; sy += 14 { + for sx := 20; sx <= 108; sx += 14 { + worldPt, ok := clusterTestWorldPointAtPixel(cam, float32(sx), float32(sy), viewW, viewH) + if !ok || math.Abs(float64(worldPt.X)) > 19 || math.Abs(float64(worldPt.Z)) > 19 { + continue + } + viewDir := cam.Pos.Sub(worldPt) + direct := render3d.ShadeClusteredPoint(worldPt, up, viewDir, clusterTestMat, rig, lights) + clustered := render3d.ShadeClusteredGridPoint(worldPt, up, viewDir, clusterTestMat, rig, sys.Grid(), view, proj, viewW, viewH) + clusterTestAssertVecNear(t, clustered, direct, "grid lookup vs brute force") + want := clusterTestSRGB(direct) + clusterTestAssertPixelNear(t, img, sx, sy, want, 3, "clustered-256") + if base := clusterTestSRGB(render3d.ShadePoint(worldPt, up, viewDir, clusterTestMat, rig)); int(want.R)+int(want.G)+int(want.B) > int(base.R)+int(base.G)+int(base.B)+30 { + litSamples++ + } + } + } + if litSamples < 10 { + t.Fatalf("expected at least 10 samples visibly lit by clustered lights, got %d", litSamples) + } +} + +func TestClusteredMixedPointAndSpotLightsGPU(t *testing.T) { + const ( + viewW = 96 + viewH = 96 + near = float32(0.5) + far = float32(40.0) + ) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 10, Z: 10}, math3d.DegToRad(50), 1, near, far) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + rig := render3d.LightRig{Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, Intensity: 0.02}} + + spot, err := render3d.ClusterLightFromSpot(render3d.SpotLight{ + Position: math3d.Vec3{X: 3, Y: 3}, Direction: math3d.Vec3{Y: -1}, Color: math3d.Vec3{X: 0.1, Y: 1, Z: 0.1}, + Intensity: 24, Range: 7, InnerConeAngle: math3d.DegToRad(15), OuterConeAngle: math3d.DegToRad(25), + }) + if err != nil { + t.Fatalf("ClusterLightFromSpot: %v", err) + } + lights := []render3d.ClusterLight{ + // Red point light on the left. + render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.1, Z: 0.1}, 5.0, 4.5), + // Green downward spot light on the right with a 15 to 25 degree cone. + spot, + // Blue spot light at the center aiming up, away from the floor: it must add nothing. + render3d.NewSpotClusterLight(math3d.Vec3{X: 0, Y: 2, Z: 0}, math3d.Vec3{Y: 1}, math3d.Vec3{X: 0.1, Y: 0.2, Z: 1}, 30.0, 8.0, math3d.DegToRad(20), math3d.DegToRad(35)), + } + + sr := gpu.NewSoftwareRenderer(viewW, viewH, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.DefaultClusterConfig()) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + t.Cleanup(func() { _ = sys.Close() }) + floor, err := render3d.UploadMesh(nil, dev, clusterTestFloorMesh(10), render3d.MeshUpload{}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + t.Cleanup(func() { _ = floor.Close() }) + g := newClusterTestGPU(t, nil, dev, sys) + + clusterTestUpdate(t, sys, dev, cam, viewW, viewH, rig, lights) + g.cam.WriteCamera(cam) + img := clusterTestRenderSoftware(t, sr, g, sys, floor) + + up := math3d.Vec3Up() + checks := []struct { + name string + world math3d.Vec3 + }{ + {"under-red-point", math3d.Vec3{X: -3, Y: 0, Z: 0}}, + {"under-green-spot-center", math3d.Vec3{X: 3, Y: 0, Z: 0}}, + {"green-spot-penumbra", math3d.Vec3{X: 3 + 1.05, Y: 0, Z: 0}}, + {"outside-green-spot-cone", math3d.Vec3{X: 3 + 2.5, Y: 0, Z: 0}}, + {"under-upward-blue-spot", math3d.Vec3{X: 0, Y: 0, Z: 0}}, + } + for _, ch := range checks { + scr, _, vis := cam.WorldToScreen(ch.world, viewW, viewH) + if !vis { + t.Fatalf("%s not visible on screen", ch.name) + } + px, py := int(scr.X), int(scr.Y) + exactWorld, ok := clusterTestWorldPointAtPixel(cam, float32(px), float32(py), viewW, viewH) + if !ok { + t.Fatalf("%s failed raycast", ch.name) + } + want := clusterTestSRGB(render3d.ShadeClusteredPoint(exactWorld, up, cam.Pos.Sub(exactWorld), clusterTestMat, rig, lights)) + clusterTestAssertPixelNear(t, img, px, py, want, 3, ch.name) + + switch ch.name { + case "under-red-point": + if want.R < 150 || 2*int(want.G) > int(want.R) { + t.Fatalf("expected bright red under point light, got %+v", want) + } + case "under-green-spot-center": + if want.G < 150 || 2*int(want.R) > int(want.G) { + t.Fatalf("expected bright green under spot light, got %+v", want) + } + case "under-upward-blue-spot": + if want.B > 50 { + t.Fatalf("upward spot light should not light the floor, got %+v", want) + } + } + } +} + +func TestClusteredUpdateRejectsInvalidLights(t *testing.T) { + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + dev := sr.Device() + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 4, Z: 6}, math3d.DegToRad(50), 1, 0.5, 40) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + for _, force := range []bool{false, true} { + sys, err := render3d.NewClusteredLightSystem(nil, dev, render3d.ClusterConfig{ForceFallback: force}) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + // Range 0 is unbounded in a LightRig, so the clustered system refuses it instead of dropping it silently. + unbounded := render3d.NewPointClusterLight(math3d.Vec3{Y: 1}, math3d.Vec3{X: 1, Y: 1, Z: 1}, 2, 0) + if _, err := sys.UpdateCamera(dev, cam, 16, 16, render3d.LightRig{}, []render3d.ClusterLight{unbounded}); !errors.Is(err, render3d.ErrInvalidClusterLight) { + t.Fatalf("fallback=%v: Update with a Range 0 light = %v, want ErrInvalidClusterLight", force, err) + } + badRig := render3d.LightRig{Ambient: render3d.AmbientLight{Intensity: -1}} + if _, err := sys.UpdateCamera(dev, cam, 16, 16, badRig, nil); !errors.Is(err, render3d.ErrInvalidLight) { + t.Fatalf("fallback=%v: Update with a malformed rig = %v, want ErrInvalidLight", force, err) + } + converted, err := render3d.ClusterLightFromPoint(render3d.PointLight{Position: math3d.Vec3{Y: 1}, Color: math3d.Vec3{X: 1, Y: 1, Z: 1}, Intensity: 2}) + if err != nil { + t.Fatalf("ClusterLightFromPoint: %v", err) + } + st, err := sys.UpdateCamera(dev, cam, 16, 16, render3d.LightRig{}, []render3d.ClusterLight{converted}) + if err != nil || st.VisibleLights != 1 { + t.Fatalf("fallback=%v: Update with a converted unbounded light = %+v, %v; want 1 visible light", force, st, err) + } + _ = sys.Close() + } +} + +func TestClusteredFallbackNoGPUComputeAndForceFallback(t *testing.T) { + const ( + viewW = 64 + viewH = 64 + near = float32(0.5) + far = float32(60.0) + ) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), 1, near, far) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + rig := clusterTestRig() + // 256 point lights across the floor plus bright foreground lights near the center so every mode visibly lights the sampled pixels. + lights := clusterTest256PointLights() + lights[0] = render3d.NewPointClusterLight(math3d.Vec3{X: 0, Y: 1.5, Z: 0}, math3d.Vec3{X: 1, Y: 0.3, Z: 0.2}, 18.0, 6.0) + lights[1] = render3d.NewPointClusterLight(math3d.Vec3{X: -3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 1, Z: 0.3}, 18.0, 6.0) + lights[2] = render3d.NewPointClusterLight(math3d.Vec3{X: 3, Y: 1.5, Z: 1}, math3d.Vec3{X: 0.2, Y: 0.4, Z: 1}, 18.0, 6.0) + + modes := []struct { + name string + cfg render3d.ClusterConfig + appOpts []nsgotest.Option + wantCluster bool + wantCaps bool + }{ + {name: "full-clustered", cfg: render3d.DefaultClusterConfig(), wantCluster: true, wantCaps: true}, + {name: "webgl2-gles3-no-compute-fallback", cfg: render3d.DefaultClusterConfig(), appOpts: []nsgotest.Option{nsgotest.NoGPUCompute()}}, + {name: "force-fallback-on-full-device", cfg: render3d.ClusterConfig{ForceFallback: true, FallbackMaxLights: 8}, wantCaps: true}, + } + + for _, m := range modes { + t.Run(m.name, func(t *testing.T) { + var ( + sys *render3d.ClusteredLightSystem + floor *render3d.GPUMesh + g clusterTestGPU + gotCaps bool + gotStats render3d.ClusterStats + ) + opts := append([]nsgotest.Option{nsgotest.Size(viewW, viewH), nsgotest.ManualFrames()}, m.appOpts...) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "cluster-view", + Style: core.Style{Width: core.Pt(viewW), Height: core.Pt(viewH)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(dev *gpu.Device) { + gotCaps = render3d.DeviceSupportsClusteredLighting(dev) + var err error + sys, err = render3d.NewClusteredLightSystem(cx, dev, m.cfg) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + floor, err = render3d.UploadMesh(cx, dev, clusterTestFloorMesh(20), render3d.MeshUpload{}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + g = newClusterTestGPU(t, cx, dev, sys) + }, + OnFrame: func(frame *gpu.Frame) { + dev := frame.Device() + g.cam.WriteCamera(cam) + gotStats = clusterTestUpdate(t, sys, dev, cam, viewW, viewH, rig, lights) + pass := frame.BeginRenderPass(gpu.RenderPassDesc{}) + pass.ClearColor(core.RGB(0x050608)) + pass.ClearDepth(1) + g.record(pass, sys, floor) + pass.End() + frame.Submit() + }, + }) + }, opts...) + + app.Advance(16 * time.Millisecond) + + if gotCaps != m.wantCaps { + t.Fatalf("DeviceSupportsClusteredLighting = %v, want %v", gotCaps, m.wantCaps) + } + if sys.IsClustered() != m.wantCluster || sys.IsFallback() == m.wantCluster { + t.Fatalf("mode mismatch: IsClustered=%v IsFallback=%v, wantCluster=%v", sys.IsClustered(), sys.IsFallback(), m.wantCluster) + } + + img, err := app.GPUReadPixels("id:cluster-view") + if err != nil { + t.Fatalf("GPUReadPixels: %v", err) + } + + refLights := lights + if sys.IsFallback() { + wantCap := m.cfg.FallbackMaxLights + if wantCap == 0 { + wantCap = render3d.DefaultFallbackMaxLights + } + refLights = sys.FallbackLights() + if len(refLights) != wantCap || gotStats.VisibleLights != wantCap { + t.Fatalf("fallback selected %d lights, want %d (stats=%+v)", len(refLights), wantCap, gotStats) + } + if gotStats.TruncatedLights == 0 || gotStats.CulledLights+gotStats.TruncatedLights+gotStats.VisibleLights != 256 { + t.Fatalf("fallback stats %+v must split 256 lights into culled, truncated and visible with some truncated", gotStats) + } + } + + up := math3d.Vec3Up() + litCount := 0 + for _, pt := range [][2]int{{22, 32}, {32, 32}, {42, 32}, {32, 42}} { + worldPt, ok := clusterTestWorldPointAtPixel(cam, float32(pt[0]), float32(pt[1]), viewW, viewH) + if !ok { + continue + } + want := clusterTestSRGB(render3d.ShadeClusteredPoint(worldPt, up, cam.Pos.Sub(worldPt), clusterTestMat, rig, refLights)) + clusterTestAssertPixelNear(t, img, pt[0], pt[1], want, 3, m.name) + if want.R > 120 || want.G > 120 || want.B > 120 { + litCount++ + } + } + if litCount == 0 { + t.Fatalf("%s: expected visibly lit pixels above ambient/clear", m.name) + } + }) + } +} + +func TestClusteredFallbackUpdateZeroAllocs(t *testing.T) { + sr := gpu.NewSoftwareRenderer(16, 16, gpu.FormatDepth24Plus) + t.Cleanup(sr.Close) + sys, err := render3d.NewClusteredLightSystem(nil, sr.Device(), render3d.ClusterConfig{ForceFallback: true}) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + t.Cleanup(func() { _ = sys.Close() }) + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Y: 14, Z: 18}, math3d.DegToRad(50), 16.0/9.0, 0.5, 60) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + view, proj := cam.ViewMatrix(), cam.ProjMatrix() + rig := clusterTestRig() + lights := clusterTest256PointLights() + update := func() { + if _, err := sys.Update(nil, view, proj, 0.5, 60, 1280, 720, rig, lights); err != nil { + t.Fatalf("Update: %v", err) + } + } + update() + if allocs := testing.AllocsPerRun(50, update); allocs != 0 { + t.Fatalf("steady-state fallback Update(256 lights) allocated %.2f times/op, want 0", allocs) + } +} + +func TestClusteredEmptyLightsResizeRetainedAndClose(t *testing.T) { + if _, err := render3d.NewClusteredLightSystem(nil, nil, render3d.DefaultClusterConfig()); err == nil { + t.Fatal("expected error for nil device") + } + var nilSys *render3d.ClusteredLightSystem + if nilSys.Valid() || nilSys.IsClustered() || nilSys.IsFallback() || nilSys.ByteSize() != 0 { + t.Fatal("nil ClusteredLightSystem returned unexpected non-zero state") + } + if err := nilSys.Close(); err != nil { + t.Fatalf("nil Close: %v", err) + } + + profiles := []struct { + name string + opts []nsgotest.Option + }{ + {"full", nil}, + {"webgl2-gles3", []nsgotest.Option{nsgotest.NoGPUCompute()}}, + } + for _, prof := range profiles { + t.Run(prof.name, func(t *testing.T) { + const size = 48 + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 6, Z: 6}, math3d.DegToRad(50), 1, 0.5, 40) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + rig := render3d.LightRig{Ambient: render3d.AmbientLight{Color: math3d.Vec3{X: 0.2, Y: 0.3, Z: 0.4}, Intensity: 1}} + activeLights := []render3d.ClusterLight{} + + var ( + sys *render3d.ClusteredLightSystem + floor *render3d.GPUMesh + g clusterTestGPU + ) + opts := append([]nsgotest.Option{nsgotest.Size(size, size), nsgotest.ManualFrames()}, prof.opts...) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return gpu.View(cx, gpu.ViewProps{ + TestID: "ret-view", + Style: core.Style{Width: core.Pt(size), Height: core.Pt(size)}, + DepthFormat: gpu.FormatDepth24Plus, + OnReady: func(dev *gpu.Device) { + var err error + if sys == nil { + cfg := render3d.DefaultClusterConfig() + cfg.Retained = true + sys, err = render3d.NewClusteredLightSystem(cx, dev, cfg) + if err != nil { + t.Fatalf("NewClusteredLightSystem: %v", err) + } + floor, err = render3d.UploadMesh(cx, dev, clusterTestFloorMesh(10), render3d.MeshUpload{Retained: true}) + if err != nil { + t.Fatalf("UploadMesh: %v", err) + } + } + g = newClusterTestGPU(t, cx, dev, sys) + }, + OnFrame: func(frame *gpu.Frame) { + dev := frame.Device() + w, h := dev.SurfaceSize() + cam.SetViewport(float32(w), float32(h)) + g.cam.WriteCamera(cam) + clusterTestUpdate(t, sys, dev, cam, float32(w), float32(h), rig, activeLights) + pass := frame.BeginRenderPass(gpu.RenderPassDesc{}) + pass.ClearColor(core.RGB(0x000000)) + pass.ClearDepth(1) + g.record(pass, sys, floor) + pass.End() + frame.Submit() + }, + }) + }, opts...) + + // Frame 1: no local lights, so only the rig's ambient term lights the floor. + app.Advance(16 * time.Millisecond) + img, err := app.GPUReadPixels("id:ret-view") + if err != nil { + t.Fatalf("GPUReadPixels empty: %v", err) + } + ambientOnly := render3d.ShadeClusteredPoint(math3d.Vec3Zero(), math3d.Vec3Up(), cam.Pos, clusterTestMat, rig, nil) + clusterTestAssertPixelNear(t, img, size/2, size/2, clusterTestSRGB(ambientOnly), 3, "empty-ambient") + + // Frame 2: add a bright yellow light above the origin. + activeLights = []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Y: 1.5}, math3d.Vec3{X: 1, Y: 0.9, Z: 0.1}, 12.0, 6.0), + } + app.Advance(16 * time.Millisecond) + beforeLoss, err := app.GPUReadPixels("id:ret-view") + if err != nil { + t.Fatalf("GPUReadPixels before loss: %v", err) + } + centerBefore := beforeLoss.RGBAAt(size/2, size/2) + if centerBefore.R < 150 || centerBefore.G < 150 { + t.Fatalf("expected bright yellow center before loss, got %+v", centerBefore) + } + + // Lose and restore the device: the retained ClusteredLightSystem must recover. + firstSys := sys + app.TriggerGPUDeviceLost("id:ret-view", nsgotest.GPULostContextLost, "context lost") + if firstSys.Valid() { + t.Fatal("ClusteredLightSystem still Valid while device is lost") + } + app.RestoreGPUDevice("id:ret-view") + if sys != firstSys || !firstSys.Valid() { + t.Fatalf("retained ClusteredLightSystem not restored: same=%v valid=%v", sys == firstSys, firstSys.Valid()) + } + + app.Advance(16 * time.Millisecond) + afterRestore, err := app.GPUReadPixels("id:ret-view") + if err != nil { + t.Fatalf("GPUReadPixels after restore: %v", err) + } + clusterTestAssertPixelNear(t, afterRestore, size/2, size/2, centerBefore, 2, "after-restore") + + if err := sys.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if sys.Valid() { + t.Fatal("ClusteredLightSystem still Valid after Close") + } + if err := sys.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + }) + } +} + +func TestSelectFallbackLightsPrioritization(t *testing.T) { + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{Z: 10}, math3d.DegToRad(60), 1, 0.5, 100) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + lights := []render3d.ClusterLight{ + render3d.NewPointClusterLight(math3d.Vec3{Z: 20}, math3d.Vec3{X: 1}, 2, 3), // behind the camera + render3d.NewPointClusterLight(math3d.Vec3{Z: 5}, math3d.Vec3{Y: 1}, 5, 6), // closest and bright in front + render3d.NewPointClusterLight(math3d.Vec3{Z: -30}, math3d.Vec3{Z: 1}, 1, 3), // far in front + render3d.NewPointClusterLight(math3d.Vec3{Z: 4}, math3d.Vec3{X: 1}, 0, 5), // no power + render3d.NewPointClusterLight(math3d.Vec3{Z: 6}, math3d.Vec3{X: 1}, 3, 6), // second best in front + render3d.NewPointClusterLight(math3d.Vec3{X: 60, Z: 8}, math3d.Vec3{X: 1}, 500, 6), // brightest of all, but off screen to the side + } + picked := render3d.SelectFallbackLights(nil, cam.ViewMatrix(), cam.ProjMatrix(), lights, 2) + if len(picked) != 2 { + t.Fatalf("picked %d lights, want 2", len(picked)) + } + if picked[0].Position.Z != 5 || picked[1].Position.Z != 6 { + t.Fatalf("picked %+v, want the visible lights at Z=5 then Z=6", picked) + } + all := render3d.SelectFallbackLights(nil, cam.ViewMatrix(), cam.ProjMatrix(), lights, 16) + if len(all) != 3 { + t.Fatalf("picked %d lights with room for 16, want the 3 visible powered lights: %+v", len(all), all) + } +} + +// BenchmarkClusterAssign256Lights measures the CPU side of clustering 256 lights per frame, which a 60 FPS desktop frame must fit in well under 16 ms. +func BenchmarkClusterAssign256Lights(b *testing.B) { + grid, err := render3d.NewClusterGrid(render3d.DefaultClusterConfig()) + if err != nil { + b.Fatalf("NewClusterGrid: %v", err) + } + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), 16.0/9.0, 0.5, 60) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + view := cam.ViewMatrix() + proj := cam.ProjMatrix() + lights := clusterTest256PointLights() + + grid.AssignLights(view, proj, 0.5, 60, lights) + + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + grid.AssignLights(view, proj, 0.5, 60, lights) + } +} + +func BenchmarkClusterFallbackSelect256Lights(b *testing.B) { + cam := scene3d.NewPerspectiveCamera(math3d.Vec3{X: 0, Y: 14, Z: 18}, math3d.DegToRad(50), 16.0/9.0, 0.5, 60) + cam.LookAt(math3d.Vec3Zero(), math3d.Vec3Up()) + view, proj := cam.ViewMatrix(), cam.ProjMatrix() + lights := clusterTest256PointLights() + dst := make([]render3d.ClusterLight, 0, render3d.DefaultFallbackMaxLights) + + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + dst = render3d.SelectFallbackLights(dst, view, proj, lights, render3d.DefaultFallbackMaxLights) + } +}