craft-pbr: metallic-roughness BRDF, environment BRDF and default environment from EffectCraft

Adds the direct-light BRDF, the split-sum environment BRDF and the
default studio environment of EffectCraft's adv/shade.rs and
adv/scene.rs to craft-pbr, with EffectCraft's tests on the new API.

- Material::try_new and try_with_weights check base color, metallic,
  roughness and the specular and diffuse weights; NaN, infinity and
  values out of range give PbrError::BadMaterial. try_direct checks and
  normalizes its directions (PbrError::BadDirection).
- The BRDF is the final form of glTF 2.0 section B.3.5 with Schlick's
  Fresnel and the GGX distribution of ggx_distribution, evaluated in
  f64. The geometry term stays the Smith-Schlick term with
  k = (roughness + 1)^2 / 8 for analytic lights; it equals glTF's
  separable Smith term at roughness 1.
- Roughness is shaded as at least 0.032 instead of 0.03, above the
  alpha floor of ggx_distribution. A view straight opposite the light
  gives 0.
- try_environment_brdf keeps scale and bias at least 0 with a sum of at
  most 1. The fit gave a scale of -0.044 and a bias of 1.044 at n.v = 0
  and roughness 0, and a bias of -0.0024 at n.v = 0 and roughness 1.
- default_environment returns the 8 x 4 studio gradient in this crate's
  frame; its pixels match EffectCraft's within 1e-6.

