Skip to main content

sgl_3d/content/
baked_specular_probe.rs

1//! Caller-authored static specular probes: local image-based lighting with
2//! parallax-corrected cubemaps (Lagarde and Zanuttini, SIGGRAPH 2012), as
3//! HDRP, Unreal, Godot, Wicked and Bevy use under screen-space reflections.
4//! Each probe is a prefiltered cube with an influence box, where receivers use
5//! it, and an optional proxy box, which corrects parallax. Capture is a
6//! blocking authoring operation; installing a collection only uploads it.
7use glam::{Mat4, Vec3};
8
9/// Probes in one installed collection: Wicked Engine's per-frame entity array
10/// (SHADER_ENTITY_COUNT in ShaderInterop_Renderer.h, commit 4323a33), which
11/// its tiled culling walks as eight 32-entity buckets. Wicked, Godot and Bevy
12/// fill that array each frame from the probes a CPU frustum pass finds
13/// visible; SGL3D installs the whole collection as the array instead, and the
14/// per-tile frustum and depth test (probe_culling.wgsl) does that culling.
15/// Every probe stays resident in one cube array, as Unreal's reflection
16/// captures do, so the device's array layers bound it too.
17pub(crate) const MAX_PROBES: usize = 256;
18
19/// Mip levels of a prefiltered probe: perceptual roughness 0, 1/6, ..., 1.
20pub(crate) const LEVELS: u32 = 7;
21
22/// An axis-aligned box in a probe's local frame.
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct SpecularProbeBox {
25    pub min: Vec3,
26    pub max: Vec3,
27}
28
29/// A GGX-prefiltered cube: perceptual roughness level/6 at mip `level`, seven
30/// levels from `face_size` down. `texels` run level-major, then the six faces
31/// in WebGPU cube order, then rows. Faces follow the capture views' Z-mirrored
32/// convention.
33#[derive(Clone, Debug)]
34pub struct SpecularProbeRadiance {
35    pub face_size: u32,
36    pub texels: SpecularProbeTexels,
37}
38
39/// A probe's stored radiance.
40#[derive(Clone, Debug)]
41pub enum SpecularProbeTexels {
42    /// RGBA texels, each u16 an IEEE-754 binary16 value, as captures return.
43    Rgba16Float(Vec<u16>),
44    /// BC6H unsigned-float blocks, 16 bytes per 4x4 texels (a level smaller
45    /// than a block takes one), as engines ship probes: an eighth of the size
46    /// on disk and in memory. Installing them needs
47    /// `wgpu::Features::TEXTURE_COMPRESSION_BC`.
48    Bc6hUfloat(Vec<u8>),
49}
50
51impl SpecularProbeTexels {
52    pub(crate) fn bytes(&self) -> &[u8] {
53        match self {
54            Self::Rgba16Float(texels) => bytemuck::cast_slice(texels),
55            Self::Bc6hUfloat(blocks) => blocks,
56        }
57    }
58
59    /// Its texel values: unsigned BC6H decodes only finite, nonnegative
60    /// binary16 values.
61    pub(crate) fn validate_radiance(&self) -> Result<(), ProbeError> {
62        if let Self::Rgba16Float(values) = self {
63            for (component, &value) in values.iter().enumerate() {
64                // Reject infinities/NaNs and negative values, accepting signed zero.
65                if value & 0x7c00 == 0x7c00 || (value & 0x8000 != 0 && value & 0x7fff != 0) {
66                    return Err(ProbeError::InvalidRadiance { component });
67                }
68            }
69        }
70        Ok(())
71    }
72}
73
74/// One probe of a collection.
75#[derive(Clone, Debug)]
76pub struct BakedSpecularProbe {
77    /// Capture position.
78    pub center: Vec3,
79    /// Rigid world-to-local transform of the influence and proxy boxes.
80    pub world_to_local: Mat4,
81    /// Receivers inside use this probe. Its weight is one `blend` (per local
82    /// axis) inside each face, falling linearly to zero at the face; zero on
83    /// an axis is a hard edge. Overlapping probes are normalised by their
84    /// total weight, and where the total is below one the sky fills the rest.
85    pub influence: SpecularProbeBox,
86    pub blend: Vec3,
87    /// The geometry the capture sees, for box-projected parallax. It may
88    /// extend well beyond the influence (a corridor's whole length). `None`
89    /// treats what the probe sees as distant, as for open outdoor spaces.
90    pub proxy: Option<SpecularProbeBox>,
91    pub radiance: SpecularProbeRadiance,
92}
93
94/// Invalid caller data or failure of the explicit GPU authoring operation.
95#[derive(Debug)]
96pub enum ProbeError {
97    InvalidProbe(&'static str),
98    InvalidDimensions,
99    InvalidPayloadLength { expected: usize, actual: usize },
100    InvalidRadiance { component: usize },
101    MixedRadiance,
102    CompressionUnsupported,
103    TooManyProbes,
104    Readback(String),
105}
106
107impl std::fmt::Display for ProbeError {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        match self {
110            Self::InvalidProbe(reason) => write!(f, "invalid specular probe: {reason}"),
111            Self::InvalidDimensions => write!(
112                f,
113                "specular probe faces must be a power of two from 64 within device limits"
114            ),
115            Self::InvalidPayloadLength { expected, actual } => write!(
116                f,
117                "specular probe radiance requires {expected} bytes, received {actual}"
118            ),
119            Self::InvalidRadiance { component } => write!(
120                f,
121                "specular probe component {component} is negative or non-finite"
122            ),
123            Self::MixedRadiance => write!(
124                f,
125                "a collection's probes share one face size and texel encoding"
126            ),
127            Self::CompressionUnsupported => write!(
128                f,
129                "BC6H specular probes need wgpu::Features::TEXTURE_COMPRESSION_BC"
130            ),
131            Self::TooManyProbes => write!(
132                f,
133                "a collection holds at most {MAX_PROBES} probes within the device's array layers"
134            ),
135            Self::Readback(reason) => {
136                write!(f, "static specular capture readback failed: {reason}")
137            }
138        }
139    }
140}
141impl std::error::Error for ProbeError {}
142
143fn validate_box(b: SpecularProbeBox, what: &'static str) -> Result<(), ProbeError> {
144    if !b.min.is_finite() || !(b.max - b.min).is_finite() || !b.min.cmplt(b.max).all() {
145        return Err(ProbeError::InvalidProbe(what));
146    }
147    Ok(())
148}
149
150impl BakedSpecularProbe {
151    /// Its position, transform, influence, blend and proxy.
152    pub(crate) fn validate_placement(&self) -> Result<(), ProbeError> {
153        let m = self.world_to_local;
154        if !self.center.is_finite() || !m.is_finite() {
155            return Err(ProbeError::InvalidProbe("coordinates must be finite"));
156        }
157        let axes = [
158            m.x_axis.truncate(),
159            m.y_axis.truncate(),
160            m.z_axis.truncate(),
161        ];
162        let affine = Vec3::new(m.x_axis.w, m.y_axis.w, m.z_axis.w);
163        if affine.abs().max_element() > 1e-5
164            || (m.w_axis.w - 1.).abs() > 1e-5
165            || axes
166                .iter()
167                .any(|axis| (axis.length_squared() - 1.).abs() > 1e-4)
168            || axes[0].dot(axes[1]).abs() > 1e-4
169            || axes[0].dot(axes[2]).abs() > 1e-4
170            || axes[1].dot(axes[2]).abs() > 1e-4
171            || (m.determinant() - 1.).abs() > 1e-4
172        {
173            return Err(ProbeError::InvalidProbe(
174                "transform must be a rigid rotation and translation",
175            ));
176        }
177        validate_box(
178            self.influence,
179            "influence must have positive, finite extent",
180        )?;
181        if !self.blend.is_finite() || self.blend.min_element() < 0. {
182            return Err(ProbeError::InvalidProbe(
183                "blend distances must be finite and nonnegative",
184            ));
185        }
186        if let Some(proxy) = self.proxy {
187            validate_box(proxy, "proxy must have positive, finite extent")?;
188            let local = m.transform_point3(self.center);
189            if !local.cmpge(proxy.min).all() || !local.cmple(proxy.max).all() {
190                return Err(ProbeError::InvalidProbe(
191                    "capture center must lie inside the proxy",
192                ));
193            }
194        }
195        Ok(())
196    }
197}