From 44d95ef00e088af57bb1bb001de8810f4c98c91e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:00:48 -0800 Subject: [PATCH 1/3] craft-pbr: shading functions as WGSL text for apps' shaders SHADE_WGSL (src/shade.wgsl) holds the WGSL counterparts of the crate's BRDF, environment BRDF, equirect mapping and SH9 irradiance, plus the split-sum environment light, taken from EffectCraft's Advanced 3D shader. The text declares no bindings or entry points and has no loops; an app joins its own declarations, the text and its entry points into one module. GpuMaterial and GpuSh9 lay out the PbrMaterial and PbrSh9 structs it reads, and GpuSh9::try_new rejects coefficients that are not finite or are over 1e30, so the f32 irradiance sum stays finite. The WGSL follows the Rust functions where they differ from EffectCraft's shader: the 0.032 roughness floor, 0 for a view opposite the light, and the clamped environment fit. The README lists each function next to its Rust counterpart and every change from that shader. naga 30.0.1 with wgsl-in is a dev dependency: tests parse and validate the text alone and joined with app bindings and vs and fs entry points, and check the struct layouts against the bytes. The default build does not depend on naga or wgpu. --- Cargo.lock | 1 + crates/pbr/Cargo.toml | 2 + crates/pbr/README.md | 72 ++++++++++++ crates/pbr/src/lib.rs | 5 + crates/pbr/src/shade.wgsl | 204 ++++++++++++++++++++++++++++++++ crates/pbr/src/wgsl.rs | 110 ++++++++++++++++++ crates/pbr/tests/it/main.rs | 1 + crates/pbr/tests/it/wgsl.rs | 224 ++++++++++++++++++++++++++++++++++++ 8 files changed, 619 insertions(+) create mode 100644 crates/pbr/src/shade.wgsl create mode 100644 crates/pbr/src/wgsl.rs create mode 100644 crates/pbr/tests/it/wgsl.rs diff --git a/Cargo.lock b/Cargo.lock index 864adb9fb1..48f51526fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2816,6 +2816,7 @@ dependencies = [ "craft-pbr", "craft-texture", "glam 0.30.10", + "naga", "rayon", "thiserror 2.0.21", ] diff --git a/crates/pbr/Cargo.toml b/crates/pbr/Cargo.toml index 5be5e44567..654a7c93b8 100644 --- a/crates/pbr/Cargo.toml +++ b/crates/pbr/Cargo.toml @@ -23,4 +23,6 @@ thiserror = { workspace = true } craft-pbr = { path = ".", features = ["parallel"] } # The differential tests run verbatim copies of the apps' previous code, which uses glam and rayon. glam = "0.30" +# Parses and validates the WGSL text of `SHADE_WGSL`. +naga = { version = "30.0.1", features = ["wgsl-in"] } rayon = { workspace = true } diff --git a/crates/pbr/README.md b/crates/pbr/README.md index dd66e52d9b..511641038a 100644 --- a/crates/pbr/README.md +++ b/crates/pbr/README.md @@ -92,6 +92,78 @@ It has no UI, does no file or network I/O and has no `unsafe` code. On a 256 × 128 source, the default `try_prefilter` evaluates 1,396,736 samples (10,912 output pixels in levels 1 to 5, 128 samples each). +## WGSL + +`SHADE_WGSL` is the WGSL text of the shading functions (`src/shade.wgsl`). It declares no +bindings and no entry points, and every name in it starts with `pbr_`, `PBR_` or `Pbr`. An app +joins its own declarations, the text and its entry points into one module: + +```rust +let source = [APP_BINDINGS, craft_pbr::SHADE_WGSL, APP_ENTRY_POINTS].join("\n"); +``` + +and passes `source` to its shader compiler (with wgpu, `wgpu::ShaderSource::Wgsl(source.into())`). +The crate does not depend on wgpu or naga in its build. + +- **Values.** `Material::gpu()` returns a `GpuMaterial`, laid out as the WGSL struct + `PbrMaterial` (32 bytes: `base_color` at 0, `metallic` at 12, `roughness` at 16, `specular` at + 20, `diffuse` at 24). `GpuSh9::try_new` takes the coefficients of `try_sh9` and lays them out as + `PbrSh9` (144 bytes, one `vec4` per coefficient). `to_bytes` on either returns the + little-endian bytes for a uniform or storage buffer. `GpuSh9::try_new` returns + `PbrError::BadOption` for a coefficient that is not finite or whose magnitude is over + `GpuSh9::MAX_COEFFICIENT` (1e30), which keeps the `f32` sum of `pbr_irradiance` finite. Every + result of `try_sh9` is accepted. +- **Bounds.** No function loops or recurses. The GPU cannot return an error, so where the Rust + function returns one, the WGSL function returns a defined value: `pbr_direct` and + `pbr_environment_light` clamp material values to the ranges `Material::try_new` and + `try_with_weights` accept, a zero-length direction gives 0, and `pbr_environment_brdf` clamps + roughness to 0 to 1. WGSL implementations may assume that values are finite, so an app uploads + only checked values: a `GpuMaterial` comes from a checked `Material`. +- **Output.** Colors are linear. The text has no display encoding. + +| Rust | WGSL | Notes | +|------|------|-------| +| `Material::try_new` | `pbr_material_clamped` | Clamps to the ranges the Rust constructors check, including `try_with_weights`. | +| `Material::f0` | `pbr_f0` | Same formula. | +| `Material::try_direct` | `pbr_direct` | Same terms, floors and zero cases; a zero-length direction gives 0 instead of an error. | +| `fresnel_schlick` | `pbr_fresnel_schlick` | Same formula. | +| `smith_schlick_ggx` | `pbr_smith_schlick_ggx` | Same formula. | +| `ggx_distribution` | `pbr_ggx_distribution` | Same `α` floor, in `f32`; `(n·h)² (α² − 1) + 1` is computed as `(1 − n·h)(1 + n·h) + (n·h)² α²`. | +| `try_environment_brdf` | `pbr_environment_brdf` | Same fit and clamps; roughness is clamped instead of checked. | +| `dir_of` | `pbr_dir_of` | Same frame. | +| `uv_of` | `pbr_uv_of` | Same frame; a direction straight up or down has `u = 0`, as `atan2(0, 0)` gives in Rust. | +| `sh_basis` | `pbr_sh_basis` | Same basis; a zero-length direction gives nine zeros. | +| `irradiance` | `pbr_irradiance` | Sums in `f32` instead of `f64`. | +| `unit` | `pbr_unit` | Scales by the largest component first, as the Rust helper does; a zero-length direction gives the zero vector. | + +Two WGSL functions have no Rust counterpart in this crate. `pbr_specular_levels(roughness, +levels)` returns the two levels of a `try_prefilter` chain to blend and the weight of the second. +`pbr_environment_light` combines irradiance, prefiltered radiance and `pbr_environment_brdf` by +the split sum, as EffectCraft's `shade.rs` does on the CPU. + +The functions come from EffectCraft's `crates/gpu/src/shaders/advanced3d.wgsl` (at EffectCraft +`f4d45dfe`), which ports `shade.rs`. Changes from that shader: + +- The direct roughness floor is 0.032 instead of 0.03, a view straight opposite the light gives 0 + instead of a fallback half vector, and the environment BRDF keeps `scale` and `bias` at least 0 + with a sum of at most 1, as in the Rust functions (see Origin). +- A zero-length direction gives 0. EffectCraft's `norm3` replaced it with `(0, 0, −1)`. +- Material values are clamped to the Rust ranges. EffectCraft read them unchecked. +- `D` computes its inner term as `(1 − n·h)(1 + n·h) + (n·h)² α²` with an `α` floor of 0.001 and + a denominator of at least `f32::MIN_POSITIVE`. EffectCraft computed `(n·h)² (α² − 1) + 1`, + which loses precision in `f32` near `n·h = 1` for small `α`, with a denominator of at least + `1e-12` and no `α` floor. +- Fresnel raises `1 − v·h` to the fifth power by multiplication instead of `pow`. +- The equirect mapping is in this crate's frame. For EffectCraft's frame, a direction + `(x, y, z)` there is `(−z, −y, −x)` here, which gives the same `v` and the same `u` before + EffectCraft adds its rotation. +- EffectCraft's `srgb_to_linear` is not carried: the shader does not call it. + +Texture sampling, shadow maps, light attenuation and the unpacking of EffectCraft's buffers stay +in EffectCraft: they read its own bindings and packed layouts. The tests parse and validate the +text with naga, alone and with app bindings and `vs` and `fs` entry points, and check the +`PbrMaterial` and `PbrSh9` layouts against `to_bytes`. They do not run the WGSL on a GPU. + ## Origin The algorithms come from the `crates/render/src/ibl.rs` files of TextureCraft and MaterialCraft, diff --git a/crates/pbr/src/lib.rs b/crates/pbr/src/lib.rs index 1516068688..72f11da573 100644 --- a/crates/pbr/src/lib.rs +++ b/crates/pbr/src/lib.rs @@ -31,6 +31,9 @@ //! with the Smith-Schlick geometry term Karis gives for analytic lights. [`default_environment`] //! is a small studio environment for an environment light without an image. //! +//! [`SHADE_WGSL`] is the WGSL text of the same shading functions for an app's own shaders, and +//! [`GpuMaterial`] and [`GpuSh9`] lay out the values it reads. +//! //! The diffuse coefficients are the nine real SH coefficients of the radiance, convolved with the //! clamped cosine lobe (band factors `π`, `2π/3` and `π/4`, Ramamoorthi and Hanrahan 2001, //! ) and divided by `π`. [`irradiance`] @@ -50,6 +53,7 @@ mod environment; mod prefilter; mod sh; mod vec3; +mod wgsl; #[cfg(feature = "parallel")] use rayon::prelude::*; @@ -58,6 +62,7 @@ pub use brdf::{MAX_SPECULAR, MIN_DIRECT_ROUGHNESS, Material, try_environment_brd pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, default_environment, dir_of, uv_of}; pub use prefilter::{PrefilterOptions, ggx_distribution, hammersley, try_prefilter}; pub use sh::{irradiance, sh_basis, try_sh9}; +pub use wgsl::{GpuMaterial, GpuSh9, SHADE_WGSL}; /// Why an environment could not be made, filtered or read, or a material could not be shaded. #[derive(Debug, Clone, PartialEq, thiserror::Error)] diff --git a/crates/pbr/src/shade.wgsl b/crates/pbr/src/shade.wgsl new file mode 100644 index 0000000000..aa27e0cfaa --- /dev/null +++ b/crates/pbr/src/shade.wgsl @@ -0,0 +1,204 @@ +// craft-pbr shading functions in WGSL: the metallic-roughness BRDF for direct light, the +// environment BRDF of the split sum, the equirect mapping, SH9 irradiance and the light of an +// environment. Each function computes the terms of the Rust function the crate README lists +// next to it. The text declares no bindings and no entry points. An app makes one module of +// its own declarations, this text and its entry points. Every name here starts with `pbr_`, +// `PBR_` or `Pbr`. Colors are linear, and nothing here encodes them for display. No function +// loops or recurses. + +const PBR_PI: f32 = 3.14159265358979; +const PBR_TAU: f32 = 6.28318530717959; +// MIN_DIRECT_ROUGHNESS +const PBR_MIN_DIRECT_ROUGHNESS: f32 = 0.032; +// MAX_SPECULAR +const PBR_MAX_SPECULAR: f32 = 25.0; +// The smallest n·v the direct BRDF divides by. +const PBR_MIN_N_DOT_V: f32 = 1e-4; +// The α floor of ggx_distribution. +const PBR_MIN_ALPHA: f32 = 1e-3; +// f32::MIN_POSITIVE +const PBR_F32_MIN_POSITIVE: f32 = 1.17549435e-38; + +// A material as GpuMaterial lays it out: 32 bytes, base_color at 0, metallic at 12, roughness +// at 16, specular at 20 and diffuse at 24. +struct PbrMaterial { + base_color: vec3, + metallic: f32, + roughness: f32, + specular: f32, + diffuse: f32, +}; + +// Nine SH coefficients as GpuSh9 lays them out, in the order of pbr_sh_basis: red, green and +// blue in x, y and z, 16 bytes each. +struct PbrSh9 { + c: array, 9>, +}; + +// The material with each value clamped to the range Material::try_new and try_with_weights +// accept: base color, metallic, roughness and diffuse from 0 to 1, specular from 0 to 25. +fn pbr_material_clamped(m: PbrMaterial) -> PbrMaterial { + return PbrMaterial( + clamp(m.base_color, vec3(0.0), vec3(1.0)), + clamp(m.metallic, 0.0, 1.0), + clamp(m.roughness, 0.0, 1.0), + clamp(m.specular, 0.0, PBR_MAX_SPECULAR), + clamp(m.diffuse, 0.0, 1.0), + ); +} + +// `d` scaled to unit length, or the zero vector when `d` has zero length. `d` is divided by its +// largest component first, which keeps the squared length in range. +fn pbr_unit(d: vec3) -> vec3 { + let big = max(abs(d.x), max(abs(d.y), abs(d.z))); + if (!(big > 0.0)) { + return vec3(0.0); + } + let s = d / big; + return s * inverseSqrt(dot(s, s)); +} + +// The reflectance at normal incidence: 0.04 × specular mixed toward the base color by metallic. +fn pbr_f0(m: PbrMaterial) -> vec3 { + let d = vec3(0.04 * m.specular); + return d + (m.base_color - d) * m.metallic; +} + +// The GGX distribution D at n_dot_h for perceptual roughness, with α = max(roughness², 0.001): +// α² / (π ((n·h)² (α² − 1) + 1)²). The inner term is computed as (1 − n·h)(1 + n·h) + (n·h)² α², +// the same value, which keeps the peak 1 / (π α²) of small α in f32. +fn pbr_ggx_distribution(n_dot_h: f32, roughness: f32) -> f32 { + let a = max(roughness * roughness, PBR_MIN_ALPHA); + let a2 = a * a; + let k = (1.0 - n_dot_h) * (1.0 + n_dot_h) + n_dot_h * n_dot_h * a2; + return a2 / max(PBR_PI * k * k, PBR_F32_MIN_POSITIVE); +} + +// Schlick's Fresnel f0 + (1 − f0) (1 − v·h)⁵, with 1 − v·h kept in 0..=1. +fn pbr_fresnel_schlick(f0: vec3, v_dot_h: f32) -> vec3 { + let x = clamp(1.0 - v_dot_h, 0.0, 1.0); + let x2 = x * x; + return f0 + (vec3(1.0) - f0) * (x2 * x2 * x); +} + +// The Smith-Schlick-GGX geometry term for direct light, k = (roughness + 1)² / 8. +fn pbr_smith_schlick_ggx(n_dot_v: f32, n_dot_l: f32, roughness: f32) -> f32 { + let k = (roughness + 1.0) * (roughness + 1.0) / 8.0; + let gv = n_dot_v / (n_dot_v * (1.0 - k) + k); + let gl = n_dot_l / (n_dot_l * (1.0 - k) + k); + return gv * gl; +} + +// The light one light reflects toward the viewer: the BRDF times n·l times π, per channel, for +// a light whose color is the irradiance on a surface facing it. `n`, `v` and `l` are the +// normal, the direction to the viewer and the direction to the light; they are normalized here. +// The material is clamped with pbr_material_clamped and roughness is shaded as at least +// PBR_MIN_DIRECT_ROUGHNESS. A light at or below the surface, a view straight opposite the light +// and a zero-length direction give 0. n·v is taken as at least 1e-4. +fn pbr_direct(material: PbrMaterial, n_in: vec3, v_in: vec3, l_in: vec3) -> vec3 { + let m = pbr_material_clamped(material); + let n = pbr_unit(n_in); + let v = pbr_unit(v_in); + let l = pbr_unit(l_in); + let n_l = dot(n, l); + if (n_l <= 0.0 || dot(v, v) == 0.0) { + return vec3(0.0); + } + let h = pbr_unit(v + l); + if (dot(h, h) == 0.0) { + return vec3(0.0); + } + let n_v = max(dot(n, v), PBR_MIN_N_DOT_V); + let n_h = max(dot(n, h), 0.0); + let v_h = max(dot(v, h), 0.0); + let r = max(m.roughness, PBR_MIN_DIRECT_ROUGHNESS); + let f = pbr_fresnel_schlick(pbr_f0(m), v_h); + let spec = pbr_ggx_distribution(n_h, r) * pbr_smith_schlick_ggx(n_v, n_l, r) / max(4.0 * n_v * n_l, 1e-4); + let kd = (vec3(1.0) - f) * (1.0 - m.metallic); + return (kd * m.base_color / PBR_PI * m.diffuse + f * spec) * n_l * PBR_PI; +} + +// The environment BRDF term of the split sum for n_dot_v and perceptual roughness, as +// (scale, bias): specular light is prefiltered radiance times f0 × scale + bias. Karis's analytic +// fit for mobile, with scale and bias at least 0 and their sum at most 1. n_dot_v and roughness +// are clamped to 0..=1. +fn pbr_environment_brdf(n_dot_v: f32, roughness: f32) -> vec2 { + let n_v = clamp(n_dot_v, 0.0, 1.0); + let rough = clamp(roughness, 0.0, 1.0); + let r = rough * vec4(-1.0, -0.0275, -0.572, 0.022) + vec4(1.0, 0.0425, 1.04, -0.04); + let a004 = min(r.x * r.x, exp2(-9.28 * n_v)) * r.x + r.y; + let scale = clamp(-1.04 * a004 + r.z, 0.0, 1.0); + let bias = clamp(1.04 * a004 + r.w, 0.0, 1.0 - scale); + return vec2(scale, bias); +} + +// The direction of equirect coordinates (u, v) in the crate's frame: +Y up, row 0 straight up, +// u = 0 toward +X and u increasing toward +Z. +fn pbr_dir_of(u: f32, v: f32) -> vec3 { + let theta = v * PBR_PI; + let phi = u * PBR_TAU; + return vec3(sin(theta) * cos(phi), cos(theta), sin(theta) * sin(phi)); +} + +// The equirect coordinates (u, v) of a unit direction, u in 0..=1 and v in 0..=1. A direction +// straight up or down has u = 0. +fn pbr_uv_of(d: vec3) -> vec2 { + var phi = 0.0; + if (d.x != 0.0 || d.z != 0.0) { + phi = atan2(d.z, d.x); + } + let u = phi / PBR_TAU; + return vec2(u - floor(u), acos(clamp(d.y, -1.0, 1.0)) / PBR_PI); +} + +// The nine real SH basis functions at direction `d`, bands 0 to 2 in the order +// Y00, Y1-1 (y), Y10 (z), Y11 (x), Y2-2 (xy), Y2-1 (yz), Y20, Y21 (xz), Y22. `d` is normalized +// first; a zero-length direction gives nine zeros. +fn pbr_sh_basis(d_in: vec3) -> array { + let d = pbr_unit(d_in); + if (dot(d, d) == 0.0) { + return array(); + } + return array( + 0.282095, + 0.488603 * d.y, + 0.488603 * d.z, + 0.488603 * d.x, + 1.092548 * d.x * d.y, + 1.092548 * d.y * d.z, + 0.315392 * (3.0 * d.z * d.z - 1.0), + 1.092548 * d.x * d.z, + 0.546274 * (d.x * d.x - d.y * d.y), + ); +} + +// Σ c_k Y_k(n): the diffuse radiance a white surface with normal `n` reflects. Negative results, +// which ringing can give, are kept. A zero-length normal gives 0. +fn pbr_irradiance(sh: PbrSh9, n: vec3) -> vec3 { + let b = pbr_sh_basis(n); + return sh.c[0].xyz * b[0] + sh.c[1].xyz * b[1] + sh.c[2].xyz * b[2] + sh.c[3].xyz * b[3] + sh.c[4].xyz * b[4] + + sh.c[5].xyz * b[5] + sh.c[6].xyz * b[6] + sh.c[7].xyz * b[7] + sh.c[8].xyz * b[8]; +} + +// The two prefiltered levels to blend for perceptual roughness, and the weight of the second, as +// (low, high, weight). Level l of `levels` from try_prefilter is filtered for roughness +// l / (levels − 1). Roughness is clamped to 0..=1; 0 or 1 levels give (0, 0, 0). +fn pbr_specular_levels(roughness: f32, levels: u32) -> vec3 { + let last = f32(max(levels, 1u) - 1u); + let lv = clamp(roughness, 0.0, 1.0) * last; + let lo = floor(lv); + let hi = min(lo + 1.0, last); + return vec3(lo, hi, lv - lo); +} + +// The light an environment reflects toward the viewer, by the split sum. `irradiance` is the +// diffuse radiance a white surface with this normal reflects (pbr_irradiance, or the app's own +// lookup), and `prefiltered` is the radiance of the prefiltered levels along the reflection of +// the view about the normal, blended as pbr_specular_levels gives. The diffuse part is weighted +// by 1 − (f0 × scale + bias) and 1 − metallic. The material is clamped with pbr_material_clamped. +fn pbr_environment_light(material: PbrMaterial, n_dot_v: f32, irradiance: vec3, prefiltered: vec3) -> vec3 { + let m = pbr_material_clamped(material); + let ab = pbr_environment_brdf(n_dot_v, m.roughness); + let fs = pbr_f0(m) * ab.x + vec3(ab.y); + return irradiance * m.base_color * (vec3(1.0) - fs) * (1.0 - m.metallic) * m.diffuse + prefiltered * fs; +} diff --git a/crates/pbr/src/wgsl.rs b/crates/pbr/src/wgsl.rs new file mode 100644 index 0000000000..71a979d210 --- /dev/null +++ b/crates/pbr/src/wgsl.rs @@ -0,0 +1,110 @@ +//! The WGSL text of the shading functions and the GPU layouts of the values it reads. + +use std::mem::offset_of; + +use crate::{Material, PbrError}; + +/// WGSL source of the shading functions: `pbr_direct`, `pbr_environment_brdf`, +/// `pbr_environment_light`, `pbr_irradiance` and the helpers they call, with the structs +/// `PbrMaterial` and `PbrSh9`. The crate README lists each function next to its Rust +/// counterpart. +/// +/// The text declares no bindings and no entry points, and every name in it starts with `pbr_`, +/// `PBR_` or `Pbr`. An app joins its own declarations, this text and its entry points with +/// newlines into one module and passes that to its shader compiler. No function loops or +/// recurses. Colors are linear. +pub const SHADE_WGSL: &str = include_str!("shade.wgsl"); + +/// A [`Material`] laid out as the WGSL struct `PbrMaterial`, 32 bytes. Made by [`Material::gpu`]. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpuMaterial { + base_color: [f32; 3], + metallic: f32, + roughness: f32, + specular: f32, + diffuse: f32, + pad: f32, +} + +impl GpuMaterial { + /// Bytes of one `PbrMaterial`, which is also its array stride. + pub const SIZE: usize = size_of::(); + + /// The little-endian bytes of `PbrMaterial`, for a uniform or storage buffer. + pub fn to_bytes(&self) -> [u8; GpuMaterial::SIZE] { + let mut out = [0u8; GpuMaterial::SIZE]; + let fields = [ + (offset_of!(GpuMaterial, base_color), self.base_color[0]), + (offset_of!(GpuMaterial, base_color) + 4, self.base_color[1]), + (offset_of!(GpuMaterial, base_color) + 8, self.base_color[2]), + (offset_of!(GpuMaterial, metallic), self.metallic), + (offset_of!(GpuMaterial, roughness), self.roughness), + (offset_of!(GpuMaterial, specular), self.specular), + (offset_of!(GpuMaterial, diffuse), self.diffuse), + (offset_of!(GpuMaterial, pad), self.pad), + ]; + for (at, v) in fields { + if let Some(dst) = out.get_mut(at..at + 4) { + dst.copy_from_slice(&v.to_le_bytes()); + } + } + out + } +} + +impl Material { + /// The material in the layout of the WGSL struct `PbrMaterial`. + pub fn gpu(&self) -> GpuMaterial { + GpuMaterial { + base_color: self.base_color(), + metallic: self.metallic(), + roughness: self.roughness(), + specular: self.specular(), + diffuse: self.diffuse(), + pad: 0.0, + } + } +} + +/// Nine SH coefficients from [`try_sh9`](crate::try_sh9) laid out as the WGSL struct `PbrSh9`, +/// 144 bytes: one `vec4` per coefficient with red, green and blue in `x`, `y` and `z` and 0 +/// in `w`. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GpuSh9 { + c: [[f32; 4]; 9], +} + +impl GpuSh9 { + /// Bytes of one `PbrSh9`. + pub const SIZE: usize = size_of::(); + + /// The largest magnitude of a coefficient. The coefficients of [`try_sh9`](crate::try_sh9) + /// for radiance up to [`MAX_RADIANCE`](crate::MAX_RADIANCE) stay under 4e28. The basis + /// functions sum to less than 5 in magnitude in every direction, so `pbr_irradiance` sums + /// to less than 5e30 in `f32`. + pub const MAX_COEFFICIENT: f32 = 1e30; + + /// The coefficients in the layout of `PbrSh9`. Returns [`PbrError::BadOption`] when a + /// coefficient is not finite or its magnitude is over [`GpuSh9::MAX_COEFFICIENT`]. + pub fn try_new(coefficients: &[[f32; 3]; 9]) -> Result { + if coefficients.iter().flatten().any(|c| !c.is_finite() || c.abs() > GpuSh9::MAX_COEFFICIENT) { + return Err(PbrError::BadOption("an SH coefficient is not finite or its magnitude is over 1e30")); + } + Ok(GpuSh9 { c: coefficients.map(|[r, g, b]| [r, g, b, 0.0]) }) + } + + /// The little-endian bytes of `PbrSh9`, for a uniform or storage buffer. + pub fn to_bytes(&self) -> [u8; GpuSh9::SIZE] { + let mut out = [0u8; GpuSh9::SIZE]; + let base = offset_of!(GpuSh9, c); + for (i, v) in self.c.iter().flatten().enumerate() { + let at = base + 4 * i; + if let Some(dst) = out.get_mut(at..at + 4) { + dst.copy_from_slice(&v.to_le_bytes()); + } + } + out + } +} diff --git a/crates/pbr/tests/it/main.rs b/crates/pbr/tests/it/main.rs index 88029a518c..af2668dee1 100644 --- a/crates/pbr/tests/it/main.rs +++ b/crates/pbr/tests/it/main.rs @@ -8,6 +8,7 @@ mod brdf; mod differential; mod moved; mod numeric; +mod wgsl; /// Verbatim copies of the apps' previous code, run by `differential` and `brdf`. mod reference { diff --git a/crates/pbr/tests/it/wgsl.rs b/crates/pbr/tests/it/wgsl.rs new file mode 100644 index 0000000000..a2bdfcebd7 --- /dev/null +++ b/crates/pbr/tests/it/wgsl.rs @@ -0,0 +1,224 @@ +//! The WGSL text of the shading functions: it parses and validates, alone and joined with an app's +//! bindings and entry points; every Rust shading function has its WGSL counterpart; and the GPU +//! layouts write the bytes where the WGSL structs read them. + +use craft_pbr::{GpuMaterial, GpuSh9, Limits, MAX_RADIANCE, Material, PbrError, SHADE_WGSL, sh_basis, try_sh9}; +use naga::valid::{Capabilities, ValidationFlags, Validator}; +use naga::{Block, Module, Statement, TypeInner}; + +/// Each Rust shading function and its WGSL counterpart. The README's table lists the same pairs. +const COUNTERPARTS: [(&str, &str); 12] = [ + ("Material::try_new", "pbr_material_clamped"), + ("Material::f0", "pbr_f0"), + ("Material::try_direct", "pbr_direct"), + ("fresnel_schlick", "pbr_fresnel_schlick"), + ("smith_schlick_ggx", "pbr_smith_schlick_ggx"), + ("ggx_distribution", "pbr_ggx_distribution"), + ("try_environment_brdf", "pbr_environment_brdf"), + ("dir_of", "pbr_dir_of"), + ("uv_of", "pbr_uv_of"), + ("sh_basis", "pbr_sh_basis"), + ("irradiance", "pbr_irradiance"), + ("unit", "pbr_unit"), +]; + +/// App-side declarations and entry points in the shape EffectCraft's Advanced 3D shader has: a +/// uniform block, material and SH buffers, an environment texture, and `vs` and `fs` that shade +/// one light and the environment with the shared functions. +const APP_DECLARATIONS: &str = " +struct Globals { + clip: mat4x4, + eye: vec4, + light: vec4, + env: vec4, +}; +@group(0) @binding(0) var g: Globals; +@group(0) @binding(1) var materials: array; +@group(0) @binding(2) var sh: PbrSh9; +@group(0) @binding(3) var env_tex: texture_2d; +@group(0) @binding(4) var env_smp: sampler; +"; + +const APP_ENTRY_POINTS: &str = " +struct VIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) material: u32, +}; +struct VOut { + @builtin(position) clip: vec4, + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) @interpolate(flat) material: u32, +}; +@vertex +fn vs(v: VIn) -> VOut { + var o: VOut; + o.clip = g.clip * vec4(v.pos, 1.0); + o.pos = v.pos; + o.normal = v.normal; + o.material = v.material; + return o; +} +@fragment +fn fs(i: VOut) -> @location(0) vec4 { + let m = materials[i.material]; + let n = pbr_unit(i.normal); + let v = pbr_unit(g.eye.xyz - i.pos); + var c = pbr_direct(m, n, v, g.light.xyz); + let lv = pbr_specular_levels(m.roughness, u32(g.env.x)); + let uv = pbr_uv_of(reflect(-v, n)); + let a = textureSampleLevel(env_tex, env_smp, uv, lv.x).rgb; + let b = textureSampleLevel(env_tex, env_smp, uv, lv.y).rgb; + c = c + pbr_environment_light(m, dot(n, v), pbr_irradiance(sh, n), mix(a, b, lv.z)); + return vec4(c, 1.0); +} +"; + +/// Parses and validates `source`, failing the test with naga's report. +fn module(source: &str) -> Module { + let module = naga::front::wgsl::parse_str(source).unwrap_or_else(|e| panic!("{}", e.emit_to_string(source))); + if let Err(e) = Validator::new(ValidationFlags::all(), Capabilities::default()).validate(&module) { + panic!("{}", e.emit_to_string(source)); + } + module +} + +fn function_names(m: &Module) -> Vec<&str> { + m.functions.iter().filter_map(|(_, f)| f.name.as_deref()).collect() +} + +fn has_loop(block: &Block) -> bool { + block.iter().any(|s| match s { + Statement::Loop { .. } => true, + Statement::Block(b) => has_loop(b), + Statement::If { accept, reject, .. } => has_loop(accept) || has_loop(reject), + Statement::Switch { cases, .. } => cases.iter().any(|c| has_loop(&c.body)), + _ => false, + }) +} + +/// The members of the struct named `name` as (member name, offset, type), and its size. +fn struct_layout<'m>(m: &'m Module, name: &str) -> (Vec<(&'m str, u32, &'m TypeInner)>, u32) { + let ty = m.types.iter().find(|(_, t)| t.name.as_deref() == Some(name)).unwrap_or_else(|| panic!("no struct {name}")).1; + let TypeInner::Struct { members, span } = &ty.inner else { panic!("{name} is not a struct") }; + let fields = members.iter().map(|mb| (mb.name.as_deref().unwrap_or(""), mb.offset, &m.types[mb.ty].inner)).collect(); + (fields, *span) +} + +fn f32_at(bytes: &[u8], at: u32) -> f32 { + let at = at as usize; + f32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) +} + +#[test] +fn shading_text_validates_with_an_apps_bindings_and_entry_points() { + let source = [APP_DECLARATIONS, SHADE_WGSL, APP_ENTRY_POINTS].join("\n"); + let m = module(&source); + let entry: Vec<&str> = m.entry_points.iter().map(|e| e.name.as_str()).collect(); + assert_eq!(entry, ["vs", "fs"]); +} + +#[test] +fn shading_text_alone_has_no_bindings_entry_points_or_loops() { + let m = module(SHADE_WGSL); + assert!(m.global_variables.is_empty(), "the text declares a binding"); + assert!(m.entry_points.is_empty(), "the text declares an entry point"); + for (_, f) in m.functions.iter() { + assert!(!has_loop(&f.body), "{:?} loops", f.name); + } + let names = m + .functions + .iter() + .filter_map(|(_, f)| f.name.clone()) + .chain(m.constants.iter().filter_map(|(_, c)| c.name.clone())) + .chain(m.types.iter().filter_map(|(_, t)| t.name.clone()).filter(|n| n.chars().next().is_some_and(char::is_uppercase))); + for name in names { + assert!(name.starts_with("pbr_") || name.starts_with("PBR_") || name.starts_with("Pbr"), "{name} has no pbr prefix"); + } +} + +#[test] +fn every_rust_shading_function_has_a_wgsl_counterpart_listed_in_the_readme() { + let m = module(SHADE_WGSL); + let names = function_names(&m); + let readme = include_str!("../../README.md"); + for (rust, wgsl) in COUNTERPARTS { + assert!(names.contains(&wgsl), "{wgsl}, the counterpart of {rust}, is missing from SHADE_WGSL"); + let row = format!("| `{rust}` | `{wgsl}` |"); + assert!(readme.lines().any(|l| l.starts_with(&row)), "the README has no row for {rust} and {wgsl}"); + } +} + +#[test] +fn gpu_material_bytes_sit_where_pbr_material_reads_them() { + let m = module(SHADE_WGSL); + let (fields, span) = struct_layout(&m, "PbrMaterial"); + assert_eq!(span as usize, GpuMaterial::SIZE); + let mat = Material::try_new([0.1, 0.2, 0.3], 0.4, 0.5).unwrap().try_with_weights(6.0, 0.7).unwrap(); + let bytes = mat.gpu().to_bytes(); + assert_eq!(bytes.len(), span as usize); + let names: Vec<&str> = fields.iter().map(|f| f.0).collect(); + assert_eq!(names, ["base_color", "metallic", "roughness", "specular", "diffuse"]); + for (name, offset, _) in fields { + let read = match name { + "base_color" => vec![f32_at(&bytes, offset), f32_at(&bytes, offset + 4), f32_at(&bytes, offset + 8)], + _ => vec![f32_at(&bytes, offset)], + }; + let want = match name { + "base_color" => mat.base_color().to_vec(), + "metallic" => vec![mat.metallic()], + "roughness" => vec![mat.roughness()], + "specular" => vec![mat.specular()], + _ => vec![mat.diffuse()], + }; + assert_eq!(read, want, "{name} at byte {offset}"); + } +} + +#[test] +fn gpu_sh9_bytes_sit_where_pbr_sh9_reads_them() { + let m = module(SHADE_WGSL); + let (fields, span) = struct_layout(&m, "PbrSh9"); + assert_eq!(span as usize, GpuSh9::SIZE); + let &[(_, offset, &TypeInner::Array { stride, .. })] = fields.as_slice() else { panic!("PbrSh9 is not one array") }; + let coefficients: [[f32; 3]; 9] = std::array::from_fn(|k| std::array::from_fn(|c| (k * 3 + c) as f32 - 4.5)); + let bytes = GpuSh9::try_new(&coefficients).unwrap().to_bytes(); + assert_eq!(bytes.len(), span as usize); + for (k, rgb) in coefficients.iter().enumerate() { + for (c, want) in rgb.iter().enumerate() { + assert_eq!(f32_at(&bytes, offset + stride * k as u32 + 4 * c as u32), *want, "coefficient {k} channel {c}"); + } + } +} + +#[test] +fn gpu_sh9_rejects_coefficients_that_are_not_finite_or_too_large() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX, -1.5 * GpuSh9::MAX_COEFFICIENT] { + let mut c = [[0.5f32; 3]; 9]; + c[8][2] = bad; + assert!(matches!(GpuSh9::try_new(&c), Err(PbrError::BadOption(_))), "{bad}"); + } + let mut c = [[0.5f32; 3]; 9]; + c[0][0] = -GpuSh9::MAX_COEFFICIENT; + assert!(GpuSh9::try_new(&c).is_ok()); +} + +#[test] +fn gpu_sh9_accepts_the_brightest_environments_and_keeps_the_wgsl_sum_finite() { + // A uniform environment and one lit only above the horizon, at the largest radiance. + for lit_rows in [8, 4] { + let env = crate::env_from(16, 8, |_, y| if y < lit_rows { [MAX_RADIANCE; 3] } else { [0.0; 3] }); + let sh = try_sh9(&env, &Limits::default()).unwrap(); + assert!(GpuSh9::try_new(&sh).is_ok(), "{lit_rows} lit rows: {sh:?}"); + } + // pbr_irradiance sums nine coefficients of at most MAX_COEFFICIENT times the basis values. + let mut largest = 0.0f32; + for i in 0..4096u32 { + let [u, v] = craft_pbr::hammersley(i, 4096).unwrap(); + let b = sh_basis(craft_pbr::dir_of(u, v)).unwrap(); + largest = largest.max(b.iter().map(|y| y.abs()).sum()); + } + assert!(largest < 5.0, "basis sum {largest}"); + assert!((5.0 * GpuSh9::MAX_COEFFICIENT).is_finite()); +} From e4b46d6a337f0653f5101cec306dcebe2edeb157 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:17:58 -0800 Subject: [PATCH 2/3] =?UTF-8?q?craft-pbr:=20keep=20n=C2=B7h=20at=20most=20?= =?UTF-8?q?1=20in=20pbr=5Fdirect,=20as=20try=5Fdirect=20does?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pbr_direct now takes n·h as clamp(dot(n, h), 0, 1), matching try_direct. With n·h slightly over 1 after rounding, the GGX inner term shrinks and D rises above its peak. Its comment also names the 1e-4 floor of the specular denominator. The README's pbr_direct row lists the floors and the differences from try_direct, and the changes from EffectCraft's shader say that it clamped roughness to 0.03 to 1 and read the other material values unchecked. --- crates/pbr/README.md | 10 ++++++---- crates/pbr/src/shade.wgsl | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/pbr/README.md b/crates/pbr/README.md index 8b760c85eb..1cf69ebd20 100644 --- a/crates/pbr/README.md +++ b/crates/pbr/README.md @@ -129,7 +129,7 @@ The crate does not depend on wgpu or naga in its build. |------|------|-------| | `Material::try_new` | `pbr_material_clamped` | Clamps to the ranges the Rust constructors check, including `try_with_weights`. | | `Material::f0` | `pbr_f0` | Same formula. | -| `Material::try_direct` | `pbr_direct` | Same terms, floors and zero cases; a zero-length direction gives 0 instead of an error. | +| `Material::try_direct` | `pbr_direct` | Same floors: roughness at least 0.032, `n·v` at least `1e-4`, `n·h` at most 1 and `4 (n·v) (n·l)` at least `1e-4`. A light at or below the surface or a view straight opposite the light gives 0 in both. A zero-length direction gives 0 instead of an error, material values are clamped instead of checked, and `D` is evaluated in `f32` by `pbr_ggx_distribution`. | | `fresnel_schlick` | `pbr_fresnel_schlick` | Same formula. | | `smith_schlick_ggx` | `pbr_smith_schlick_ggx` | Same formula. | | `ggx_distribution` | `pbr_ggx_distribution` | Same `α` floor, in `f32`; `(n·h)² (α² − 1) + 1` is computed as `(1 − n·h)(1 + n·h) + (n·h)² α²`. | @@ -149,10 +149,12 @@ The functions come from EffectCraft's `crates/gpu/src/shaders/advanced3d.wgsl` ( `f4d45dfe`), which ports `shade.rs`. Changes from that shader: - The direct roughness floor is 0.032 instead of 0.03, a view straight opposite the light gives 0 - instead of a fallback half vector, and the environment BRDF keeps `scale` and `bias` at least 0 - with a sum of at most 1, as in the Rust functions (see Origin). + instead of a fallback half vector, `n·h` is taken as at most 1 as well as at least 0, and the + environment BRDF keeps `scale` and `bias` at least 0 with a sum of at most 1, as in the Rust + functions (see Origin). - A zero-length direction gives 0. EffectCraft's `norm3` replaced it with `(0, 0, −1)`. -- Material values are clamped to the Rust ranges. EffectCraft read them unchecked. +- Material values are clamped to the Rust ranges. EffectCraft clamped roughness to 0.03 to 1 and + read base color, metallic, specular and diffuse unchecked. - `D` computes its inner term as `(1 − n·h)(1 + n·h) + (n·h)² α²` with an `α` floor of 0.001 and a denominator of at least `f32::MIN_POSITIVE`. EffectCraft computed `(n·h)² (α² − 1) + 1`, which loses precision in `f32` near `n·h = 1` for small `α`, with a denominator of at least diff --git a/crates/pbr/src/shade.wgsl b/crates/pbr/src/shade.wgsl index aa27e0cfaa..01a3a20a92 100644 --- a/crates/pbr/src/shade.wgsl +++ b/crates/pbr/src/shade.wgsl @@ -94,7 +94,8 @@ fn pbr_smith_schlick_ggx(n_dot_v: f32, n_dot_l: f32, roughness: f32) -> f32 { // normal, the direction to the viewer and the direction to the light; they are normalized here. // The material is clamped with pbr_material_clamped and roughness is shaded as at least // PBR_MIN_DIRECT_ROUGHNESS. A light at or below the surface, a view straight opposite the light -// and a zero-length direction give 0. n·v is taken as at least 1e-4. +// and a zero-length direction give 0. n·v is taken as at least 1e-4, n·h as at most 1, and the +// specular denominator 4 (n·v) (n·l) as at least 1e-4. fn pbr_direct(material: PbrMaterial, n_in: vec3, v_in: vec3, l_in: vec3) -> vec3 { let m = pbr_material_clamped(material); let n = pbr_unit(n_in); @@ -109,7 +110,7 @@ fn pbr_direct(material: PbrMaterial, n_in: vec3, v_in: vec3, l_in: vec return vec3(0.0); } let n_v = max(dot(n, v), PBR_MIN_N_DOT_V); - let n_h = max(dot(n, h), 0.0); + let n_h = clamp(dot(n, h), 0.0, 1.0); let v_h = max(dot(v, h), 0.0); let r = max(m.roughness, PBR_MIN_DIRECT_ROUGHNESS); let f = pbr_fresnel_schlick(pbr_f0(m), v_h); From 9acd6d5883794748664b77b865a6fa3bbc29d2b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:41:50 -0800 Subject: [PATCH 3/3] craft-pbr: record the TextureCraft, MaterialCraft and EffectCraft sources in NOTICE NOTICE lists the files craft-pbr adapts and the reference copies in tests/it/reference, with each repository, path and full revision, under Source provenance as docs/clean-room.md asks. --- NOTICE | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/NOTICE b/NOTICE index 66b01e02fe..17e3c4476e 100644 --- a/NOTICE +++ b/NOTICE @@ -223,6 +223,26 @@ The colour management module in crates/cms is extracted from: Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain (CC0-1.0); see ATTRIBUTION.md. +The image-based lighting in crates/pbr (craft-pbr) is adapted from: +- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc, + copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs. + https://github.com/storytold/texturecraft + Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. +- MaterialCraft, crates/render/src/ibl.rs, revision 4ff5af9af7371613ee37b186e03caf49ee6dbd88, + whose differing parts are copied to crates/pbr/tests/it/reference/materialcraft.rs. + https://github.com/storytold/materialcraft + Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. +The BRDF, environment BRDF and default environment in crates/pbr are adapted from: +- EffectCraft, crates/render/src/three_d/adv/shade.rs and adv/scene.rs, revision + 41da144555a1c8ddbbe94876a00259832322d00c, whose shading functions and default environment + are copied to crates/pbr/tests/it/reference/effectcraft.rs. + https://github.com/storytold/effectcraft + Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. +The WGSL text in crates/pbr/src/shade.wgsl is adapted from: +- EffectCraft, crates/gpu/src/shaders/advanced3d.wgsl, revision + f4d45dfef3a280d96aff1d4eb5f1950160adefc2 (above). +All four sources are licensed MIT OR Apache-2.0. crates/pbr/README.md lists the changes from them. + Optional PDF writer Krilla 0.8.2 (https://github.com/LaurenzV/krilla), MIT OR Apache-2.0.