New tests: a white metal reflects at most the light it receives at every
roughness and view angle, the BRDF is reciprocal, roughness is clamped
at MIN_DIRECT_ROUGHNESS, metallic 0 and 1 match glTF's dielectric and
metal BRDFs, the geometry term against glTF's Smith form, invalid
values are refused, and the direct light, environment BRDF and default
environment match a copy of EffectCraft's code.
This commit is contained in:
dotCooCoo
2026-11-21 08:30:29 -08:00
parent e8fac42706
commit bb5a3d472b
8 changed files with 844 additions and 10 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-pbr"
description = "Image-based lighting for physically based rendering: equirect environments, a GGX-prefiltered specular chain and SH9 diffuse irradiance"
description = "Image-based lighting for physically based rendering: equirect environments, a GGX-prefiltered specular chain, SH9 diffuse irradiance and the metallic-roughness BRDF"
version.workspace = true
edition.workspace = true
license.workspace = true
+62 -4
View File
@@ -3,8 +3,9 @@
Image-based lighting for physically based rendering, computed on the CPU. An `EnvImage` is a linear
RGB equirect (latitude-longitude) environment, row-major with the top row first. The crate turns it
into a GGX-prefiltered chain for specular light and nine spherical-harmonics coefficients for
diffuse light, and renders six procedural environments with no image assets. It has no UI, does no
file or network I/O and has no `unsafe` code.
diffuse light, and renders six procedural environments with no image assets. It also evaluates the
glTF 2.0 metallic-roughness BRDF for direct light and the environment BRDF term of the split sum.
It has no UI, does no file or network I/O and has no `unsafe` code.
- **Frame.** +Y is up. Column `u = φ / 2π` and row `v = θ / π` map to the direction
`(sin θ cos φ, cos θ, sin θ sin φ)`: row 0 is straight up, `u = 0` points to +X and `u` increases
@@ -32,8 +33,40 @@ file or network I/O and has no `unsafe` code.
`ggx_distribution` evaluates the distribution as section B.3.2 writes it
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#specular-brdf>). Samples read a box-filtered pyramid of the source at a level chosen from each
sample's density plus `lod_bias` (default 1). `firefly_cap` caps source radiance before
filtering when set (default off); level 0 is never capped. The environment BRDF term of the
split sum is not in this crate.
filtering when set (default off); level 0 is never capped.
- **Environment BRDF.** `try_environment_brdf(n_dot_v, roughness)` returns the `[scale, bias]` of
the split sum's second term: specular light is a prefiltered level's radiance times
`f0 × scale + bias`. The values are Karis's analytic fit for mobile
(<https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile>), with `scale` and
`bias` kept at least 0 and their sum at most 1. `n_dot_v` is clamped to `0..=1`.
- **Direct light.** `Material::try_new(base_color, metallic, roughness)` takes linear base color,
metallic and perceptual roughness, each from 0 to 1 as glTF 2.0 defines them, and
`try_with_weights(specular, diffuse)` sets two weights for direct light: `specular` (0 to
`MAX_SPECULAR`, 25) scales the dielectric reflectance at normal incidence, 0.04, and `diffuse`
(0 to 1) scales the diffuse lobe. Both are 1 for a glTF material. Other values, NaN and
infinity give `PbrError::BadMaterial`. `try_direct(n, v, l)` returns the BRDF times `n·l` times
π, the fraction of a light's irradiance reflected toward the viewer, per RGB channel. The BRDF
is the final form of glTF 2.0 section B.3.5
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metal-brdf-and-dielectric-brdf>):
`f0` is 0.04 mixed toward the base color by metallic, `F` is Schlick's approximation at `v·h`
(section B.3.4), the diffuse lobe is `(1 − F) (1 − metallic) base / π`, and the specular lobe
is `F D G / (4 (n·v) (n·l))` with the `D` of `ggx_distribution`.
- `G` is the Smith-Schlick term with `k = (roughness + 1)² / 8`, which Karis gives for analytic
lights in the 2013 notes above. Section B.3.2 writes the separable Smith
form. The two are equal at roughness 1; on smoother surfaces this `G` is darker at grazing
angles.
- Roughness is shaded as at least `MIN_DIRECT_ROUGHNESS` (0.032, `α` = 0.001024).
- `n·v` is taken as at least `1e-4`, so a view at or below the surface sees it as at a
grazing angle. A light at or below the surface, or a view straight opposite the light, gives
0. Directions are normalized; one that is not finite or has zero length gives
`PbrError::BadDirection`.
- A white metal reflects at most the light it receives. As section B.3.6.3 notes, the Fresnel
coupling of the two lobes does not conserve energy: a smooth white dielectric seen about 80
degrees from the normal reflects about 9.8% more light than it receives.
- **Default environment.** `default_environment()` is an 8 × 4 gray studio gradient for an
environment light that has no image: radiance proportional to `0.15 + 1.2 max(0, d·key)` with
the key `(0.66, 0.75, 0)`, up and toward +X, scaled to a mean of 0.3 over the pixels weighted
by `sin θ` at their centers.
- **Diffuse.** `try_sh9` projects every pixel of the source onto the nine real SH basis functions
of `sh_basis`, each integrated over the area of each pixel. The coefficients are convolved with
the clamped cosine lobe (band factors `π`, `2π/3`, `π/4`, Ramamoorthi and Hanrahan 2001,
@@ -79,6 +112,26 @@ prefiltered levels match theirs for sources with even sides. Changes from those
rows (3.2e-4 on 64).
- Rows run on several threads only with the `parallel` feature.
The BRDF, the environment BRDF and the default environment come from EffectCraft's
`crates/render/src/three_d/adv/shade.rs` and `adv/scene.rs`. Changes from those files:
- Material values, weights and directions are checked; NaN, infinity, values out of range and
zero-length directions give an error instead of a NaN or negative color. Directions are
normalized.
- The distribution is `ggx_distribution`, evaluated in `f64`. EffectCraft evaluated it in `f32`,
which loses the narrow peak of smooth surfaces. From roughness 0.25 up, the direct light matches
within `1e-4` of `max(1, value)`.
- Roughness is shaded as at least 0.032 instead of 0.03, so `α` stays above the 0.001 floor of
`ggx_distribution`.
- A view straight opposite the light gives 0 instead of using a fallback half vector.
- The environment BRDF keeps `scale` and `bias` at least 0 with a sum of at most 1. The fit gives
a negative scale for smooth surfaces at grazing angles (-0.044 with a bias of 1.044 at
`n·v` = 0 and roughness 0), which made `f0 × scale + bias` greater than 1 and the diffuse
weight `1 − fs` negative, and a negative bias of -0.0024 for rough surfaces at grazing angles.
- The default environment is in this crate's frame. An EffectCraft direction `(x, y, z)`, with +Y
down and the image center at +Z, is `(−z, −y, −x)` here, so the key `(0, −0.75, −0.66)`
becomes `(0.66, 0.75, 0)` and the pixels are the same within `1e-6`.
## Migration
- **TextureCraft.** Replace `texturecraft_render::ibl` with `craft_pbr`. Pass
@@ -93,3 +146,8 @@ prefiltered levels match theirs for sources with even sides. Changes from those
- **MaterialCraft.** Replace `materialcraft_render::ibl` with `craft_pbr`, with the same
`firefly_cap`. `by_id` stays in the app and maps view ids to `Environment::from_name`.
`hammersley` returns `None` when `i` is not below `n`.
- **EffectCraft.** Replace `shade::brdf` with `Material::try_new(...)?.try_with_weights(specular_k,
diffuse_k)?.try_direct(n, v, l)`, and `shade::env_brdf` with `try_environment_brdf`. The
adapter keeps layer policy, texture sampling, lights, shadows and its box-filtered environment
chain, and maps a material error to a render failure. `default_environment` replaces
`scene::default_environment` once the adapter converts directions to this crate's frame.
+172
View File
@@ -0,0 +1,172 @@
//! The metallic-roughness BRDF for direct light and the environment BRDF term of the split sum.
use std::f32::consts::PI;
use crate::PbrError;
use crate::prefilter::ggx_distribution;
use crate::vec3::unit;
/// The smallest roughness direct light is shaded with. Smaller values, 0 included, are shaded as
/// this one, so a point light keeps a highlight of finite height. Its `α = roughness²` of
/// 0.001024 is above the `α` floor of [`ggx_distribution`].
pub const MIN_DIRECT_ROUGHNESS: f32 = 0.032;
/// Largest [`Material::specular`] weight: at 25 the dielectric reflectance at normal incidence,
/// `0.04 × specular`, is 1.
pub const MAX_SPECULAR: f32 = 25.0;
/// The smallest `n·v` the direct BRDF divides by. A view at or below the surface is shaded as
/// a view at this cosine.
const MIN_N_DOT_V: f32 = 1e-4;
/// A metallic-roughness material: linear base color, metallic and perceptual roughness, each in
/// `0..=1` as glTF 2.0 defines them, and two weights for direct light.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Material {
base_color: [f32; 3],
metallic: f32,
roughness: f32,
specular: f32,
diffuse: f32,
}
/// Checks that `v` is finite and in `lo..=hi`.
fn in_range(v: f32, lo: f32, hi: f32, what: &'static str) -> Result<f32, PbrError> {
if v.is_finite() && (lo..=hi).contains(&v) { Ok(v) } else { Err(PbrError::BadMaterial(what)) }
}
impl Material {
/// A material with specular and diffuse weights of 1. Returns [`PbrError::BadMaterial`] when
/// a base color channel, `metallic` or `roughness` is not a number in `0..=1`.
pub fn try_new(base_color: [f32; 3], metallic: f32, roughness: f32) -> Result<Material, PbrError> {
for c in base_color {
in_range(c, 0.0, 1.0, "a base color channel is not a number from 0 to 1")?;
}
Ok(Material {
base_color,
metallic: in_range(metallic, 0.0, 1.0, "the metallic value is not a number from 0 to 1")?,
roughness: in_range(roughness, 0.0, 1.0, "the roughness is not a number from 0 to 1")?,
specular: 1.0,
diffuse: 1.0,
})
}
/// The material with these weights. `specular` scales the dielectric reflectance at normal
/// incidence, 0.04 at 1, and is a number from 0 to [`MAX_SPECULAR`]. `diffuse` scales the
/// diffuse lobe and is a number from 0 to 1. Returns [`PbrError::BadMaterial`] otherwise.
/// glTF 2.0 has neither weight; both are 1 for a glTF material.
pub fn try_with_weights(self, specular: f32, diffuse: f32) -> Result<Material, PbrError> {
Ok(Material {
specular: in_range(specular, 0.0, MAX_SPECULAR, "the specular weight is not a number from 0 to 25")?,
diffuse: in_range(diffuse, 0.0, 1.0, "the diffuse weight is not a number from 0 to 1")?,
..self
})
}
/// The linear base color.
pub fn base_color(&self) -> [f32; 3] {
self.base_color
}
/// The metallic value.
pub fn metallic(&self) -> f32 {
self.metallic
}
/// The perceptual roughness.
pub fn roughness(&self) -> f32 {
self.roughness
}
/// The specular weight.
pub fn specular(&self) -> f32 {
self.specular
}
/// The diffuse weight.
pub fn diffuse(&self) -> f32 {
self.diffuse
}
/// The reflectance at normal incidence: `0.04 × specular` mixed toward the base color by
/// `metallic`. Each channel is in `0..=1`.
pub fn f0(&self) -> [f32; 3] {
let d = 0.04 * self.specular;
self.base_color.map(|c| d + (c - d) * self.metallic)
}
/// The light one light reflects toward the viewer: the BRDF times `n·l` times π, per RGB
/// channel, for a light whose color is the irradiance on a surface facing it. A white light
/// on a white rough dielectric lit and seen head-on gives about 1.
///
/// `n`, `v` and `l` are the surface normal, the direction to the viewer and the direction to
/// the light; they are normalized here. The BRDF is the final form of glTF 2.0 section
/// B.3.5: a Lambert lobe `(1 − F) (1 − metallic) base / π` plus `F D G / (4 (n·v) (n·l))`,
/// with Schlick's `F` (section B.3.4) at `v·h`, the GGX `D` of [`ggx_distribution`], and
/// the Smith-Schlick `G` with `k = (roughness + 1)² / 8` that Karis gives for analytic
/// lights, where section B.3.2 writes the separable Smith form. Roughness is shaded as at
/// least [`MIN_DIRECT_ROUGHNESS`]. A light at or below the surface gives 0, and so does a
/// view straight opposite the light, which has no half vector. `n·v` is taken as at least
/// `1e-4`, so a view at or below the surface sees the surface as at a grazing angle.
///
/// Returns [`PbrError::BadDirection`] when a direction is not finite or has zero length.
pub fn try_direct(&self, n: [f32; 3], v: [f32; 3], l: [f32; 3]) -> Result<[f32; 3], PbrError> {
let n = unit(n).ok_or(PbrError::BadDirection)?;
let v = unit(v).ok_or(PbrError::BadDirection)?;
let l = unit(l).ok_or(PbrError::BadDirection)?;
let n_l = n.dot(l);
if n_l <= 0.0 {
return Ok([0.0; 3]);
}
let Some(h) = unit((v + l).to_array()) else { return Ok([0.0; 3]) };
let n_v = n.dot(v).max(MIN_N_DOT_V);
let n_h = n.dot(h).max(0.0);
let v_h = v.dot(h).max(0.0);
let r = self.roughness.max(MIN_DIRECT_ROUGHNESS);
let f = fresnel_schlick(self.f0(), v_h);
let spec = ggx_distribution(n_h, r) * smith_schlick_ggx(n_v, n_l, r) / (4.0 * n_v * n_l).max(1e-4);
let mut out = [0.0; 3];
for c in 0..3 {
let kd = (1.0 - f[c]) * (1.0 - self.metallic);
out[c] = (kd * self.base_color[c] / PI * self.diffuse + f[c] * spec) * n_l * PI;
}
Ok(out)
}
}
/// Schlick's Fresnel `f0 + (1 − f0) (1 − v·h)⁵`, with `1 − v·h` kept in `0..=1`.
fn fresnel_schlick(f0: [f32; 3], v_h: f32) -> [f32; 3] {
let k = (1.0 - v_h).clamp(0.0, 1.0).powi(5);
f0.map(|c| c + (1.0 - c) * k)
}
/// The Smith-Schlick-GGX geometry term for direct light, `k = (roughness + 1)² / 8`.
fn smith_schlick_ggx(n_v: f32, n_l: f32, roughness: f32) -> f32 {
let k = (roughness + 1.0) * (roughness + 1.0) / 8.0;
let g1 = |x: f32| x / (x * (1.0 - k) + k);
g1(n_v) * g1(n_l)
}
/// The environment BRDF term of the split sum for `n_dot_v` and perceptual `roughness`, as
/// `[scale, bias]`: the specular light of a prefiltered environment is its radiance times
/// `f0 × scale + bias`. The values are Karis's analytic fit for mobile
/// (<https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile>), kept so that
/// `scale` and `bias` are at least 0 and their sum is at most 1, which keeps `f0 × scale + bias`
/// in `0..=1` for every `f0` in `0..=1`. `n_dot_v` is clamped to `0..=1`.
///
/// Returns [`PbrError::BadDirection`] when `n_dot_v` is not finite, and
/// [`PbrError::BadMaterial`] when `roughness` is not a number in `0..=1`.
pub fn try_environment_brdf(n_dot_v: f32, roughness: f32) -> Result<[f32; 2], PbrError> {
if !n_dot_v.is_finite() {
return Err(PbrError::BadDirection);
}
let rough = in_range(roughness, 0.0, 1.0, "the roughness is not a number from 0 to 1")?;
let n_v = n_dot_v.clamp(0.0, 1.0);
let c0 = [-1.0, -0.0275, -0.572, 0.022];
let c1 = [1.0, 0.0425, 1.04, -0.04];
let r = [rough * c0[0] + c1[0], rough * c0[1] + c1[1], rough * c0[2] + c1[2], rough * c0[3] + c1[3]];
let a004 = (r[0] * r[0]).min((-9.28 * n_v).exp2()) * r[0] + r[1];
let scale = (-1.04 * a004 + r[2]).clamp(0.0, 1.0);
let bias = (1.04 * a004 + r[3]).clamp(0.0, 1.0 - scale);
Ok([scale, bias])
}
+24
View File
@@ -328,3 +328,27 @@ impl Environment {
Ok(EnvImage { width, height, data })
}
}
/// A dim studio environment of 8 × 4 pixels for an environment light that has no image: a gray
/// gradient whose radiance in direction `d` is proportional to `0.15 + 1.2 max(0, d·key)`, with
/// the key direction `(0.66, 0.75, 0)` up and toward +X. It is scaled so that the mean of its
/// pixels, each weighted by `sin θ` at its center, is 0.3.
pub fn default_environment() -> Result<EnvImage, PbrError> {
let key = V3::new(0.66, 0.75, 0.0);
let (w, h) = (8usize, 4usize);
let mut data = try_pixels(w * h)?;
let (mut mean, mut weight) = (0.0f32, 0.0f32);
for (i, px) in data.iter_mut().enumerate() {
let (x, y) = (i % w, i / w);
let sa = ((y as f32 + 0.5) / h as f32 * PI).sin();
let l = 0.15 + 1.2 * pixel_dir(x, y, w, h).dot(key).max(0.0);
*px = [l; 3];
mean += l * sa;
weight += sa;
}
let k = if mean.is_finite() && mean > 1e-6 { 0.3 * weight / mean } else { 1.0 };
for px in &mut data {
*px = px.map(|c| c * k);
}
Ok(EnvImage { width: w as u32, height: h as u32, data })
}
+15 -4
View File
@@ -22,8 +22,14 @@
//! distribution D is the one section B.3.2 writes
//! (<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#specular-brdf>).
//! Samples are importance-sampled from Hammersley points and read from a box-filtered pyramid
//! of the source at a level chosen from each sample's density. The environment BRDF term of the
//! split sum is not in this crate.
//! of the source at a level chosen from each sample's density. [`try_environment_brdf`] gives
//! the other term of the split sum, the scale and bias of `f0`.
//!
//! [`Material`] holds a glTF 2.0 metallic-roughness material, and [`Material::try_direct`]
//! evaluates its BRDF for one light in the final form of section B.3.5
//! (<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metal-brdf-and-dielectric-brdf>),
//! 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.
//!
//! 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,
@@ -39,6 +45,7 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod brdf;
mod environment;
mod prefilter;
mod sh;
@@ -47,11 +54,12 @@ mod vec3;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, dir_of, uv_of};
pub use brdf::{MAX_SPECULAR, MIN_DIRECT_ROUGHNESS, Material, try_environment_brdf};
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};
/// Why an environment could not be made, filtered or read.
/// Why an environment could not be made, filtered or read, or a material could not be shaded.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PbrError {
@@ -74,6 +82,9 @@ pub enum PbrError {
/// An option is out of its range; the text names it.
#[error("{0}")]
BadOption(&'static str),
/// A material value is not a number or is out of its range; the text names it.
#[error("{0}")]
BadMaterial(&'static str),
/// The filtering would take more sample evaluations than [`Limits::max_work`].
#[error("the filtering needs {needed} sample evaluations, over the limit of {limit}")]
TooMuchWork { needed: u64, limit: u64 },
+439
View File
@@ -0,0 +1,439 @@
//! The direct-light BRDF, the environment BRDF and the default environment: EffectCraft's tests on
//! this crate's API, a comparison with EffectCraft's code, glTF 2.0's closed forms and numeric
//! properties.
use std::f32::consts::PI;
use craft_pbr::{EnvImage, MIN_DIRECT_ROUGHNESS, Material, PbrError, default_environment, ggx_distribution, hammersley, try_environment_brdf};
use crate::reference::effectcraft as ec;
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn norm(a: [f32; 3]) -> [f32; 3] {
let l = dot(a, a).sqrt();
[a[0] / l, a[1] / l, a[2] / l]
}
fn material(base: [f32; 3], metallic: f32, roughness: f32) -> Material {
Material::try_new(base, metallic, roughness).unwrap()
}
/// Unit directions spread over the upper hemisphere of +Z, from Hammersley points, with `n·d` at
/// least `min_cos`.
fn hemisphere(count: u32, min_cos: f32) -> Vec<[f32; 3]> {
(0..count)
.filter_map(|i| {
let [a, b] = hammersley(i, count)?;
let z = min_cos + (1.0 - min_cos) * b;
let s = (1.0 - z * z).max(0.0).sqrt();
Some([s * (2.0 * PI * a).cos(), s * (2.0 * PI * a).sin(), z])
})
.collect()
}
// ------------------------------------------------------------------ moved from EffectCraft
#[test]
fn brdf_matches_cook_torrance_formula() {
// Reference: f = kd·c/π + D·G·F/(4·NV·NL), returned × NL × π.
let n = [0.0, 0.0, 1.0];
let v = norm([0.3, 0.1, 1.0]);
let l = norm([-0.4, 0.2, 1.0]);
let (base, metal, rough) = ([0.8, 0.4, 0.2], 0.3f32, 0.45f32);
let got = material(base, metal, rough).try_direct(n, v, l).unwrap();
let h = norm([v[0] + l[0], v[1] + l[1], v[2] + l[2]]);
let (nv, nl, nh, vh) = (dot(n, v), dot(n, l), dot(n, h), dot(v, h));
let a2 = (rough * rough).powi(2);
let d = a2 / (PI * ((nh * nh) * (a2 - 1.0) + 1.0).powi(2));
let k = (rough + 1.0).powi(2) / 8.0;
let g = nv / (nv * (1.0 - k) + k) * nl / (nl * (1.0 - k) + k);
for c in 0..3 {
let f0 = 0.04 + (base[c] - 0.04) * metal;
let f = f0 + (1.0 - f0) * (1.0 - vh).powi(5);
let expect = ((1.0 - f) * (1.0 - metal) * base[c] / PI + d * g * f / (4.0 * nv * nl)) * nl * PI;
assert!((got[c] - expect).abs() < 1e-5, "channel {c}: {} vs {expect}", got[c]);
}
// No light from behind the surface.
assert_eq!(material(base, metal, rough).try_direct(n, v, [0.0, 0.0, -1.0]).unwrap(), [0.0; 3]);
// A white rough dielectric lit head-on reflects about its base color (π folded in).
let w = material([1.0; 3], 0.0, 1.0).try_direct(n, n, n).unwrap();
assert!(w[0] > 0.95 && w[0] < 1.05, "{w:?}");
}
#[test]
fn env_brdf_endpoints() {
let [a, b] = try_environment_brdf(1.0, 0.0).unwrap();
assert!(a + b > 0.9 && a + b <= 1.05);
let [a, b] = try_environment_brdf(0.1, 1.0).unwrap();
assert!(a >= 0.0 && b > -0.01 && a + b < 1.0);
}
/// The default environment is a dim studio with a mean of 0.3, lit from up and toward +X, and
/// symmetric about the XY plane.
#[test]
fn default_environment_keeps_the_level_and_points_up() {
let env = default_environment().unwrap();
let (w, h) = (env.width(), env.height());
assert_eq!((w, h), (8, 4));
let (mut mean, mut weight) = (0.0f32, 0.0f32);
let mut toward = [0.0f32; 3];
for (i, p) in env.pixels().iter().enumerate() {
let (x, y) = (i % w as usize, i / w as usize);
let v = (y as f32 + 0.5) / h as f32;
let sa = (v * PI).sin();
let lum = (p[0] + p[1] + p[2]) / 3.0;
mean += lum * sa;
weight += sa;
let d = craft_pbr::dir_of((x as f32 + 0.5) / w as f32, v);
for c in 0..3 {
toward[c] += d[c] * lum * sa;
}
}
assert!((mean / weight - 0.3).abs() < 0.01, "dim studio mean: {}", mean / weight);
let t = norm(toward);
assert!(t[1] > 0.5, "the key is up: {t:?}");
assert!(t[0] > 0.3, "the key is toward +X: {t:?}");
assert!(t[2].abs() < 0.1, "symmetric about the XY plane: {t:?}");
// No texel clips past white at the default intensity.
assert!(env.pixels().iter().all(|p| p[0] <= 1.0 && p[0] > 0.0), "0 < radiance <= 1");
}
// ------------------------------------------------------------------ against EffectCraft's code
/// EffectCraft's environment direction `(x, y, z)`, with +Y down and the image center at +Z, is
/// `(−z, −y, −x)` in this crate's frame, and the same pixels hold the same light.
#[test]
fn default_environment_matches_effectcraft_in_this_crate_frame() {
let ours = default_environment().unwrap();
let (w, h, theirs) = ec::default_environment();
assert_eq!((ours.width(), ours.height()), (w, h));
for (a, b) in ours.pixels().iter().zip(&theirs) {
for c in 0..3 {
assert!((a[c] - b[c]).abs() < 1e-6, "{a:?} vs {b:?}");
}
}
for (u, v) in [(0.1f32, 0.2f32), (0.5, 0.5), (0.8, 0.9)] {
let e = ec::equirect_dir(u, v, 0.0);
let d = craft_pbr::dir_of(u, v);
for (x, y) in [(d[0], -e[2]), (d[1], -e[1]), (d[2], -e[0])] {
assert!((x - y).abs() < 1e-5, "{d:?} vs {e:?}");
}
}
}
/// From roughness 0.25 up, the direct light matches EffectCraft's `brdf` within `1e-4` of
/// `max(1, value)`. Below it, this crate's distribution is evaluated in `f64` and EffectCraft's
/// in `f32`, which loses the narrow peak, and roughness is shaded as at least 0.032 where
/// EffectCraft used 0.03.
#[test]
fn direct_light_matches_effectcraft_for_valid_inputs() {
let n = [0.0, 0.0, 1.0];
let dirs = hemisphere(24, 0.05);
for base in [[0.8, 0.4, 0.2], [1.0, 1.0, 1.0], [0.0, 0.1, 0.9]] {
for metallic in [0.0, 0.3, 1.0] {
for roughness in [0.25, 0.5, 0.8, 1.0] {
for (specular, diffuse) in [(1.0, 1.0), (2.0, 0.5), (0.0, 0.0)] {
let m = material(base, metallic, roughness).try_with_weights(specular, diffuse).unwrap();
let s = ec::BrdfSurface { base, metallic, roughness, specular, diffuse };
for &v in &dirs {
for &l in &dirs {
let a = m.try_direct(n, v, l).unwrap();
let b = ec::brdf(s, n, v, l);
for c in 0..3 {
assert!((a[c] - b[c]).abs() <= 1e-4 * 1f32.max(b[c].abs()), "{a:?} vs {b:?} at {v:?} {l:?}");
}
}
}
}
}
}
}
}
/// The environment BRDF matches EffectCraft's `env_brdf` wherever that gives a scale and bias of
/// at least 0 with a sum of at most 1.
#[test]
fn environment_brdf_matches_effectcraft_inside_its_valid_range() {
for i in 0..=50 {
for j in 0..=50 {
let (n_v, rough) = (i as f32 / 50.0, j as f32 / 50.0);
let (a, b) = ec::env_brdf(n_v, rough);
if a >= 0.0 && b >= 0.0 && a + b <= 1.0 {
let [x, y] = try_environment_brdf(n_v, rough).unwrap();
assert!((x - a).abs() <= 1e-6 && (y - b).abs() <= 1e-6, "{x}, {y} vs {a}, {b} at {n_v}, {rough}");
}
}
}
}
// ------------------------------------------------------------------ glTF 2.0 and numeric properties
/// glTF 2.0 section B.3.5's metal and dielectric BRDFs, with `vd` the specular BRDF `V D`.
fn gltf_metal(base: f32, vh: f32, vd: f32) -> f32 {
vd * (base + (1.0 - base) * (1.0 - vh.abs()).powi(5))
}
fn gltf_dielectric(base: f32, vh: f32, vd: f32) -> f32 {
let fr = 0.04 + (1.0 - 0.04) * (1.0 - vh.abs()).powi(5);
base / PI + (vd - base / PI) * fr
}
/// At metallic 0 and 1 the BRDF is glTF 2.0's dielectric and metal BRDF of section B.3.5, with
/// the specular BRDF `V D` taken from this crate's geometry term and distribution.
#[test]
fn metallic_endpoints_are_the_gltf_closed_forms() {
let n = [0.0, 0.0, 1.0];
let dirs = hemisphere(16, 0.05);
for base in [[0.9, 0.5, 0.1], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]] {
for roughness in [0.1f32, 0.4, 1.0] {
let r = roughness.max(MIN_DIRECT_ROUGHNESS);
let k = (r + 1.0) * (r + 1.0) / 8.0;
for &v in &dirs {
for &l in &dirs {
let h = norm([v[0] + l[0], v[1] + l[1], v[2] + l[2]]);
let (nv, nl, nh, vh) = (dot(n, v), dot(n, l), dot(n, h), dot(v, h));
let g = nv / (nv * (1.0 - k) + k) * nl / (nl * (1.0 - k) + k);
let vd = g / (4.0 * nv * nl) * ggx_distribution(nh, r);
let metal = material(base, 1.0, roughness).try_direct(n, v, l).unwrap();
let dielectric = material(base, 0.0, roughness).try_direct(n, v, l).unwrap();
for c in 0..3 {
let (want_m, want_d) = (gltf_metal(base[c], vh, vd), gltf_dielectric(base[c], vh, vd));
let (got_m, got_d) = (metal[c] / (nl * PI), dielectric[c] / (nl * PI));
// `try_direct` normalizes the directions again, which moves the half vector
// of the narrow lobes by a few units in the last place.
assert!((got_m - want_m).abs() <= 1e-3 * 1f32.max(want_m), "metal {got_m} vs {want_m}");
assert!((got_d - want_d).abs() <= 1e-3 * 1f32.max(want_d), "dielectric {got_d} vs {want_d}");
}
}
}
}
}
}
/// glTF 2.0 section B.3.2's separable Smith masking for one direction.
fn gltf_g1(x: f32, a: f32) -> f32 {
2.0 * x / (x + (a * a + (1.0 - a * a) * x * x).sqrt())
}
/// The Smith-Schlick geometry term with `k = (r + 1)² / 8` is glTF's separable Smith term at
/// roughness 1, and darker than it at grazing angles on smoother surfaces.
#[test]
fn the_geometry_term_against_the_gltf_separable_smith_form() {
let n = [0.0, 0.0, 1.0];
let spec = |roughness: f32, v: [f32; 3], l: [f32; 3]| {
// A white metal reflects only its specular lobe, with F = 1.
material([1.0; 3], 1.0, roughness).try_direct(n, v, l).unwrap()[0]
};
for &v in &hemisphere(16, 0.05) {
for &l in &hemisphere(16, 0.05) {
let h = norm([v[0] + l[0], v[1] + l[1], v[2] + l[2]]);
let (nv, nl) = (dot(n, v), dot(n, l));
let want = gltf_g1(nv, 1.0) * gltf_g1(nl, 1.0) * ggx_distribution(dot(n, h), 1.0) / (4.0 * nv * nl) * nl * PI;
let got = spec(1.0, v, l);
assert!((got - want).abs() <= 1e-4 * want.max(1.0), "{got} vs {want}");
}
}
let r = 0.25f32;
let (v, l) = (norm([0.995, 0.0, 0.1]), norm([-0.995, 0.0, 0.1]));
let karis = spec(r, v, l);
let ggx = gltf_g1(0.1, r * r) * gltf_g1(0.1, r * r) * ggx_distribution(1.0, r) / (4.0 * 0.1 * 0.1) * 0.1 * PI;
assert!(karis < 0.5 * ggx, "{karis} vs {ggx}");
}
/// A unit vector along `d`, computed in the same steps and order as the crate normalizes
/// directions: divided by its largest component, then multiplied by the reciprocal length.
fn crate_unit(d: [f32; 3]) -> [f32; 3] {
let big = d[0].abs().max(d[1].abs()).max(d[2].abs());
let s = [d[0] / big, d[1] / big, d[2] / big];
let r = 1.0 / ((s[0] * s[0]) + (s[1] * s[1]) + (s[2] * s[2])).sqrt();
[s[0] * r, s[1] * r, s[2] * r]
}
/// The light a material reflects from a uniform white sky onto a surface seen at `theta`: the
/// specular lobe by GGX importance sampling of the half vector, and the diffuse lobe by cosine
/// sampling of the light.
fn albedo(m: &Material, theta: f32, steps: u32) -> f64 {
let n = [0.0, 0.0, 1.0];
let v = [theta.sin(), 0.0, theta.cos()];
let spec_only = m.try_with_weights(m.specular(), 0.0).unwrap();
let a = m.roughness().max(MIN_DIRECT_ROUGHNESS).powi(2);
let (mut spec, mut diff) = (0.0f64, 0.0f64);
for i in 0..steps {
let xi = (i as f32 + 0.5) / steps as f32;
for j in 0..steps {
let phi = 2.0 * PI * (j as f32 + 0.5) / steps as f32;
// Specular: a half vector drawn from D (n·h), a light reflected about it.
let ct = ((1.0 - xi) / (1.0 + (a * a - 1.0) * xi)).sqrt();
let st = (1.0 - ct * ct).max(0.0).sqrt();
let hv = [st * phi.cos(), st * phi.sin(), ct];
let vh = dot(v, hv);
if vh > 0.0 {
let l = [2.0 * vh * hv[0] - v[0], 2.0 * vh * hv[1] - v[1], 2.0 * vh * hv[2] - v[2]];
if l[2] > 0.0 {
// The density at the half vector `try_direct` finds again from `v` and `l`,
// rounded the same way: near `n·h` = 1 one `f32` step changes `D` of the
// narrowest lobes by about 24%.
let (uv, ul) = (crate_unit(v), crate_unit(l));
let h = crate_unit([uv[0] + ul[0], uv[1] + ul[1], uv[2] + ul[2]]);
let pdf = ggx_distribution(h[2], m.roughness().max(MIN_DIRECT_ROUGHNESS)) * h[2] / (4.0 * dot(uv, h));
spec += f64::from(spec_only.try_direct(n, v, l).unwrap()[0] / PI / pdf);
}
}
// Diffuse: a light drawn from n·l / π.
let (cl, sl) = ((1.0 - xi).sqrt(), xi.sqrt());
let l = [sl * phi.cos(), sl * phi.sin(), cl];
let d = m.try_direct(n, v, l).unwrap()[0] - spec_only.try_direct(n, v, l).unwrap()[0];
diff += f64::from(d / cl);
}
}
(spec + diff) / f64::from(steps * steps)
}
const ANGLES: [f32; 8] = [0.0, 30.0, 60.0, 75.0, 80.0, 85.0, 89.0, 89.9];
const ROUGHNESS: [f32; 9] = [0.0, 0.01, 0.032, 0.05, 0.1, 0.25, 0.5, 0.75, 1.0];
/// A white furnace: a white metal, whose BRDF is the specular lobe alone with `F = 1`, reflects
/// at most the light it receives at every roughness and view angle.
#[test]
fn a_white_metal_reflects_at_most_the_light_it_receives() {
for roughness in ROUGHNESS {
for deg in ANGLES {
let e = albedo(&material([1.0; 3], 1.0, roughness), deg.to_radians(), 96);
assert!(e <= 1.0 + 1e-3, "roughness {roughness} at {deg}°: {e}");
assert!(e > 0.0, "roughness {roughness} at {deg}°: {e}");
}
}
}
/// glTF 2.0 section B.3.6.3 notes that the Fresnel coupling of the diffuse and specular lobes in
/// section B.3.5 does not conserve energy. For a white dielectric the excess is largest on smooth
/// surfaces seen about 80 degrees from the normal, where it is about 9.8%.
#[test]
fn a_white_dielectric_reflects_at_most_ten_percent_more_than_it_receives() {
for roughness in ROUGHNESS {
for deg in ANGLES {
let e = albedo(&material([1.0; 3], 0.0, roughness), deg.to_radians(), 96);
assert!(e <= 1.1, "roughness {roughness} at {deg}°: {e}");
}
}
assert!(albedo(&material([1.0; 3], 0.0, 0.5), 0.0, 96) <= 1.0, "head-on the lobes conserve energy");
}
#[test]
fn the_brdf_is_reciprocal() {
let n = norm([0.1, -0.2, 1.0]);
let dirs: Vec<[f32; 3]> = hemisphere(20, 0.2).into_iter().map(|d| norm([d[0] + 0.1, d[1] - 0.2, d[2]])).collect();
for (base, metallic) in [([0.7, 0.3, 0.1], 0.0), ([0.9, 0.8, 0.2], 1.0), ([0.5; 3], 0.4)] {
for roughness in [0.05, 0.3, 0.9] {
let m = material(base, metallic, roughness);
for &v in &dirs {
for &l in &dirs {
let (nv, nl) = (dot(n, v), dot(n, l));
if nv < 1e-2 || nl < 1e-2 {
continue;
}
let a = m.try_direct(n, v, l).unwrap();
let b = m.try_direct(n, l, v).unwrap();
for c in 0..3 {
let (x, y) = (a[c] / nl, b[c] / nv);
assert!((x - y).abs() <= 1e-4 * x.abs().max(1.0), "{x} vs {y}");
}
}
}
}
}
}
/// Roughness below `MIN_DIRECT_ROUGHNESS` is shaded as that roughness, and its highlight peak is
/// finite.
#[test]
fn roughness_is_clamped_at_the_documented_floor() {
let n = [0.0, 0.0, 1.0];
let (v, l) = (norm([0.2, 0.0, 1.0]), norm([-0.2, 0.0, 1.0]));
let at = |r: f32| material([0.8; 3], 1.0, r).try_direct(n, v, l).unwrap();
let floor = at(MIN_DIRECT_ROUGHNESS);
assert!(floor.iter().all(|c| c.is_finite() && *c > 0.0), "{floor:?}");
for r in [0.0, 1e-6, 0.01, 0.03, MIN_DIRECT_ROUGHNESS] {
assert_eq!(at(r), floor, "roughness {r}");
}
assert!(at(MIN_DIRECT_ROUGHNESS + 0.01)[0] < floor[0], "a rougher surface has a lower peak");
}
#[test]
fn the_environment_brdf_keeps_reflectance_between_0_and_1() {
for i in 0..=60 {
for j in 0..=40 {
let (n_v, rough) = (i as f32 / 40.0 - 0.25, j as f32 / 40.0);
let [scale, bias] = try_environment_brdf(n_v, rough).unwrap();
assert!(scale >= 0.0 && bias >= 0.0 && scale + bias <= 1.0, "{scale}, {bias} at {n_v}, {rough}");
}
}
// A smooth surface seen at a grazing angle reflects all the light, whatever its f0.
assert_eq!(try_environment_brdf(0.0, 0.0).unwrap(), [0.0, 1.0]);
}
#[test]
fn valid_inputs_give_finite_non_negative_light() {
let n = [0.0, 0.0, 1.0];
let all: Vec<[f32; 3]> = hemisphere(32, -1.0);
for base in [[0.0; 3], [1.0; 3]] {
for metallic in [0.0, 1.0] {
for roughness in [0.0, 1.0] {
for (specular, diffuse) in [(0.0, 0.0), (craft_pbr::MAX_SPECULAR, 1.0)] {
let m = material(base, metallic, roughness).try_with_weights(specular, diffuse).unwrap();
for &v in &all {
for &l in &all {
let out = m.try_direct(n, v, l).unwrap();
assert!(out.iter().all(|c| c.is_finite() && *c >= 0.0), "{out:?} at {v:?} {l:?}");
}
let huge = m.try_direct([0.0, 0.0, 1e30], v, [1e-30, 0.0, 1e-30]).unwrap();
assert!(huge.iter().all(|c| c.is_finite() && *c >= 0.0), "{huge:?}");
}
// A view straight opposite the light has no half vector.
assert_eq!(m.try_direct(n, [0.0, 0.6, -0.8], [0.0, -0.6, 0.8]).unwrap(), [0.0; 3]);
}
}
}
}
}
#[test]
fn values_that_are_not_finite_or_out_of_range_are_refused() {
let bad = [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.01, 1.01];
for x in bad {
assert!(matches!(Material::try_new([x, 0.5, 0.5], 0.0, 0.5), Err(PbrError::BadMaterial(_))), "base {x}");
assert!(matches!(Material::try_new([0.5; 3], x, 0.5), Err(PbrError::BadMaterial(_))), "metallic {x}");
assert!(matches!(Material::try_new([0.5; 3], 0.0, x), Err(PbrError::BadMaterial(_))), "roughness {x}");
assert!(matches!(material([0.5; 3], 0.0, 0.5).try_with_weights(1.0, x), Err(PbrError::BadMaterial(_))), "diffuse {x}");
assert!(matches!(try_environment_brdf(0.5, x), Err(PbrError::BadMaterial(_))), "environment roughness {x}");
}
for x in [f32::NAN, f32::INFINITY, -0.01, craft_pbr::MAX_SPECULAR + 0.01] {
assert!(matches!(material([0.5; 3], 0.0, 0.5).try_with_weights(x, 1.0), Err(PbrError::BadMaterial(_))), "specular {x}");
}
for x in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
assert_eq!(try_environment_brdf(x, 0.5), Err(PbrError::BadDirection), "n·v {x}");
}
let m = material([0.5; 3], 0.0, 0.5);
let ok = [0.0, 0.0, 1.0];
for d in [[0.0; 3], [f32::NAN, 0.0, 1.0], [0.0, f32::INFINITY, 1.0], [f32::NEG_INFINITY, 0.0, 0.0]] {
assert_eq!(m.try_direct(d, ok, ok), Err(PbrError::BadDirection), "normal {d:?}");
assert_eq!(m.try_direct(ok, d, ok), Err(PbrError::BadDirection), "view {d:?}");
assert_eq!(m.try_direct(ok, ok, d), Err(PbrError::BadDirection), "light {d:?}");
}
}
/// The default environment is a valid environment for the rest of the crate.
#[test]
fn the_default_environment_prefilters_and_projects() {
let env: EnvImage = default_environment().unwrap();
let limits = craft_pbr::Limits::default();
let mips = craft_pbr::try_prefilter(&env, &craft_pbr::PrefilterOptions::default(), &limits).unwrap();
assert!(mips.iter().all(|m| m.pixels().iter().all(|p| p.iter().all(|c| c.is_finite() && *c >= 0.0))));
let sh = craft_pbr::try_sh9(&env, &limits).unwrap();
let up = craft_pbr::irradiance(&sh, [0.66, 0.75, 0.0]).unwrap()[0];
let down = craft_pbr::irradiance(&sh, [-0.66, -0.75, 0.0]).unwrap()[0];
assert!(up > down, "the key side is brighter: {up} vs {down}");
}
+3 -1
View File
@@ -4,12 +4,14 @@
mod bench;
mod bounds;
mod brdf;
mod differential;
mod moved;
mod numeric;
/// Verbatim copies of the apps' previous code, run by `differential`.
/// Verbatim copies of the apps' previous code, run by `differential` and `brdf`.
mod reference {
pub mod effectcraft;
pub mod materialcraft;
pub mod texturecraft;
}
@@ -0,0 +1,128 @@
//! The shading functions of EffectCraft's `crates/render/src/three_d/adv/shade.rs` and its
//! `default_environment` from `adv/scene.rs`, at 41da144555, copied as they are apart from
//! visibility and the scaling loop of `default_environment`, which iterates over the channels
//! instead of indexing them.
pub const PI: f32 = std::f32::consts::PI;
#[inline]
pub fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
#[inline]
pub fn norm(a: [f32; 3]) -> [f32; 3] {
let l = dot(a, a).sqrt();
if l > 1e-20 { [a[0] / l, a[1] / l, a[2] / l] } else { [0.0, 0.0, -1.0] }
}
#[inline]
fn add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
#[inline]
fn mix(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
/// GGX / Trowbridge–Reitz normal distribution, `a = roughness²`.
#[inline]
pub fn d_ggx(n_h: f32, a: f32) -> f32 {
let a2 = a * a;
let d = n_h * n_h * (a2 - 1.0) + 1.0;
a2 / (PI * d * d).max(1e-12)
}
/// Smith–Schlick-GGX geometry term for direct light (`k = (r + 1)² / 8`).
#[inline]
pub fn g_smith(n_v: f32, n_l: f32, rough: f32) -> f32 {
let k = (rough + 1.0) * (rough + 1.0) / 8.0;
let g1 = |x: f32| x / (x * (1.0 - k) + k);
g1(n_v) * g1(n_l)
}
/// Schlick's Fresnel approximation.
#[inline]
pub fn f_schlick(f0: [f32; 3], v_h: f32) -> [f32; 3] {
let k = (1.0 - v_h).clamp(0.0, 1.0).powi(5);
[f0[0] + (1.0 - f0[0]) * k, f0[1] + (1.0 - f0[1]) * k, f0[2] + (1.0 - f0[2]) * k]
}
/// Surface parameters used by the direct-light BRDF after texture sampling.
#[derive(Clone, Copy)]
pub struct BrdfSurface {
pub base: [f32; 3],
pub metallic: f32,
pub roughness: f32,
pub specular: f32,
pub diffuse: f32,
}
/// Cook–Torrance BRDF × N·L × π for one light: (diffuse colour factor, specular colour).
/// Returned as the reflected fraction of the light's irradiance.
pub fn brdf(surface: BrdfSurface, n: [f32; 3], v: [f32; 3], l: [f32; 3]) -> [f32; 3] {
let BrdfSurface { base, metallic, roughness: rough, specular: spec_k, diffuse: diff_k } = surface;
let n_l = dot(n, l);
if n_l <= 0.0 {
return [0.0; 3];
}
let n_v = dot(n, v).max(1e-4);
let h = norm(add(v, l));
let n_h = dot(n, h).max(0.0);
let v_h = dot(v, h).max(0.0);
let r = rough.clamp(0.03, 1.0);
let f0 = [mix(0.04 * spec_k, base[0], metallic), mix(0.04 * spec_k, base[1], metallic), mix(0.04 * spec_k, base[2], metallic)];
let f = f_schlick(f0, v_h);
let d = d_ggx(n_h, r * r);
let g = g_smith(n_v, n_l, r);
let spec = d * g / (4.0 * n_v * n_l).max(1e-4);
let mut out = [0.0; 3];
for c in 0..3 {
let kd = (1.0 - f[c]) * (1.0 - metallic);
out[c] = (kd * base[c] / PI * diff_k + f[c] * spec) * n_l * PI;
}
out
}
/// Split-sum environment BRDF (scale, bias) for `F0·A + B` (analytic fit).
#[inline]
pub fn env_brdf(n_v: f32, rough: f32) -> (f32, f32) {
let c0 = [-1.0, -0.0275, -0.572, 0.022];
let c1 = [1.0, 0.0425, 1.04, -0.04];
let r = [rough * c0[0] + c1[0], rough * c0[1] + c1[1], rough * c0[2] + c1[2], rough * c0[3] + c1[3]];
let a004 = (r[0] * r[0]).min((-9.28 * n_v).exp2()) * r[0] + r[1];
(-1.04 * a004 + r[2], 1.04 * a004 + r[3])
}
/// Inverse of `equirect_uv` (texel centre → direction).
pub fn equirect_dir(u: f32, v: f32, rot: f32) -> [f32; 3] {
let phi = (u - 0.5) * 2.0 * PI - rot;
let th = v * PI;
[th.sin() * phi.sin(), -th.cos(), th.sin() * phi.cos()]
}
pub fn default_environment() -> (u32, u32, Vec<[f32; 4]>) {
// The key region's centre: three quarters up, two thirds toward the viewer (the default
// camera looks +z from -z).
let key = [0.0f32, -0.75, -0.66];
let (w, h) = (8u32, 4u32);
let mut data = Vec::with_capacity((w * h) as usize);
let (mut mean, mut weight) = (0.0f32, 0.0f32);
for y in 0..h {
let v = (y as f32 + 0.5) / h as f32;
let sa = (v * std::f32::consts::PI).sin();
for x in 0..w {
let u = (x as f32 + 0.5) / w as f32;
let l = 0.15 + 1.2 * dot(equirect_dir(u, v, 0.0), key).max(0.0);
data.push([l, l, l, 1.0]);
mean += l * sa;
weight += sa;
}
}
// A dim studio: scale the gradient to a weighted mean of exactly 0.3.
let k = if mean.is_finite() && mean > 1e-6 { 0.3 * weight / mean } else { 1.0 };
for p in &mut data {
for c in p.iter_mut().take(3) {
*c *= k;
}
}
(w, h, data)
}