craft-pbr: GGX environment prefilter and SH9 irradiance for TextureCraft and MaterialCraft

New crate craft-pbr with the image-based lighting code that TextureCraft
and MaterialCraft each keep in crates/render/src/ibl.rs: an equirect
EnvImage, the split-sum GGX prefilter chain (Karis 2013, GGX as glTF 2.0
sections B.2.3 and B.3.2 define it), nine SH irradiance coefficients and
the six procedural environments.

With a firefly cap of 64, which both apps apply, the prefiltered levels
match the apps' code exactly for sources with even sides; a differential
test runs a copy of that code against the crate. Changes from it:

- Halving an odd side keeps its last column or row.
- The firefly cap and the level bias are options; the cap is off by
  default.
- Sizes, buffer lengths, radiance (0 to MAX_RADIANCE), options and
  directions are checked, and memory and sample work are bounded by
  Limits, before anything is allocated. Buffers are reserved fallibly.
- The SH projection reads every pixel and integrates each basis function
  over the pixel's area, so a uniform source of any size gives uniform
  irradiance and rows near the poles keep their solid angle.
- rayon is behind the optional `parallel` feature; the default build
  compiles for wasm32-unknown-unknown.

On a 256 x 128 source the default prefilter evaluates 1,396,736 samples.
This commit is contained in:
dotCooCoo
2026-11-21 06:15:17 -08:00
parent 531f12d235
commit 3f89a2cba8
17 changed files with 2153 additions and 1 deletions
Generated
+18 -1
View File
@@ -2809,6 +2809,17 @@ dependencies = [
name = "craft-palette"
version = "0.1.0"
[[package]]
name = "craft-pbr"
version = "0.1.0"
dependencies = [
"craft-pbr",
"craft-texture",
"glam 0.30.10",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "craft-pcap"
version = "0.1.0"
@@ -4061,7 +4072,7 @@ checksum = "e917a58e17b27d2f15626c490754ccced7f46592dc5b5f39a3013b89cba5f068"
dependencies = [
"astc-decode",
"bitflags 2.13.2",
"glam",
"glam 0.25.0",
"resize",
"zerocopy",
]
@@ -5555,6 +5566,12 @@ version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3"
[[package]]
name = "glam"
version = "0.30.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
[[package]]
name = "glifo"
version = "0.1.1"
+1
View File
@@ -202,6 +202,7 @@ craft-testkit = { path = "crates/testkit" }
craft-text = { path = "crates/text" }
craft-tcraft = { path = "crates/tcraft" }
craft-texture = { path = "crates/texture" }
craft-pbr = { path = "crates/pbr" }
craft-tga = { path = "crates/tga" }
craft-timeline = { path = "crates/timeline" }
craft-tiff = { path = "crates/tiff" }
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "craft-pbr"
description = "Image-based lighting for physically based rendering: equirect environments, a GGX-prefiltered specular chain and SH9 diffuse irradiance"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[features]
default = []
parallel = ["dep:rayon"]
[lints]
workspace = true
[dependencies]
craft-texture = { workspace = true }
rayon = { workspace = true, optional = true }
thiserror = { workspace = true }
[dev-dependencies]
craft-pbr = { path = ".", features = ["parallel"] }
# The differential tests run verbatim copies of the apps' previous code, which uses glam and rayon.
glam = "0.30"
rayon = { workspace = true }
+89
View File
@@ -0,0 +1,89 @@
# craft-pbr
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.
- **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
toward +Z. Lookups wrap horizontally and clamp vertically. `dir_of` and `uv_of` convert between
the two. An image in another frame is converted by the caller first: an OpenEXR
latitude-longitude image puts longitude 0 at +Z
(<https://openexr.com/en/latest/ReadingAndWritingImageFiles.html>).
- **Construction.** `EnvImage::try_from_linear` takes linear radiance and returns an error for a
NaN or negative value or one above `MAX_RADIANCE` (1e28, which keeps every sum of samples
within `f32`). `EnvImage::try_from_rgba` takes RGBA pixels, linear or sRGB
(`ColorEncoding`), replaces NaN, infinite and negative values with 0, caps values at 65,000 and
decodes sRGB with `craft_texture::srgb_to_linear`. Neither changes the size. `try_half` halves
each side by box averaging; the last column or row of an odd side is kept in the average.
`try_resampled` resamples by bilinear lookup at each pixel's direction. `sample` is a bilinear
lookup by direction.
- **Specular.** `try_prefilter` returns `PrefilterOptions::levels` levels (default 6). Level 0 is
a copy of the source; level `l` of `n` is filtered for roughness `l / (n - 1)` and halves each
side of the level before, keeping at least 4 × 2 pixels and never growing. The filtering is the
split-sum prefilter of Karis, *Real Shading in Unreal Engine 4* (SIGGRAPH 2013,
<https://de45xmedrsdbp.cloudfront.net/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf>):
view and reflection directions equal to the normal, GGX importance samples from Hammersley
points (`samples`, default 128), each weighted by `n·l`. The GGX distribution uses
`α = roughness²`, as glTF 2.0 section B.2.3 defines it
(<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces>), and
`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.
- **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,
<https://graphics.stanford.edu/papers/envmap/envmap.pdf>) and divided by `π`.
`irradiance` evaluates them: for a white surface the result is the diffuse radiance it
reflects.
- **Procedural environments.** `Environment` lists Studio Soft, Studio Contrast, Overcast, Sunset,
Warehouse and Night (`ENVIRONMENTS` holds the names). `try_render(width)` renders one at
`width × width / 2`.
- **Limits.** `Limits` caps the side (2048), the pixels of one image (2^22), the bytes one call
holds at once (256 MiB, counting the source copies, the pyramid, every level and the sample
table of `try_prefilter`; a single level is only a copy of the source), the levels (8), the samples per pixel (1024) and the sample
evaluations of one `try_prefilter` call (2^28). Every `try_` function checks its source against
them and returns a `PbrError` before allocating over them, and a buffer is never larger than
`isize::MAX` bytes even with raised limits. Pixel buffers are reserved fallibly
(`PbrError::OutOfMemory`). Options out of range give
`PbrError::BadOption`, and directions that are not finite or have zero length give
`PbrError::BadDirection`.
- **Features.** `parallel` computes rows on several threads with rayon. The default build is
serial and builds for `wasm32-unknown-unknown`. Results are the same either way.
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).
## Origin
The algorithms come from the `crates/render/src/ibl.rs` files of TextureCraft and MaterialCraft,
which held the same filtering code. With a firefly cap of 64, which both apps applied, the
prefiltered levels match theirs for sources with even sides. Changes from those files:
- Halving an odd side keeps its last column or row instead of dropping it.
- The firefly cap is an option, off by default, and the source level bias is an option.
- Sizes, buffer lengths, radiance values, options and directions are checked, and work and memory
are bounded, before anything is allocated.
- Level sizes never grow past the level before, so a source smaller than 4 × 2 is accepted.
- The SH projection reads every pixel of the source instead of a source halved to 128 wide by
plain averaging, which gave rows near the poles too much weight (a lit top row of a 256 × 128
source counted twice). It integrates each basis function over the area of each pixel instead of
taking its value and solid angle at the pixel center, so a uniform source of any size, down to
1 × 1, gives uniform irradiance. It sums in `f64`. On the procedural environments the
irradiance changes by less than 0.04% at 128 rows and about `1.3 / rows²` of its value on fewer
rows (3.2e-4 on 64).
- Rows run on several threads only with the `parallel` feature.
## Migration
- **TextureCraft.** Replace `texturecraft_render::ibl` with `craft_pbr`. Pass
`PrefilterOptions` with `firefly_cap: Some(64.0)` to keep today's output. `EnvImage::from_rgba`
becomes `EnvImage::try_from_rgba` followed by the app's import sizing: `try_half` while a side is
over 2048, then `try_resampled` up to at least 128 × 64.
- **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`.
+333
View File
@@ -0,0 +1,333 @@
//! Equirect environment images, their construction and lookup, and the procedural environments.
use std::f32::consts::{PI, TAU};
use crate::vec3::{V3, unit};
use crate::{Limits, PbrError, for_each_row, try_pixels};
/// An equirect environment of linear RGB radiance, row-major with the top row first. Every value
/// is between 0 and [`MAX_RADIANCE`], and both sides are at least 1.
#[derive(Clone, Debug, PartialEq)]
pub struct EnvImage {
width: u32,
height: u32,
data: Vec<[f32; 3]>,
}
/// How [`EnvImage::try_from_rgba`] reads its color channels.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorEncoding {
/// Linear radiance; values above 1 are kept.
Linear,
/// sRGB-encoded values in `0..=1`; larger values read as 1.
Srgb,
}
/// Largest radiance an [`EnvImage`] holds. Sums of up to `u32::MAX` weighted samples of it stay
/// within `f32`, so averaging and filtering cannot overflow.
pub const MAX_RADIANCE: f32 = 1e28;
/// Names of the procedural environments, in [`Environment::ALL`] order.
pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"];
/// A procedural environment: a sky gradient with soft rectangular lights or a sun.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Environment {
#[default]
StudioSoft,
StudioContrast,
Overcast,
Sunset,
Warehouse,
Night,
}
/// The direction of equirect coordinates `(u, v)`, each in `0..=1`.
pub fn dir_of(u: f32, v: f32) -> [f32; 3] {
dir(u, v).to_array()
}
/// The equirect coordinates `(u, v)` of a unit direction, `u` in `0..1` and `v` in `0..=1`.
pub fn uv_of(d: [f32; 3]) -> [f32; 2] {
uv(V3::from_array(d))
}
pub(crate) fn dir(u: f32, v: f32) -> V3 {
let (theta, phi) = (v * PI, u * TAU);
V3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin())
}
fn uv(d: V3) -> [f32; 2] {
let phi = d.z.atan2(d.x);
[(phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI]
}
/// The direction at the center of pixel `(x, y)` of a `w × h` image.
pub(crate) fn pixel_dir(x: usize, y: usize, w: usize, h: usize) -> V3 {
dir((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32)
}
impl EnvImage {
/// An environment of linear radiance, `width × height` pixels. Returns an error when the size
/// is over `limits`, the buffer does not hold `width × height` pixels, or a value is NaN,
/// negative or above [`MAX_RADIANCE`].
pub fn try_from_linear(width: u32, height: u32, data: Vec<[f32; 3]>, limits: &Limits) -> Result<EnvImage, PbrError> {
let expected = limits.check(width, height)?;
if data.len() != expected {
return Err(PbrError::BadDataLength { expected, found: data.len() });
}
if let Some(index) = data.iter().position(|p| p.iter().any(|v| !(0.0..=MAX_RADIANCE).contains(v))) {
return Err(PbrError::BadRadiance { index });
}
Ok(EnvImage { width, height, data })
}
/// An environment from RGBA pixels (alpha is ignored), row-major with the top row first.
/// NaN, infinite and negative values become 0 and values are capped at 65,000, the largest
/// a half float holds near its top. [`ColorEncoding::Srgb`] values are decoded to linear after
/// capping at 1. Returns an error when the size is over `limits` or the slice does not hold
/// `width × height` pixels. The size is kept as given.
pub fn try_from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], encoding: ColorEncoding, limits: &Limits) -> Result<EnvImage, PbrError> {
let expected = limits.check(width, height)?;
if rgba.len() != expected {
return Err(PbrError::BadDataLength { expected, found: rgba.len() });
}
let lin = |v: f32| {
let v = if v.is_finite() { v.clamp(0.0, 65_000.0) } else { 0.0 };
match encoding {
ColorEncoding::Linear => v,
ColorEncoding::Srgb => craft_texture::srgb_to_linear(v.min(1.0)),
}
};
let mut data = try_pixels(expected)?;
for (out, p) in data.iter_mut().zip(rgba) {
*out = [lin(p[0]), lin(p[1]), lin(p[2])];
}
Ok(EnvImage { width, height, data })
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
/// The pixels, row-major with the top row first.
pub fn pixels(&self) -> &[[f32; 3]] {
&self.data
}
pub fn into_pixels(self) -> Vec<[f32; 3]> {
self.data
}
/// The pixel at column `x` (wrapped) and row `y` (clamped).
pub(crate) fn get(&self, x: i64, y: i64) -> V3 {
let w = i64::from(self.width.max(1));
let xx = x.rem_euclid(w) as usize;
let yy = y.clamp(0, i64::from(self.height.max(1)) - 1) as usize;
self.data.get(yy * self.width as usize + xx).map_or(V3::ZERO, |v| V3::from_array(*v))
}
/// Bilinear lookup by direction. `d` need not be unit length. Returns
/// [`PbrError::BadDirection`] when it is not finite or has zero length.
pub fn sample(&self, d: [f32; 3]) -> Result<[f32; 3], PbrError> {
let d = unit(d).ok_or(PbrError::BadDirection)?;
Ok(self.sample_v(d).to_radiance_array())
}
/// Bilinear lookup by a finite direction.
pub(crate) fn sample_v(&self, d: V3) -> V3 {
let [u, v] = uv(d);
let (fx, fy) = (u * self.width as f32 - 0.5, v * self.height as f32 - 0.5);
let (x0, y0) = (fx.floor() as i64, fy.floor() as i64);
let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
let a = self.get(x0, y0).lerp(self.get(x0 + 1, y0), tx);
let b = self.get(x0, y0 + 1).lerp(self.get(x0 + 1, y0 + 1), tx);
a.lerp(b, ty)
}
/// Box-downsamples by 2 to `max(width / 2, 1) × max(height / 2, 1)`. Each output pixel
/// averages the source area it covers, so the last column or row of an odd side is kept in
/// the average.
pub fn try_half(&self, limits: &Limits) -> Result<EnvImage, PbrError> {
let (w, h) = half_size(self.width, self.height);
let len = limits.check(w, h)?;
let mut data = try_pixels(len)?;
if self.width.is_multiple_of(2) && self.height.is_multiple_of(2) {
for_each_row(&mut data, w as usize, |y, row| {
for (x, px) in row.iter_mut().enumerate() {
let (sx, sy) = (x as i64 * 2, y as i64 * 2);
let s = (self.get(sx, sy) + self.get(sx + 1, sy) + self.get(sx, sy + 1) + self.get(sx + 1, sy + 1)) * 0.25;
*px = s.to_radiance_array();
}
});
} else {
let (wx, wy) = (box_weights(self.width, w), box_weights(self.height, h));
for_each_row(&mut data, w as usize, |y, row| {
let ys = wy.get(y).map_or(&[][..], Vec::as_slice);
for (x, px) in row.iter_mut().enumerate() {
let mut acc = V3::ZERO;
for &(sy, fy) in ys {
for &(sx, fx) in wx.get(x).map_or(&[][..], Vec::as_slice) {
acc += self.get(sx as i64, sy as i64) * (fx * fy);
}
}
*px = acc.to_radiance_array();
}
});
}
Ok(EnvImage { width: w, height: h, data })
}
/// Resamples to `width × height` by bilinear lookup at each output pixel's direction.
pub fn try_resampled(&self, width: u32, height: u32, limits: &Limits) -> Result<EnvImage, PbrError> {
let len = limits.check(width, height)?;
let mut data = try_pixels(len)?;
let (w, h) = (width as usize, height as usize);
for_each_row(&mut data, w, |y, row| {
for (x, px) in row.iter_mut().enumerate() {
*px = self.sample_v(pixel_dir(x, y, w, h)).to_radiance_array();
}
});
Ok(EnvImage { width, height, data })
}
}
/// The size [`EnvImage::try_half`] gives.
pub(crate) fn half_size(w: u32, h: u32) -> (u32, u32) {
((w / 2).max(1), (h / 2).max(1))
}
/// For each of `dst` output pixels along one axis, the source pixels it covers and the share of
/// its width each covers. The shares of one output pixel add up to 1.
fn box_weights(src: u32, dst: u32) -> Vec<Vec<(usize, f32)>> {
let scale = f64::from(src) / f64::from(dst);
(0..dst)
.map(|i| {
let (lo, hi) = (f64::from(i) * scale, f64::from(i + 1) * scale);
let first = lo.floor() as usize;
let last = (hi.ceil() as usize).min(src as usize);
(first..last)
.filter_map(|s| {
let cover = (hi.min(s as f64 + 1.0) - lo.max(s as f64)) / scale;
(cover > 0.0).then_some((s, cover as f32))
})
.collect()
})
.collect()
}
/// A soft rectangular light: azimuth and elevation of its center and its half sizes, in degrees.
struct SoftBox {
az: f32,
el: f32,
hw: f32,
hh: f32,
color: V3,
}
impl SoftBox {
fn eval(&self, d: V3) -> V3 {
let el = d.y.clamp(-1.0, 1.0).asin().to_degrees();
let az = d.z.atan2(d.x).to_degrees();
let daz = ((az - self.az + 540.0).rem_euclid(360.0)) - 180.0;
let (x, y) = (daz.abs() / self.hw, (el - self.el).abs() / self.hh);
let e = |t: f32| 1.0 - smooth((t - 0.8) / 0.4);
self.color * e(x) * e(y)
}
}
fn smooth(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
fn sky(d: V3, zenith: V3, horizon: V3, ground: V3) -> V3 {
if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(0.6)) } else { horizon.lerp(ground, (-d.y).powf(0.25)) }
}
const fn soft(az: f32, el: f32, hw: f32, hh: f32, color: V3) -> SoftBox {
SoftBox { az, el, hw, hh, color }
}
impl Environment {
/// Every environment, in menu order.
pub const ALL: [Environment; 6] = [
Environment::StudioSoft,
Environment::StudioContrast,
Environment::Overcast,
Environment::Sunset,
Environment::Warehouse,
Environment::Night,
];
/// The display name, one of [`ENVIRONMENTS`].
pub fn name(self) -> &'static str {
match self {
Environment::StudioSoft => "Studio Soft",
Environment::StudioContrast => "Studio Contrast",
Environment::Overcast => "Overcast",
Environment::Sunset => "Sunset",
Environment::Warehouse => "Warehouse",
Environment::Night => "Night",
}
}
/// The environment with display name `name`, or `None` for another name.
pub fn from_name(name: &str) -> Option<Environment> {
Environment::ALL.into_iter().find(|e| e.name() == name)
}
fn radiance(self, d: V3) -> V3 {
match self {
Environment::StudioContrast => {
let base = sky(d, V3::splat(0.04), V3::splat(0.03), V3::splat(0.01));
base + soft(35.0, 30.0, 22.0, 18.0, V3::new(14.0, 13.2, 12.0)).eval(d) + soft(-150.0, 40.0, 6.0, 30.0, V3::new(4.0, 4.4, 5.0)).eval(d)
}
Environment::Overcast => {
let base = sky(d, V3::new(1.2, 1.25, 1.35), V3::new(0.95, 0.95, 0.95), V3::new(0.18, 0.2, 0.15));
base + soft(60.0, 55.0, 40.0, 25.0, V3::splat(0.6)).eval(d)
}
Environment::Sunset => {
let base = sky(d, V3::new(0.15, 0.25, 0.55), V3::new(1.4, 0.65, 0.3), V3::new(0.08, 0.06, 0.05));
let sun = smooth((d.dot(dir(0.12, 0.47)) - 0.9985) / 0.0012) * 120.0;
base + V3::new(1.0, 0.6, 0.3) * sun
}
Environment::Warehouse => {
let mut c = sky(d, V3::splat(0.25), V3::splat(0.18), V3::splat(0.06));
for k in 0..6 {
c += soft(-150.0 + k as f32 * 60.0, 50.0, 6.0, 3.0, V3::new(9.0, 8.5, 7.5)).eval(d);
}
c + soft(90.0, 5.0, 30.0, 12.0, V3::new(1.6, 1.8, 2.2)).eval(d)
}
Environment::Night => {
let base = sky(d, V3::new(0.01, 0.015, 0.04), V3::new(0.03, 0.03, 0.06), V3::splat(0.005));
base + soft(20.0, 15.0, 10.0, 10.0, V3::new(0.4, 1.6, 4.0)).eval(d) + soft(-110.0, 10.0, 12.0, 8.0, V3::new(4.0, 0.8, 1.6)).eval(d)
}
Environment::StudioSoft => {
let base = sky(d, V3::new(0.5, 0.52, 0.56), V3::new(0.32, 0.32, 0.33), V3::new(0.08, 0.075, 0.07));
base + soft(40.0, 35.0, 28.0, 20.0, V3::new(5.5, 5.2, 4.8)).eval(d)
+ soft(-125.0, 20.0, 35.0, 22.0, V3::new(1.1, 1.25, 1.5)).eval(d)
+ soft(175.0, 55.0, 8.0, 25.0, V3::new(3.0, 3.0, 3.0)).eval(d)
}
}
}
/// Renders the environment at `width × width / 2` pixels. Returns [`PbrError::BadSize`] for a
/// width under 2 and an error when the size is over `limits`.
pub fn try_render(self, width: u32, limits: &Limits) -> Result<EnvImage, PbrError> {
let height = width / 2;
let len = limits.check(width, height)?;
let mut data = try_pixels(len)?;
let (w, h) = (width as usize, height as usize);
for_each_row(&mut data, w, |y, row| {
for (x, px) in row.iter_mut().enumerate() {
*px = self.radiance(pixel_dir(x, y, w, h)).to_array();
}
});
Ok(EnvImage { width, height, data })
}
}
+162
View File
@@ -0,0 +1,162 @@
//! # craft-pbr
//!
//! Image-based lighting for physically based rendering, computed on the CPU. An [`EnvImage`] is a
//! linear RGB equirect (latitude-longitude) environment. [`try_prefilter`] turns it into a
//! GGX-prefiltered chain for specular light, one level per roughness, and [`try_sh9`] projects it
//! onto nine spherical-harmonics coefficients for diffuse light. [`Environment`] renders six
//! procedural environments with no image assets.
//!
//! The equirect frame has +Y 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 toward +Z. Lookups wrap horizontally and clamp vertically. [`dir_of`] and [`uv_of`]
//! convert between the two. An image in another frame, such as an OpenEXR latitude-longitude
//! image, is converted by the caller before it is passed in.
//!
//! The specular chain follows the split-sum approximation of Karis, *Real Shading in Unreal
//! Engine 4* (SIGGRAPH 2013,
//! <https://de45xmedrsdbp.cloudfront.net/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf>):
//! level `l` of `n` is filtered for roughness `l / (n - 1)` with the view and reflection
//! directions taken equal to the normal, and samples weighted by `n·l`. The distribution is GGX
//! with `α = roughness²`, as glTF 2.0 Appendix B.2.3 defines it
//! (<https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces>), and its
//! 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.
//!
//! 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,
//! <https://graphics.stanford.edu/papers/envmap/envmap.pdf>) and divided by `π`. [`irradiance`]
//! evaluates them: for a white surface its result is the diffuse radiance it reflects.
//!
//! Sizes and work are bounded. [`Limits`] caps the side, the pixel count, the bytes and the
//! sample work, and every `try_` function returns a [`PbrError`] before it allocates anything
//! over them. Pixel buffers are reserved fallibly and give [`PbrError::OutOfMemory`] when the
//! reservation fails. Radiance in every [`EnvImage`] is between 0 and [`MAX_RADIANCE`]: the
//! constructors reject or replace other values. Rows are computed on several threads only with
//! the `parallel` feature, and the results are the same either way.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod environment;
mod prefilter;
mod sh;
mod vec3;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
pub use environment::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, MAX_RADIANCE, 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.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PbrError {
/// A side is zero or longer than [`Limits::max_side`].
#[error("environment size {0}x{1} has a zero side or a side over the limit")]
BadSize(u32, u32),
/// The pixel count or the byte count is over [`Limits`], or a buffer would be larger than
/// `isize::MAX` bytes, the largest allocation the target allows.
#[error("environment size {0}x{1} needs more pixels or bytes than the limits or the target allow")]
TooLarge(u32, u32),
/// The pixel buffer does not hold width × height pixels.
#[error("environment data holds {found} pixels where {expected} are needed")]
BadDataLength { expected: usize, found: usize },
/// A linear radiance value is NaN, negative or above [`MAX_RADIANCE`].
#[error("pixel {index} has a radiance that is not a number, is negative or is over the maximum")]
BadRadiance { index: usize },
/// A direction has a non-finite component or zero length.
#[error("the direction is not finite or has zero length")]
BadDirection,
/// An option is out of its range; the text names it.
#[error("{0}")]
BadOption(&'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 },
/// Memory for the pixels could not be reserved.
#[error("not enough memory for the environment")]
OutOfMemory,
}
/// Caps on sizes and work, checked before anything is allocated or computed.
/// `#[non_exhaustive]`: start from [`Limits::default`] and set the fields you change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
/// Longest side in pixels. Default 2048.
pub max_side: u32,
/// Most pixels (width × height) of one image. Default 2^22, which is 2048 × 2048.
pub max_pixels: u64,
/// Most bytes of pixel data one call holds at once: for [`try_prefilter`] the source copies,
/// the pyramid, every output level and the sample table together. Default 256 MiB.
pub max_bytes: u64,
/// Most levels [`try_prefilter`] makes. Default 8.
pub max_levels: u32,
/// Most samples per output pixel. Default 1024.
pub max_samples: u32,
/// Most sample evaluations of one [`try_prefilter`] call: output pixels of the filtered levels
/// times samples. Default 2^28.
pub max_work: u64,
}
impl Default for Limits {
fn default() -> Self {
Self { max_side: 2048, max_pixels: 1 << 22, max_bytes: 256 << 20, max_levels: 8, max_samples: 1024, max_work: 1 << 28 }
}
}
/// Bytes of one pixel: three `f32` channels.
const PIXEL_BYTES: u64 = 12;
/// The largest allocation in bytes that a `Vec` can make on the target.
const MAX_ALLOC_BYTES: u64 = isize::MAX as u64;
impl Limits {
/// The pixel count of a `w × h` image, or the error the limits give for that size. A size
/// whose bytes are over `isize::MAX` is [`PbrError::TooLarge`] whatever the limits are.
/// Nothing is allocated.
pub fn check(&self, w: u32, h: u32) -> Result<usize, PbrError> {
if w == 0 || h == 0 || w > self.max_side || h > self.max_side {
return Err(PbrError::BadSize(w, h));
}
let pixels = u64::from(w) * u64::from(h);
let bytes = pixels.checked_mul(PIXEL_BYTES).ok_or(PbrError::TooLarge(w, h))?;
if pixels > self.max_pixels || bytes > self.max_bytes || bytes > MAX_ALLOC_BYTES {
return Err(PbrError::TooLarge(w, h));
}
usize::try_from(pixels).map_err(|_| PbrError::TooLarge(w, h))
}
/// Checks a total of `bytes` held at once against [`Limits::max_bytes`] and `isize::MAX`.
fn check_total_bytes(&self, bytes: Option<u64>, w: u32, h: u32) -> Result<(), PbrError> {
match bytes {
Some(b) if b <= self.max_bytes && b <= MAX_ALLOC_BYTES => Ok(()),
_ => Err(PbrError::TooLarge(w, h)),
}
}
}
/// A zeroed pixel buffer of `len` pixels, reserved fallibly.
fn try_pixels(len: usize) -> Result<Vec<[f32; 3]>, PbrError> {
let mut v = Vec::new();
v.try_reserve_exact(len).map_err(|_| PbrError::OutOfMemory)?;
v.resize(len, [0.0; 3]);
Ok(v)
}
/// Runs `f(row index, row)` for each row of `width` pixels, on several threads with the
/// `parallel` feature. `width` is at least 1.
fn for_each_row<F>(data: &mut [[f32; 3]], width: usize, f: F)
where
F: Fn(usize, &mut [[f32; 3]]) + Sync + Send,
{
let width = width.max(1);
#[cfg(feature = "parallel")]
data.par_chunks_mut(width).enumerate().for_each(|(y, row)| f(y, row));
#[cfg(not(feature = "parallel"))]
data.chunks_mut(width).enumerate().for_each(|(y, row)| f(y, row));
}
+256
View File
@@ -0,0 +1,256 @@
//! The GGX-prefiltered specular chain.
use std::f32::consts::{PI, TAU};
use crate::environment::{EnvImage, half_size, pixel_dir};
use crate::vec3::V3;
use crate::{Limits, PIXEL_BYTES, PbrError, for_each_row, try_pixels};
/// How [`try_prefilter`] filters. `#[non_exhaustive]`: start from [`PrefilterOptions::default`]
/// and set the fields you change.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct PrefilterOptions {
/// Levels in the chain, 1 to [`Limits::max_levels`]. Default 6.
pub levels: u32,
/// Importance samples per output pixel, 1 to [`Limits::max_samples`]. Default 128.
pub samples: u32,
/// Added to each sample's source pyramid level, in levels. A larger value reads blurrier
/// source levels and hides sampling noise. Finite. Default 1.
pub lod_bias: f32,
/// When set, source radiance is capped at this value before filtering, so a small bright
/// light gives fewer isolated bright pixels in rough levels and less light overall. Finite
/// and above 0. Level 0 is never capped. Default `None`.
pub firefly_cap: Option<f32>,
}
impl Default for PrefilterOptions {
fn default() -> Self {
Self { levels: 6, samples: 128, lod_bias: 1.0, firefly_cap: None }
}
}
impl PrefilterOptions {
fn validate(&self, limits: &Limits) -> Result<(), PbrError> {
if self.levels == 0 || self.levels > limits.max_levels {
return Err(PbrError::BadOption("the level count is 0 or over the limit"));
}
if self.samples == 0 || self.samples > limits.max_samples {
return Err(PbrError::BadOption("the sample count is 0 or over the limit"));
}
if !self.lod_bias.is_finite() {
return Err(PbrError::BadOption("the level bias is not finite"));
}
if self.firefly_cap.is_some_and(|c| !c.is_finite() || c <= 0.0) {
return Err(PbrError::BadOption("the firefly cap is not finite or not above 0"));
}
Ok(())
}
}
/// Point `i` of `n` of the Hammersley set: `(i / n, radical inverse of i in base 2)`. Returns
/// `None` when `i` is not below `n`.
pub fn hammersley(i: u32, n: u32) -> Option<[f32; 2]> {
(i < n).then(|| [i as f32 / n as f32, i.reverse_bits() as f32 * 2.328_306_4e-10])
}
/// The GGX normal distribution `D` at `n_dot_h` for perceptual `roughness`, with
/// `α = max(roughness², 0.001)`: `α² / (π ((n·h)² (α² − 1) + 1)²)`, as glTF 2.0 Appendix B writes
/// it in section B.3.2. Over the hemisphere, `D(h) (n·h)` integrates to 1.
/// It is evaluated in `f64`, so it keeps its peak `1 / (π α²)` at `n·h = 1` for the smallest `α`.
pub fn ggx_distribution(n_dot_h: f32, roughness: f32) -> f32 {
let a = f64::from((roughness * roughness).max(1e-3));
let c2 = f64::from(n_dot_h) * f64::from(n_dot_h);
let a2 = a * a;
(a2 / (std::f64::consts::PI * (c2 * (a2 - 1.0) + 1.0).powi(2)).max(f64::MIN_POSITIVE)) as f32
}
/// `D` of [`ggx_distribution`] in `f32` for the sample table, with `a = α`. The denominator is at
/// least `π α⁴`, which is above `f32::MIN_POSITIVE` for `α` of at least 0.001.
fn ggx_d(cos_t: f32, a: f32) -> f32 {
a * a / (PI * ((cos_t * cos_t) * (a * a - 1.0) + 1.0).powi(2)).max(f32::MIN_POSITIVE)
}
/// Sizes of the source pyramid after level 0: halved while it is wider than 8, at most 9 more.
fn pyramid_sizes(w: u32, h: u32) -> Vec<(u32, u32)> {
let mut sizes = Vec::new();
let mut size = (w, h);
while sizes.len() < 9 && size.0 > 8 {
size = half_size(size.0, size.1);
sizes.push(size);
}
sizes
}
/// The size of the output level after one of `size`: each side halved but kept at least 4 × 2,
/// and never larger than `size`.
fn next_level(size: (u32, u32)) -> (u32, u32) {
((size.0 / 2).max(size.0.min(4)), (size.1 / 2).max(size.1.min(2)))
}
/// Sizes of output levels 1 and up, reserved fallibly. Called after [`check_budget`].
fn level_sizes(w: u32, h: u32, levels: u32) -> Result<Vec<(u32, u32)>, PbrError> {
let mut sizes = Vec::new();
sizes.try_reserve_exact(levels.saturating_sub(1) as usize).map_err(|_| PbrError::OutOfMemory)?;
let mut size = (w, h);
for _ in 1..levels {
size = next_level(size);
sizes.push(size);
}
Ok(sizes)
}
/// The pixels of output levels 1 and up, without listing them: once a level keeps its size,
/// every later level has that size too.
fn level_pixels(w: u32, h: u32, levels: u32) -> Option<u64> {
let mut size = (w, h);
let mut total = 0u64;
let mut left = u64::from(levels.saturating_sub(1));
while left > 0 {
let next = next_level(size);
let pixels = u64::from(next.0) * u64::from(next.1);
if next == size {
return total.checked_add(pixels.checked_mul(left)?);
}
total = total.checked_add(pixels)?;
left -= 1;
size = next;
}
Some(total)
}
fn pixels_of(sizes: &[(u32, u32)]) -> Option<u64> {
sizes.iter().try_fold(0u64, |acc, &(w, h)| acc.checked_add(u64::from(w) * u64::from(h)))
}
/// Checks the bytes held at once (the source copies, the pyramid, the levels with their list
/// entries, and one sample table) and the sample work of a call before anything is allocated.
fn check_budget(env: &EnvImage, options: &PrefilterOptions, pyramid: &[(u32, u32)], limits: &Limits) -> Result<(), PbrError> {
let (w, h) = (env.width(), env.height());
let src = u64::from(w) * u64::from(h);
// One level is a copy of the source; no pyramid, capped copy or sample table is made.
let filtering = options.levels > 1;
let copies = if filtering && options.firefly_cap.is_some() { 2 } else { 1 };
let pyramid = if filtering { pixels_of(pyramid) } else { Some(0) };
let levels = level_pixels(w, h, options.levels);
let pixels = pyramid.zip(levels).and_then(|(p, l)| src.checked_mul(copies)?.checked_add(p)?.checked_add(l));
let table = if filtering { u64::from(options.samples) * size_of::<Sample<'_>>() as u64 } else { 0 };
let lists = u64::from(options.levels) * (size_of::<(u32, u32)>() + size_of::<EnvImage>()) as u64;
let bytes = pixels.and_then(|p| p.checked_mul(PIXEL_BYTES)?.checked_add(table)?.checked_add(lists));
limits.check_total_bytes(bytes, w, h)?;
let needed = levels.and_then(|l| l.checked_mul(u64::from(options.samples))).unwrap_or(u64::MAX);
if needed > limits.max_work {
return Err(PbrError::TooMuchWork { needed, limit: limits.max_work });
}
Ok(())
}
/// A copy of `env` with every value capped at `cap`.
fn capped(env: &EnvImage, cap: f32) -> Result<EnvImage, PbrError> {
let mut data = try_pixels(env.pixels().len())?;
for (out, p) in data.iter_mut().zip(env.pixels()) {
*out = p.map(|v| v.min(cap));
}
rebuild(env.width(), env.height(), data)
}
fn rebuild(w: u32, h: u32, data: Vec<[f32; 3]>) -> Result<EnvImage, PbrError> {
let limits = Limits { max_side: u32::MAX, max_pixels: u64::MAX, max_bytes: u64::MAX, ..Limits::default() };
EnvImage::try_from_linear(w, h, data, &limits)
}
/// One importance sample: its tangent-space half vector, `n·l` and the pyramid level it reads.
type Sample<'a> = (V3, f32, &'a EnvImage);
/// The samples of one level. With `n = v`, every sample's half vector, `n·l` and source level
/// depend only on its index, so they are computed once per level.
fn sample_table<'a>(rough: f32, options: &PrefilterOptions, src_pixels: f32, pyramid: &[&'a EnvImage]) -> Result<Vec<Sample<'a>>, PbrError> {
let a = (rough * rough).max(1e-3);
let samples = options.samples;
let sa_texel = 4.0 * PI / src_pixels;
let top = pyramid.len().saturating_sub(1);
let mut table = Vec::new();
table.try_reserve_exact(samples as usize).map_err(|_| PbrError::OutOfMemory)?;
table.extend((0..samples).filter_map(|i| {
let [xu, xv] = hammersley(i, samples)?;
let phi = TAU * xu;
let cos_t = ((1.0 - xv) / (1.0 + (a * a - 1.0) * xv)).max(0.0).sqrt();
let sin_t = (1.0 - cos_t * cos_t).max(0.0).sqrt();
let ndl = 2.0 * cos_t * cos_t - 1.0;
if ndl <= 0.0 {
return None;
}
let dd = ggx_d(cos_t, a);
let sa_sample = 1.0 / (samples as f32 * dd / 4.0 + 1e-6);
let lod = (0.5 * (sa_sample / sa_texel).log2() + options.lod_bias).clamp(0.0, top as f32);
let src = pyramid.get(lod.round() as usize).or(pyramid.first()).copied()?;
Some((V3::new(sin_t * phi.cos(), sin_t * phi.sin(), cos_t), ndl, src))
}));
Ok(table)
}
/// One filtered level of `w × h` pixels.
fn filter_level(w: u32, h: u32, table: &[Sample<'_>]) -> Result<EnvImage, PbrError> {
let wsum: f32 = table.iter().map(|t| t.1).sum();
let mut data = try_pixels(w as usize * h as usize)?;
let (wu, hu) = (w as usize, h as usize);
for_each_row(&mut data, wu, |y, row| {
for (x, px) in row.iter_mut().enumerate() {
let n = pixel_dir(x, y, wu, hu);
let up = if n.y.abs() < 0.999 { V3::Y } else { V3::X };
let tx = up.cross(n).normalize();
let ty = n.cross(tx);
let mut acc = V3::ZERO;
for (hv, ndl, src) in table {
let hw = tx * hv.x + ty * hv.y + n * hv.z;
acc += src.sample_v(hw * (2.0 * hv.z) - n) * *ndl;
}
*px = (acc / wsum.max(1e-6)).to_radiance_array();
}
});
rebuild(w, h, data)
}
/// The GGX-prefiltered chain of `env`. Level `l` of `options.levels` is filtered for roughness
/// `l / (levels − 1)`; level 0 is a copy of `env`, and each later level halves each side but
/// keeps at least 4 × 2 pixels and is never larger than the level before. Returns an error, before
/// allocating, for an option out of range, for a source over the size limits, or when the source
/// copies, the pyramid, the levels and the sample table together are over [`Limits::max_bytes`]
/// or the sample work is over [`Limits::max_work`].
pub fn try_prefilter(env: &EnvImage, options: &PrefilterOptions, limits: &Limits) -> Result<Vec<EnvImage>, PbrError> {
options.validate(limits)?;
let (w, h) = (env.width(), env.height());
limits.check(w, h)?;
let pyramid_size = pyramid_sizes(w, h);
check_budget(env, options, &pyramid_size, limits)?;
let sizes = level_sizes(w, h, options.levels)?;
let mut out = Vec::new();
out.try_reserve_exact(sizes.len() + 1).map_err(|_| PbrError::OutOfMemory)?;
let mut first = try_pixels(env.pixels().len())?;
first.copy_from_slice(env.pixels());
out.push(rebuild(w, h, first)?);
if sizes.is_empty() {
return Ok(out);
}
let base = match options.firefly_cap {
Some(cap) => Some(capped(env, cap)?),
None => None,
};
let base = base.as_ref().unwrap_or(env);
let unbounded = Limits { max_side: u32::MAX, max_pixels: u64::MAX, max_bytes: u64::MAX, ..*limits };
let mut rest: Vec<EnvImage> = Vec::new();
for _ in &pyramid_size {
let next = rest.last().unwrap_or(base).try_half(&unbounded)?;
rest.push(next);
}
let pyramid: Vec<&EnvImage> = std::iter::once(base).chain(rest.iter()).collect();
let src_pixels = w as f32 * h as f32;
let steps = (options.levels - 1) as f32;
for (l, &(lw, lh)) in sizes.iter().enumerate() {
let rough = (l + 1) as f32 / steps;
let table = sample_table(rough, options, src_pixels, &pyramid)?;
out.push(filter_level(lw, lh, &table)?);
}
Ok(out)
}
+166
View File
@@ -0,0 +1,166 @@
//! Diffuse irradiance as nine spherical-harmonics coefficients.
use std::f64::consts::{PI, TAU};
use crate::environment::EnvImage;
use crate::vec3::{V3, unit};
use crate::{Limits, PbrError};
/// Diffuse irradiance of `env` as nine SH coefficients, in the order of [`sh_basis`], already
/// convolved with the cosine lobe and divided by `π`: `Σ c_k Y_k(n)` times the albedo is the
/// diffuse radiance a surface with normal `n` reflects. Every pixel of the source is projected,
/// with each basis function integrated over the area of the pixel. Returns an error when the
/// source is over `limits`.
pub fn try_sh9(env: &EnvImage, limits: &Limits) -> Result<[[f32; 3]; 9], PbrError> {
limits.check(env.width(), env.height())?;
project(env)
}
/// Integrals over the longitudes `φ0..φ1` of one column.
struct Column {
/// `∫ dφ`
len: f64,
/// `∫ cos φ dφ`
cos: f64,
/// `∫ sin φ dφ`
sin: f64,
/// `∫ cos² φ dφ`
cos2: f64,
/// `∫ sin² φ dφ`
sin2: f64,
/// `∫ sin φ cos φ dφ`
sin_cos: f64,
}
impl Column {
fn new(x: usize, w: usize) -> Column {
let (p0, p1) = (TAU * x as f64 / w as f64, TAU * (x + 1) as f64 / w as f64);
let len = p1 - p0;
let half_sin2 = ((2.0 * p1).sin() - (2.0 * p0).sin()) / 4.0;
Column {
len,
cos: p1.sin() - p0.sin(),
sin: p0.cos() - p1.cos(),
cos2: len / 2.0 + half_sin2,
sin2: len / 2.0 - half_sin2,
sin_cos: (p1.sin().powi(2) - p0.sin().powi(2)) / 2.0,
}
}
}
/// Integrals over the colatitudes `θ0..θ1` of one row, each with the `sin θ` of the solid angle.
struct Row {
/// `∫ sin θ dθ`
s1: f64,
/// `∫ cos θ sin θ dθ`
c1s1: f64,
/// `∫ sin² θ dθ`
s2: f64,
/// `∫ cos θ sin² θ dθ`
c1s2: f64,
/// `∫ sin³ θ dθ`
s3: f64,
/// `∫ cos² θ sin θ dθ`
c2s1: f64,
}
impl Row {
fn new(y: usize, h: usize) -> Row {
let (t0, t1) = (PI * y as f64 / h as f64, PI * (y + 1) as f64 / h as f64);
let (c0, c1, s0, s1) = (t0.cos(), t1.cos(), t0.sin(), t1.sin());
Row {
s1: c0 - c1,
c1s1: (s1 * s1 - s0 * s0) / 2.0,
s2: (t1 - t0) / 2.0 - ((2.0 * t1).sin() - (2.0 * t0).sin()) / 4.0,
c1s2: (s1.powi(3) - s0.powi(3)) / 3.0,
s3: (c0 - c1) - (c0.powi(3) - c1.powi(3)) / 3.0,
c2s1: (c0.powi(3) - c1.powi(3)) / 3.0,
}
}
}
/// The integral of each function of [`basis`] over one pixel, from the column and row integrals
/// of `x = sin θ cos φ`, `y = cos θ` and `z = sin θ sin φ`.
fn pixel_basis(c: &Column, r: &Row) -> [f64; 9] {
[
0.282_095 * c.len * r.s1,
0.488_603 * c.len * r.c1s1,
0.488_603 * c.sin * r.s2,
0.488_603 * c.cos * r.s2,
1.092_548 * c.cos * r.c1s2,
1.092_548 * c.sin * r.c1s2,
0.315_392 * (3.0 * c.sin2 * r.s3 - c.len * r.s1),
1.092_548 * c.sin_cos * r.s3,
0.546_274 * (c.cos2 * r.s3 - c.len * r.c2s1),
]
}
/// Projects each pixel with the integral of the basis over its area rather than the basis at its
/// center, so a coarse image of uniform radiance has no directional terms. Sums in `f64`, so
/// the sums cannot overflow before the result is clamped to `f32`.
fn project(src: &EnvImage) -> Result<[[f32; 3]; 9], PbrError> {
let (w, h) = (src.width() as usize, src.height() as usize);
let mut columns = Vec::new();
columns.try_reserve_exact(w).map_err(|_| PbrError::OutOfMemory)?;
columns.extend((0..w).map(|x| Column::new(x, w)));
let mut c = [[0.0f64; 3]; 9];
for (y, pixels) in src.pixels().chunks_exact(w).enumerate() {
let row = Row::new(y, h);
for (col, p) in columns.iter().zip(pixels) {
let l = p.map(f64::from);
for (ck, ylm) in c.iter_mut().zip(pixel_basis(col, &row)) {
for (cc, lc) in ck.iter_mut().zip(l) {
*cc += lc * ylm;
}
}
}
}
let a = [1.0, 2.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0, 0.25, 0.25, 0.25, 0.25, 0.25];
let max = f64::from(f32::MAX);
let mut out = [[0.0; 3]; 9];
for ((o, ck), ak) in out.iter_mut().zip(c).zip(a) {
*o = ck.map(|v| (v * ak).clamp(-max, max) as f32);
}
Ok(out)
}
/// 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. Returns [`PbrError::BadDirection`] when it is not finite or has zero length.
pub fn sh_basis(d: [f32; 3]) -> Result<[f32; 9], PbrError> {
unit(d).map(basis).ok_or(PbrError::BadDirection)
}
fn basis(d: V3) -> [f32; 9] {
let (x, y, z) = (d.x, d.y, d.z);
[
0.282_095,
0.488_603 * y,
0.488_603 * z,
0.488_603 * x,
1.092_548 * x * y,
1.092_548 * y * z,
0.315_392 * (3.0 * z * z - 1.0),
1.092_548 * x * z,
0.546_274 * (x * x - y * y),
]
}
/// `Σ c_k Y_k(n)` for coefficients from [`try_sh9`]: the diffuse radiance a white surface with
/// normal `n` reflects. Negative results, which ringing can give, are kept. Returns
/// [`PbrError::BadDirection`] when `n` is not finite or has zero length, and
/// [`PbrError::BadOption`] when a coefficient is not finite.
pub fn irradiance(coefficients: &[[f32; 3]; 9], n: [f32; 3]) -> Result<[f32; 3], PbrError> {
let b = sh_basis(n)?;
if coefficients.iter().flatten().any(|c| !c.is_finite()) {
return Err(PbrError::BadOption("an SH coefficient is not finite"));
}
let mut e = [0.0f64; 3];
for (c, y) in coefficients.iter().zip(b) {
for (ec, cc) in e.iter_mut().zip(c) {
*ec += f64::from(*cc) * f64::from(y);
}
}
let max = f64::from(f32::MAX);
Ok(e.map(|v| v.clamp(-max, max) as f32))
}
+112
View File
@@ -0,0 +1,112 @@
//! A small three-component `f32` vector for the lighting math. The operations evaluate in the same
//! order as glam's `Vec3`, so results match the apps' code that used it.
use std::ops::{Add, AddAssign, Div, Mul, Sub};
use crate::MAX_RADIANCE;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct V3 {
pub(crate) x: f32,
pub(crate) y: f32,
pub(crate) z: f32,
}
impl V3 {
pub(crate) const ZERO: V3 = V3::new(0.0, 0.0, 0.0);
pub(crate) const X: V3 = V3::new(1.0, 0.0, 0.0);
pub(crate) const Y: V3 = V3::new(0.0, 1.0, 0.0);
pub(crate) const fn new(x: f32, y: f32, z: f32) -> V3 {
V3 { x, y, z }
}
pub(crate) const fn splat(v: f32) -> V3 {
V3::new(v, v, v)
}
pub(crate) const fn from_array(a: [f32; 3]) -> V3 {
V3::new(a[0], a[1], a[2])
}
pub(crate) const fn to_array(self) -> [f32; 3] {
[self.x, self.y, self.z]
}
pub(crate) fn dot(self, o: V3) -> f32 {
(self.x * o.x) + (self.y * o.y) + (self.z * o.z)
}
pub(crate) fn cross(self, o: V3) -> V3 {
V3::new(self.y * o.z - o.y * self.z, self.z * o.x - o.z * self.x, self.x * o.y - o.x * self.y)
}
pub(crate) fn length(self) -> f32 {
self.dot(self).sqrt()
}
pub(crate) fn normalize(self) -> V3 {
self * self.length().recip()
}
pub(crate) fn lerp(self, o: V3, s: f32) -> V3 {
self * (1.0 - s) + o * s
}
pub(crate) fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
}
/// The components of a non-negative average of radiance, kept at most [`MAX_RADIANCE`] when
/// rounding takes them a little above it.
pub(crate) fn to_radiance_array(self) -> [f32; 3] {
[self.x.min(MAX_RADIANCE), self.y.min(MAX_RADIANCE), self.z.min(MAX_RADIANCE)]
}
}
impl Div<f32> for V3 {
type Output = V3;
fn div(self, s: f32) -> V3 {
V3::new(self.x / s, self.y / s, self.z / s)
}
}
impl Add for V3 {
type Output = V3;
fn add(self, o: V3) -> V3 {
V3::new(self.x + o.x, self.y + o.y, self.z + o.z)
}
}
impl AddAssign for V3 {
fn add_assign(&mut self, o: V3) {
*self = *self + o;
}
}
impl Sub for V3 {
type Output = V3;
fn sub(self, o: V3) -> V3 {
V3::new(self.x - o.x, self.y - o.y, self.z - o.z)
}
}
impl Mul<f32> for V3 {
type Output = V3;
fn mul(self, s: f32) -> V3 {
V3::new(self.x * s, self.y * s, self.z * s)
}
}
/// A unit vector along `d`, or `None` when `d` has a non-finite component or zero length.
pub(crate) fn unit(d: [f32; 3]) -> Option<V3> {
let v = V3::from_array(d);
let big = v.x.abs().max(v.y.abs()).max(v.z.abs());
if !v.is_finite() || big == 0.0 {
return None;
}
// Scaling by the largest component first keeps the squared length in range.
let v = v / big;
let n = v * (1.0 / v.length());
n.is_finite().then_some(n)
}
+28
View File
@@ -0,0 +1,28 @@
//! CPU time of the default filtering:
//! `cargo test -p craft-pbr --release --test it -- --ignored --nocapture bench`.
use std::time::Instant;
use craft_pbr::{Environment, Limits, PrefilterOptions, try_prefilter, try_sh9};
#[test]
#[ignore = "timing, not a correctness check"]
fn bench_prefilter_and_sh9() {
let limits = Limits::default();
for width in [256, 512, 2048] {
let env = Environment::Sunset.try_render(width, &limits).unwrap();
let t = Instant::now();
let mips = try_prefilter(&env, &PrefilterOptions::default(), &limits).unwrap();
let filter = t.elapsed();
let t = Instant::now();
let sh = try_sh9(&env, &limits).unwrap();
println!(
"{width}x{}: prefilter {:.1} ms ({} levels), SH9 {:.1} ms (sh0 {:?})",
width / 2,
filter.as_secs_f64() * 1000.0,
mips.len(),
t.elapsed().as_secs_f64() * 1000.0,
sh[0]
);
}
}
+214
View File
@@ -0,0 +1,214 @@
//! Sizes, budgets, options and values out of range are refused with an error before allocating.
use craft_pbr::{
ColorEncoding, EnvImage, Environment, Limits, MAX_RADIANCE, PbrError, PrefilterOptions, hammersley, irradiance, sh_basis, try_prefilter, try_sh9,
};
use crate::{env_from, limits, opts};
/// Limits raised as far as they go, so only the `isize::MAX` bound is left.
fn unbounded() -> Limits {
limits(|l| {
l.max_side = u32::MAX;
l.max_pixels = u64::MAX;
l.max_bytes = u64::MAX;
l.max_levels = u32::MAX;
l.max_samples = u32::MAX;
l.max_work = u64::MAX;
})
}
#[test]
fn zero_sizes_are_refused() {
let limits = Limits::default();
assert_eq!(EnvImage::try_from_linear(0, 4, Vec::new(), &limits), Err(PbrError::BadSize(0, 4)));
assert_eq!(EnvImage::try_from_linear(4, 0, Vec::new(), &limits), Err(PbrError::BadSize(4, 0)));
assert_eq!(EnvImage::try_from_rgba(0, 0, &[], ColorEncoding::Linear, &limits), Err(PbrError::BadSize(0, 0)));
assert_eq!(Environment::Night.try_render(1, &limits), Err(PbrError::BadSize(1, 0)));
assert_eq!(Environment::Night.try_render(0, &limits), Err(PbrError::BadSize(0, 0)));
}
#[test]
fn huge_sizes_are_refused_before_allocating() {
let default = Limits::default();
assert_eq!(Environment::Night.try_render(4096, &default), Err(PbrError::BadSize(4096, 2048)));
let few = limits(|l| l.max_pixels = 100);
assert_eq!(Environment::Night.try_render(16, &few), Err(PbrError::TooLarge(16, 8)));
// With every limit raised, a size over isize::MAX bytes is still refused, and the size is
// checked before the data length.
let huge = unbounded();
assert_eq!(Environment::Night.try_render(u32::MAX, &huge), Err(PbrError::TooLarge(u32::MAX, u32::MAX / 2)));
assert_eq!(EnvImage::try_from_rgba(u32::MAX, u32::MAX, &[], ColorEncoding::Linear, &huge), Err(PbrError::TooLarge(u32::MAX, u32::MAX)));
assert_eq!(EnvImage::try_from_linear(u32::MAX, u32::MAX, Vec::new(), &huge), Err(PbrError::TooLarge(u32::MAX, u32::MAX)));
// 2^60 pixels are 1.5 × 2^63 bytes: within u64, over isize::MAX.
assert_eq!(EnvImage::try_from_linear(1 << 30, 1 << 30, Vec::new(), &huge), Err(PbrError::TooLarge(1 << 30, 1 << 30)));
assert_eq!(EnvImage::try_from_linear(4, 2, vec![[0.0; 3]; 7], &default), Err(PbrError::BadDataLength { expected: 8, found: 7 }));
}
#[test]
fn prefiltering_over_the_byte_or_work_budget_is_refused() {
let env = env_from(256, 128, |_, _| [1.0; 3]);
let options = PrefilterOptions::default();
// The source copy alone is 384 KiB.
let tight = limits(|l| l.max_bytes = 512 << 10);
assert_eq!(try_prefilter(&env, &options, &tight), Err(PbrError::TooLarge(256, 128)));
// Levels 1 to 5 hold 128×64 + 64×32 + 32×16 + 16×8 + 8×4 = 10,912 pixels, at 128 samples each.
let needed = 10_912 * 128;
let short = limits(|l| l.max_work = needed - 1);
assert_eq!(try_prefilter(&env, &options, &short), Err(PbrError::TooMuchWork { needed, limit: needed - 1 }));
let exact = limits(|l| l.max_work = needed);
assert!(try_prefilter(&env, &options, &exact).is_ok());
// A raised sample count on a 1 × 1 source passes the work limit, but its sample table does
// not fit the byte limit.
let tiny = env_from(1, 1, |_, _| [1.0; 3]);
let many = limits(|l| {
l.max_samples = u32::MAX;
l.max_work = u64::MAX;
});
assert_eq!(try_prefilter(&tiny, &opts(|o| o.samples = 100_000_000), &many), Err(PbrError::TooLarge(1, 1)));
// One level is only a copy, so the sample table is not counted.
let copy = try_prefilter(&tiny, &opts(|o| (o.levels, o.samples) = (1, 100_000_000)), &many).unwrap();
assert_eq!(copy, vec![tiny.clone()]);
// A raised level count is counted without listing the levels first: 2^32 − 2 levels of
// 1 × 1 are refused for their bytes, and for their work when bytes are not limited.
let deep = limits(|l| {
l.max_levels = u32::MAX;
l.max_work = u64::MAX;
});
assert_eq!(try_prefilter(&tiny, &opts(|o| o.levels = u32::MAX), &deep), Err(PbrError::TooLarge(1, 1)));
let unbounded = limits(|l| {
l.max_levels = u32::MAX;
l.max_bytes = u64::MAX;
});
let needed = (u64::from(u32::MAX) - 1) * 128;
assert_eq!(try_prefilter(&tiny, &opts(|o| o.levels = u32::MAX), &unbounded), Err(PbrError::TooMuchWork { needed, limit: 1 << 28 }));
}
#[test]
fn nan_infinite_and_negative_radiance_is_refused() {
let limits = Limits::default();
for (i, bad) in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0].into_iter().enumerate() {
let mut data = vec![[1.0; 3]; 8];
data[i + 2][i % 3] = bad;
assert_eq!(EnvImage::try_from_linear(4, 2, data, &limits), Err(PbrError::BadRadiance { index: i + 2 }), "{bad}");
}
// The RGBA import replaces them with 0 instead.
let px = [[f32::NAN, f32::INFINITY, -5.0, 1.0], [1e9, 0.5, f32::NEG_INFINITY, f32::NAN]];
let e = EnvImage::try_from_rgba(2, 1, &px, ColorEncoding::Linear, &limits).unwrap();
assert_eq!(e.pixels(), &[[0.0, 0.0, 0.0], [65_000.0, 0.5, 0.0]]);
let e = EnvImage::try_from_rgba(2, 1, &px, ColorEncoding::Srgb, &limits).unwrap();
assert_eq!(e.pixels()[1][0], 1.0);
}
#[test]
fn radiance_over_the_maximum_is_refused() {
let limits = Limits::default();
for bad in [f32::MAX, 1e29, MAX_RADIANCE * 1.001] {
let mut data = vec![[1.0; 3]; 8];
data[5][1] = bad;
assert_eq!(EnvImage::try_from_linear(4, 2, data, &limits), Err(PbrError::BadRadiance { index: 5 }), "{bad}");
}
assert!(EnvImage::try_from_linear(4, 2, vec![[MAX_RADIANCE; 3]; 8], &limits).is_ok());
}
#[test]
fn the_largest_radiance_averages_without_overflow() {
let limits = Limits::default();
let rel = |a: f32, b: f32| ((a - b) / b).abs();
// One bright pixel in a 2 × 2 block, and in a 3 × 3 image.
let block = env_from(2, 2, |x, y| if (x, y) == (1, 1) { [MAX_RADIANCE; 3] } else { [0.0; 3] });
let half = block.try_half(&limits).unwrap();
assert!(rel(half.pixels()[0][0], MAX_RADIANCE / 4.0) < 1e-6, "{:?}", half.pixels());
let odd = env_from(3, 3, |x, y| if (x, y) == (2, 2) { [MAX_RADIANCE; 3] } else { [0.0; 3] });
let half = odd.try_half(&limits).unwrap();
assert!(rel(half.pixels()[0][0], MAX_RADIANCE / 9.0) < 1e-5, "{:?}", half.pixels());
// A uniform image keeps its value through many samples; one bright pixel is spread out.
let many = limits_with_samples(100_000);
let uniform = env_from(8, 4, |_, _| [MAX_RADIANCE; 3]);
let mips = try_prefilter(&uniform, &opts(|o| (o.levels, o.samples) = (2, 100_000)), &many).unwrap();
assert!(mips[1].pixels().iter().flatten().all(|v| rel(*v, MAX_RADIANCE) < 1e-3), "{:?}", mips[1].pixels());
let spot = env_from(32, 16, |x, y| if (x, y) == (8, 8) { [MAX_RADIANCE; 3] } else { [0.0; 3] });
let mips = try_prefilter(&spot, &PrefilterOptions::default(), &limits).unwrap();
let peak = mips[5].pixels().iter().flatten().fold(0.0f32, |a, v| a.max(*v));
assert!(peak > 0.0 && peak < MAX_RADIANCE / 10.0, "{peak}");
let c = try_sh9(&uniform, &limits).unwrap();
let e = irradiance(&c, [0.3, 0.4, 0.5]).unwrap();
assert!(e.iter().all(|v| rel(*v, MAX_RADIANCE) < 1e-4), "{e:?}");
let mut c = [[0.0; 3]; 9];
c[4][1] = f32::NAN;
assert!(matches!(irradiance(&c, [0.0, 1.0, 0.0]), Err(PbrError::BadOption(_))));
}
fn limits_with_samples(samples: u32) -> Limits {
limits(|l| {
l.max_samples = samples;
l.max_work = u64::MAX;
})
}
#[test]
fn sources_over_the_size_limits_are_refused() {
let env = env_from(16, 8, |_, _| [1.0; 3]);
let few = limits(|l| l.max_pixels = 100);
assert_eq!(try_prefilter(&env, &PrefilterOptions::default(), &few), Err(PbrError::TooLarge(16, 8)));
assert_eq!(try_sh9(&env, &few), Err(PbrError::TooLarge(16, 8)));
let narrow = limits(|l| l.max_side = 8);
assert_eq!(try_prefilter(&env, &PrefilterOptions::default(), &narrow), Err(PbrError::BadSize(16, 8)));
}
#[test]
fn options_out_of_range_are_refused() {
let env = env_from(16, 8, |_, _| [1.0; 3]);
let limits = Limits::default();
let bad: [PrefilterOptions; 9] = [
opts(|o| o.levels = 0),
opts(|o| o.levels = 9),
opts(|o| o.samples = 0),
opts(|o| o.samples = 1025),
opts(|o| o.lod_bias = f32::NAN),
opts(|o| o.lod_bias = f32::INFINITY),
opts(|o| o.firefly_cap = Some(0.0)),
opts(|o| o.firefly_cap = Some(-1.0)),
opts(|o| o.firefly_cap = Some(f32::NAN)),
];
for options in bad {
assert!(matches!(try_prefilter(&env, &options, &limits), Err(PbrError::BadOption(_))), "{options:?}");
}
assert_eq!(hammersley(0, 0), None);
assert_eq!(hammersley(4, 4), None);
let [u, v] = hammersley(1, 4).unwrap();
assert!((u - 0.25).abs() < 1e-6 && (v - 0.5).abs() < 1e-6, "{u} {v}");
}
#[test]
fn directions_that_are_not_finite_or_zero_are_refused() {
let env = env_from(16, 8, |_, _| [2.0; 3]);
let c = try_sh9(&env, &Limits::default()).unwrap();
for d in [[0.0; 3], [f32::NAN, 0.0, 1.0], [f32::INFINITY, 0.0, 0.0]] {
assert_eq!(env.sample(d), Err(PbrError::BadDirection), "{d:?}");
assert_eq!(sh_basis(d), Err(PbrError::BadDirection), "{d:?}");
assert_eq!(irradiance(&c, d), Err(PbrError::BadDirection), "{d:?}");
}
// Directions need not be unit length.
assert_eq!(env.sample([1e30, 0.0, 0.0]), Ok([2.0; 3]));
assert_eq!(env.sample([0.0, 1e-30, 0.0]), Ok([2.0; 3]));
assert_eq!(env.sample([0.0, 0.0, 1e-40]), Ok([2.0; 3]));
assert_eq!(sh_basis([f32::from_bits(1), 0.0, 0.0]), sh_basis([1.0, 0.0, 0.0]));
assert_eq!(sh_basis([0.0, 0.0, 5.0]), sh_basis([0.0, 0.0, 1.0]));
}
#[test]
fn tiny_and_odd_sources_give_levels_that_never_grow() {
let limits = Limits::default();
for (w, h) in [(1, 1), (3, 1), (2, 3), (5, 3), (37, 19), (9, 4)] {
let env = env_from(w, h, |x, y| [x as f32, y as f32, 1.0]);
let mips = try_prefilter(&env, &opts(|o| o.levels = 8), &limits).unwrap();
assert_eq!(mips.len(), 8);
for pair in mips.windows(2) {
assert!(pair[1].width() <= pair[0].width() && pair[1].height() <= pair[0].height(), "{w}x{h}");
assert!(pair[1].width() >= pair[0].width().min(4) && pair[1].height() >= pair[0].height().min(2), "{w}x{h}");
}
assert!(mips.iter().all(|m| m.pixels().iter().all(|p| p.iter().all(|v| v.is_finite() && *v >= 0.0))));
assert!(try_sh9(&env, &limits).is_ok());
}
}
+136
View File
@@ -0,0 +1,136 @@
//! This crate against the apps' previous code (`crate::reference`), on the same generated
//! environments. With the apps' settings (a firefly cap of 64, 128 samples, a level bias of 1),
//! every level matches within `TOLERANCE` for sources with even sides. The intended differences:
//! halving an odd side keeps the last column or row, which the previous code dropped, so levels
//! read from the pyramid of an odd-sized source differ; and the SH projection integrates the
//! basis over each pixel of the full source and sums in `f64`, so the irradiance differs within
//! `SH_TOLERANCE`.
use craft_pbr::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, Limits, PrefilterOptions, irradiance, try_prefilter, try_sh9};
use crate::reference::{materialcraft as mc, texturecraft as tc};
use crate::{max_rel_diff, opts};
/// Largest difference allowed, relative to `max(1, |value|)`.
const TOLERANCE: f32 = 1e-5;
/// Largest difference allowed in the irradiance the SH coefficients give, relative to
/// `max(1, |value|)`. The previous code took each pixel's basis value and solid angle at its
/// center, and halved sources over 128 by plain averaging; the difference is about
/// `1.3 / rows²` at 128 rows or fewer: 3.2e-4 at 64 rows, 2.9e-3 at 19.
const SH_TOLERANCE: f32 = 4e-3;
fn apps_options(levels: u32) -> PrefilterOptions {
opts(|o| {
o.levels = levels;
o.firefly_cap = Some(64.0);
})
}
fn to_reference(env: &EnvImage) -> tc::EnvImage {
tc::EnvImage { width: env.width(), height: env.height(), data: env.pixels().to_vec() }
}
/// The largest difference of each prefiltered level and of the SH coefficients.
fn compare(env: &EnvImage, levels: u32) -> (Vec<f32>, f32) {
let ours = try_prefilter(env, &apps_options(levels), &Limits::default()).unwrap();
let theirs = tc::prefilter(&to_reference(env), levels);
assert_eq!(ours.len(), theirs.len());
let diffs = ours
.iter()
.zip(&theirs)
.map(|(a, b)| {
assert_eq!((a.width(), a.height()), (b.width, b.height));
max_rel_diff(a.pixels(), &b.data)
})
.collect();
let sh = try_sh9(env, &Limits::default()).unwrap();
let sh_ref = tc::sh9(&to_reference(env));
(diffs, irradiance_diff(&sh, &sh_ref))
}
/// The largest difference of the irradiance two SH sets give, over 26 normals (the axes, the
/// face diagonals and the corner diagonals), relative to `max(1, |value|)`.
fn irradiance_diff(a: &[[f32; 3]; 9], b: &[[f32; 3]; 9]) -> f32 {
let normals = (-1..=1).flat_map(|x| (-1..=1).flat_map(move |y| (-1..=1).map(move |z| [x as f32, y as f32, z as f32])));
let (ea, eb): (Vec<[f32; 3]>, Vec<[f32; 3]>) =
normals.filter(|n| *n != [0.0; 3]).map(|n| (irradiance(a, n).unwrap(), irradiance(b, n).unwrap())).unzip();
max_rel_diff(&ea, &eb)
}
fn assert_matches(label: &str, env: &EnvImage, levels: u32) {
let (levels, sh) = compare(env, levels);
eprintln!("{label}: level differences {levels:?}, SH difference {sh}");
assert!(levels.iter().all(|d| *d <= TOLERANCE), "{label}: {levels:?}");
assert!(sh <= SH_TOLERANCE, "{label}: SH {sh}");
}
#[test]
fn the_procedural_environments_match_the_apps() {
let limits = Limits::default();
assert_eq!(ENVIRONMENTS, tc::ENVIRONMENTS);
for e in Environment::ALL {
for width in [64, 128, 256] {
let ours = e.try_render(width, &limits).unwrap();
let theirs = tc::environment(e.name(), width);
let d = max_rel_diff(ours.pixels(), &theirs.data);
assert!(d <= TOLERANCE, "{} at {width}: {d}", e.name());
assert_matches(&format!("{} at {width}", e.name()), &ours, 6);
}
}
}
#[test]
fn materialcraft_names_map_onto_the_environments() {
assert_eq!(ENVIRONMENTS, mc::ENVIRONMENTS);
for id in ["studio", "sunset", "overcast", "night", "contrast", "warehouse", "unknown"] {
assert!(Environment::from_name(mc::by_id(id)).is_some(), "{id}");
}
}
#[test]
fn synthetic_environments_match_the_apps() {
let (w, h) = (128u32, 64u32);
let make = |f: &dyn Fn(u32, u32) -> [f32; 3]| crate::env_from(w, h, f);
assert_matches("constant 2", &make(&|_, _| [2.0, 1.0, 0.5]), 6);
assert_matches("constant 100, over the cap", &make(&|_, _| [100.0; 3]), 6);
// One bright texel in each quadrant and at each pole.
for (px, py) in [(10, 20), (70, 20), (10, 44), (70, 44), (5, 0), (90, 63)] {
assert_matches(&format!("bright texel at {px},{py}"), &make(&move |x, y| if (x, y) == (px, py) { [5000.0; 3] } else { [0.05; 3] }), 6);
}
assert_matches("linear field", &make(&|x, y| [x as f32 / 128.0, y as f32 / 64.0, 1.0]), 8);
assert_matches("quadratic field", &make(&|x, y| [(x as f32 / 64.0 - 1.0).powi(2), (y as f32 / 32.0 - 1.0).powi(2), 0.5]), 3);
}
#[test]
fn odd_sizes_differ_only_where_halving_drops_an_edge() {
for (w, h) in [(37u32, 19u32), (129, 64), (128, 65)] {
let env = crate::env_from(w, h, |x, y| [1.0 + x as f32 / w as f32, 1.0 + y as f32 / h as f32, 1.0]);
let (levels, sh) = compare(&env, 6);
eprintln!("{w}x{h}: level differences {levels:?}, SH difference {sh}");
assert_eq!(levels[0], 0.0, "{w}x{h}: level 0 is the source");
// The previous code halved sources over 128 for SH; a smaller one projects the same pixels.
if w <= 128 && h <= 128 {
assert!(sh <= SH_TOLERANCE, "{w}x{h}: SH {sh}");
}
}
}
#[test]
fn rgba_import_matches_the_apps_at_sizes_they_keep() {
let (w, h) = (128u32, 64u32);
let rgba: Vec<[f32; 4]> = (0..w * h)
.map(|i| [(i % 97) as f32 / 40.0, f32::NAN, -0.5 + (i % 13) as f32 / 4.0, 1.0])
.map(|mut p| {
if p[0] > 2.0 {
p[1] = f32::INFINITY;
}
p
})
.collect();
for (encoding, srgb) in [(ColorEncoding::Linear, false), (ColorEncoding::Srgb, true)] {
let ours = EnvImage::try_from_rgba(w, h, &rgba, encoding, &Limits::default()).unwrap();
let theirs = tc::EnvImage::from_rgba(w, h, &rgba, srgb).unwrap();
assert_eq!(ours.pixels(), &theirs.data[..], "{encoding:?}");
}
}
+64
View File
@@ -0,0 +1,64 @@
//! Integration tests: one test binary for the crate, one module per area.
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod bench;
mod bounds;
mod differential;
mod moved;
mod numeric;
/// Verbatim copies of the apps' previous code, run by `differential`.
mod reference {
pub mod materialcraft;
pub mod texturecraft;
}
use craft_pbr::{EnvImage, Limits, PrefilterOptions};
/// The default options with `f` applied.
pub fn opts(f: impl FnOnce(&mut PrefilterOptions)) -> PrefilterOptions {
let mut o = PrefilterOptions::default();
f(&mut o);
o
}
/// The default limits with `f` applied.
pub fn limits(f: impl FnOnce(&mut Limits)) -> Limits {
let mut l = Limits::default();
f(&mut l);
l
}
/// The largest difference between two pixel lists, relative to `max(1, |a|, |b|)` per value.
/// Lists of different lengths differ by infinity.
pub fn max_rel_diff(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 {
if a.len() != b.len() {
return f32::INFINITY;
}
a.iter().zip(b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs() / 1f32.max(x.abs()).max(y.abs()))).fold(0.0, f32::max)
}
/// An environment of linear pixels made by `f(x, y)`, with default limits.
pub fn env_from(w: u32, h: u32, f: impl Fn(u32, u32) -> [f32; 3]) -> EnvImage {
let data = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| f(x, y)).collect();
EnvImage::try_from_linear(w, h, data, &Limits::default()).unwrap()
}
/// Radiance integrated over the sphere: bilinear lookups on a 512 × 256 grid, each times its
/// solid angle. The same grid for every level keeps coarse levels comparable with the source.
pub fn energy(env: &EnvImage) -> [f64; 3] {
let (w, h) = (512usize, 256usize);
let mut e = [0.0f64; 3];
for y in 0..h {
let v = (y as f64 + 0.5) / h as f64;
let dw = (std::f64::consts::TAU / w as f64) * (std::f64::consts::PI / h as f64) * (std::f64::consts::PI * v).sin();
for x in 0..w {
let p = env.sample(craft_pbr::dir_of((x as f32 + 0.5) / w as f32, v as f32)).unwrap();
for c in 0..3 {
e[c] += f64::from(p[c]) * dw;
}
}
}
e
}
+79
View File
@@ -0,0 +1,79 @@
//! The tests of TextureCraft's and MaterialCraft's `ibl.rs`, on this crate's API. The import test
//! runs TextureCraft's import sizing (halve above 2048, resample below 128 × 64) the way its
//! adapter does, since that sizing stays in the app.
use craft_pbr::{ColorEncoding, ENVIRONMENTS, EnvImage, Environment, Limits, PrefilterOptions, dir_of, irradiance, try_prefilter, try_sh9, uv_of};
use crate::{limits, opts};
#[test]
fn uv_and_direction_round_trip() {
for i in 1..20 {
for j in 1..10 {
let (u, v) = (i as f32 / 20.0, j as f32 / 10.0);
let back = uv_of(dir_of(u, v));
assert!((back[0] - u).abs() < 1e-4 && (back[1] - v).abs() < 1e-4);
}
}
}
#[test]
fn sh_of_a_uniform_environment_is_constant_irradiance() {
let env = EnvImage::try_from_linear(64, 32, vec![[1.0, 1.0, 1.0]; 64 * 32], &Limits::default()).unwrap();
let c = try_sh9(&env, &Limits::default()).unwrap();
for d in [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.3, -0.8, 0.5]] {
let e = irradiance(&c, d).unwrap()[0];
assert!((e - 1.0).abs() < 0.03, "{e}");
}
}
#[test]
fn prefilter_levels_shrink_and_stay_finite() {
let limits = Limits::default();
let env = Environment::StudioSoft.try_render(128, &limits).unwrap();
let options = opts(|o| o.levels = 5);
let mips = try_prefilter(&env, &options, &limits).unwrap();
assert_eq!(mips.len(), 5);
assert!(mips[4].width() < mips[1].width());
for m in &mips {
assert!(m.pixels().iter().all(|c| c.iter().all(|v| v.is_finite() && *v >= 0.0)));
}
for name in ENVIRONMENTS {
let e = Environment::from_name(name).unwrap().try_render(64, &limits).unwrap();
assert!(e.pixels().iter().any(|c| c[0] > 0.5), "{name} has no light");
}
}
/// TextureCraft's import sizing, as its adapter applies it after `try_from_rgba`.
fn texturecraft_import(width: u32, height: u32, rgba: &[[f32; 4]], encoding: ColorEncoding) -> Option<EnvImage> {
let limits = limits(|l| {
l.max_side = 1 << 16;
l.max_pixels = 1 << 26;
l.max_bytes = 1 << 30;
});
let mut img = EnvImage::try_from_rgba(width, height, rgba, encoding, &limits).ok()?;
while img.width() > 2048 || img.height() > 2048 {
img = img.try_half(&limits).ok()?;
}
if img.width() < 128 || img.height() < 64 {
img = img.try_resampled(img.width().max(128), img.height().max(64), &limits).ok()?;
}
Some(img)
}
#[test]
fn imported_images_become_safe_linear_environments() {
assert!(texturecraft_import(4, 2, &[[0.0; 4]; 7], ColorEncoding::Linear).is_none(), "pixel count must match");
// HDR values stay above 1; NaN, infinity and negatives become 0; tiny images grow to 128×64.
let px = [[50.0, f32::NAN, -1.0, 1.0], [f32::INFINITY, 0.5, 0.25, 1.0]];
let e = texturecraft_import(2, 1, &px, ColorEncoding::Linear).unwrap();
assert_eq!((e.width(), e.height()), (128, 64));
assert!(e.pixels().iter().all(|c| c.iter().all(|v| v.is_finite() && *v >= 0.0)));
assert!(e.pixels().iter().any(|c| c[0] > 40.0), "HDR range is kept");
// 8-bit images are sRGB-decoded; big ones are halved down to the import limit.
let e = texturecraft_import(4096, 2048, &vec![[0.5, 0.5, 0.5, 1.0]; 4096 * 2048], ColorEncoding::Srgb).unwrap();
assert_eq!((e.width(), e.height()), (2048, 1024));
assert!((e.pixels()[0][0] - 0.214).abs() < 0.01, "{}", e.pixels()[0][0]);
let mips = try_prefilter(&e, &PrefilterOptions::default(), &Limits::default()).unwrap();
assert!(mips.iter().all(|m| m.pixels().iter().all(|c| c.iter().all(|v| v.is_finite()))));
}
+167
View File
@@ -0,0 +1,167 @@
//! Numeric properties of the filtering: constants stay constant, GGX is normalized, energy is
//! kept, and the SH projection matches analytic irradiance.
use craft_pbr::{EnvImage, Environment, Limits, PrefilterOptions, dir_of, ggx_distribution, irradiance, try_prefilter, try_sh9};
use crate::{energy, env_from, max_rel_diff, opts};
#[test]
fn a_constant_environment_prefilters_to_itself_at_every_roughness() {
// 100 is above the cap of 64 that the apps' copies always applied; the default has no cap.
for value in [0.25, 3.0, 100.0] {
let env = env_from(64, 32, |_, _| [value, value * 0.5, value * 2.0]);
let mips = try_prefilter(&env, &PrefilterOptions::default(), &Limits::default()).unwrap();
assert_eq!(mips.len(), 6);
for (l, m) in mips.iter().enumerate() {
let want = vec![[value, value * 0.5, value * 2.0]; m.pixels().len()];
let d = max_rel_diff(m.pixels(), &want);
assert!(d < 1e-5, "level {l} of {value} differs by {d}");
}
}
}
#[test]
fn the_firefly_cap_applies_only_when_set() {
let env = env_from(64, 32, |_, _| [100.0; 3]);
let options = opts(|o| o.firefly_cap = Some(64.0));
let mips = try_prefilter(&env, &options, &Limits::default()).unwrap();
assert_eq!(mips[0].pixels()[0], [100.0; 3], "level 0 is never capped");
assert!((mips[3].pixels()[0][0] - 64.0).abs() < 1e-3, "{:?}", mips[3].pixels()[0]);
}
#[test]
fn roughness_zero_is_the_source_bit_for_bit() {
let limits = Limits::default();
let env = Environment::Sunset.try_render(128, &limits).unwrap();
let one = try_prefilter(&env, &opts(|o| o.levels = 1), &limits).unwrap();
assert_eq!(one, vec![env.clone()]);
let six = try_prefilter(&env, &opts(|o| o.firefly_cap = Some(64.0)), &limits).unwrap();
assert_eq!(six[0], env);
}
#[test]
fn ggx_projected_area_integrates_to_one() {
// ∫ D(h) (n·h) dω over the hemisphere = 2π ∫₀¹ D(μ) μ dμ, by the midpoint rule in μ = n·h.
let steps = 1_000_000;
for roughness in [0.1, 0.3, 0.5, 0.8, 1.0] {
let sum: f64 = (0..steps)
.map(|i| {
let mu = (i as f64 + 0.5) / steps as f64;
f64::from(ggx_distribution(mu as f32, roughness)) * mu
})
.sum();
let integral = sum / steps as f64 * std::f64::consts::TAU;
assert!((integral - 1.0).abs() < 1e-3, "roughness {roughness}: {integral}");
}
// The peak 1 / (π α²) at n·h = 1, with α at its floor of 0.001 for roughness 0.
for (roughness, alpha) in [(0.0f32, 1e-3f64), (0.05, 0.0025), (0.2, 0.04)] {
let peak = 1.0 / (std::f64::consts::PI * alpha * alpha);
let d = f64::from(ggx_distribution(1.0, roughness));
assert!((d / peak - 1.0).abs() < 1e-3, "roughness {roughness}: {d} for {peak}");
}
}
/// The radiance of each level at least 32 pixels wide integrated over the sphere, relative to the
/// source's. Narrower levels are left out: bilinear lookups between their few pixel centers miss
/// the peak of a lobe, so the measurement, not the filtering, loses energy there.
fn energy_ratios(env: &EnvImage) -> Vec<f64> {
let source = energy(env);
let mips = try_prefilter(env, &PrefilterOptions::default(), &Limits::default()).unwrap();
mips.iter().filter(|m| m.width() >= 32).map(|m| energy(m)[0] / source[0]).collect()
}
/// Largest change of the light energy of a level, relative to the source. The 128 samples read a
/// box pyramid, so small bright lights lose some energy as roughness grows: on 256-wide sources
/// the most measured is 5.3%, the Warehouse lights at roughness 0.6.
const ENERGY_TOLERANCE: f64 = 0.07;
#[test]
fn prefiltering_keeps_the_light_energy() {
let limits = Limits::default();
for e in Environment::ALL {
let env = e.try_render(256, &limits).unwrap();
let ratios = energy_ratios(&env);
eprintln!("{}: energy ratios {ratios:?}", e.name());
assert_eq!(ratios.len(), 4);
for (l, r) in ratios.iter().enumerate() {
assert!((r - 1.0).abs() < ENERGY_TOLERANCE, "{} level {l}: energy ratio {r}", e.name());
}
}
// A small bright patch facing +Z on a dim background.
let patch = env_from(256, 128, |x, y| if (60..68).contains(&x) && (60..68).contains(&y) { [500.0; 3] } else { [0.1; 3] });
let ratios = energy_ratios(&patch);
eprintln!("patch: energy ratios {ratios:?}");
for (l, r) in ratios.iter().enumerate() {
assert!((r - 1.0).abs() < ENERGY_TOLERANCE, "patch level {l}: energy ratio {r}");
}
}
#[test]
fn a_bright_patch_lights_the_normals_facing_it() {
let env = env_from(128, 64, |x, y| if (30..34).contains(&x) && (30..34).contains(&y) { [500.0; 3] } else { [0.1; 3] });
let mips = try_prefilter(&env, &PrefilterOptions::default(), &Limits::default()).unwrap();
for m in &mips[1..] {
let toward = m.sample(dir_of(0.25, 0.5)).unwrap()[0];
let away = m.sample(dir_of(0.75, 0.5)).unwrap()[0];
assert!(toward > 4.0 * away, "{}x{}: {toward} toward, {away} away", m.width(), m.height());
}
}
#[test]
fn sh9_matches_analytic_irradiance_of_linear_and_quadratic_fields() {
let limits = Limits::default();
let field = |f: fn([f32; 3]) -> f32| {
env_from(128, 64, move |x, y| {
let d = dir_of((x as f32 + 0.5) / 128.0, (y as f32 + 0.5) / 64.0);
[f(d); 3]
})
};
// L = 1 + y / 2 gives E / π = 1 + y / 3; L = x² gives E / π = 1/3 + (x² − 1/3) / 4.
let linear = try_sh9(&field(|d| 1.0 + 0.5 * d[1]), &limits).unwrap();
let quadratic = try_sh9(&field(|d| d[0] * d[0]), &limits).unwrap();
for n in [[0.0, 1.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.6, 0.0, 0.8], [0.48, 0.6, -0.64]] {
let e = irradiance(&linear, n).unwrap()[0];
assert!((e - (1.0 + n[1] / 3.0)).abs() < 0.02, "linear at {n:?}: {e}");
let e = irradiance(&quadratic, n).unwrap()[0];
let want = 1.0 / 3.0 + (n[0] * n[0] - 1.0 / 3.0) / 4.0;
assert!((e - want).abs() < 0.02, "quadratic at {n:?}: {e} for {want}");
}
}
#[test]
fn sh9_weights_a_row_near_the_pole_by_its_solid_angle() {
// Only the top row is lit. Its solid angle is 2π (1 − cos(π / h)), so the constant band of
// the irradiance is L (1 − cos(π / h)) / 2, at every width, also above 128 pixels.
for (w, h) in [(64, 32), (256, 128), (512, 256)] {
let env = env_from(w, h, |_, y| if y == 0 { [1000.0; 3] } else { [0.0; 3] });
let c = try_sh9(&env, &Limits::default()).unwrap();
let expected = 1000.0 * (1.0 - (std::f64::consts::PI / h as f64).cos()) / 2.0;
let dc = f64::from(c[0][0]) * 0.282_094_791_773_878_14;
assert!((dc / expected - 1.0).abs() < 1e-4, "{w}x{h}: {dc} for {expected}");
}
}
#[test]
fn sh9_of_a_uniform_environment_is_uniform_at_any_height() {
// Each pixel is projected with the basis integrated over its area, so the directional terms
// of a uniform image vanish even with one or two rows or columns.
for (w, h) in [(1, 1), (4, 1), (1, 3), (4, 2), (3, 5), (16, 8), (64, 32)] {
let c = try_sh9(&env_from(w, h, |_, _| [1.0; 3]), &Limits::default()).unwrap();
for n in [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.3, -0.8, 0.5]] {
let e = irradiance(&c, n).unwrap()[0];
assert!((e - 1.0).abs() < 1e-4, "{w}x{h} at {n:?}: {e}");
}
}
}
#[test]
fn halving_an_odd_side_keeps_the_last_column_and_row() {
let limits = Limits::default();
// Only the last column of a 5 × 3 image is lit, then only the last row.
for (w, h, lit) in [(5u32, 3u32, true), (3, 5, false)] {
let env = env_from(w, h, |x, y| if (lit && x == w - 1) || (!lit && y == h - 1) { [9.0; 3] } else { [0.0; 3] });
let half = env.try_half(&limits).unwrap();
let mean = |e: &EnvImage| e.pixels().iter().map(|p| f64::from(p[0])).sum::<f64>() / e.pixels().len() as f64;
assert!((mean(&half) - mean(&env)).abs() < 1e-5, "{w}x{h}: mean {} for {}", mean(&half), mean(&env));
}
}
@@ -0,0 +1,20 @@
//! The parts of MaterialCraft's `crates/render/src/ibl.rs` at 4ff5af9af7 that differ from
//! TextureCraft's copy. The rest of that file (directions, procedural environments, lookup,
//! halving, the prefilter, SH9 and the basis) is the same text as `super::texturecraft` apart
//! from the glam import path and `hammersley` being `pub(crate)`, so the differential tests run
//! that one copy for both apps.
/// Built-in environments, in menu order.
pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"];
/// The environment for a 3D view id (`studio`, `sunset`, `overcast`, `night`).
pub fn by_id(id: &str) -> &'static str {
match id {
"sunset" => "Sunset",
"overcast" => "Overcast",
"night" => "Night",
"contrast" => "Studio Contrast",
"warehouse" => "Warehouse",
_ => "Studio Soft",
}
}
@@ -0,0 +1,282 @@
//! TextureCraft's `crates/render/src/ibl.rs` at fe8ee1bdb0, without its tests, for the
//! differential tests. Only the imports changed: glam and the sRGB decoder come from this
//! crate's dependencies, and `ENVIRONMENTS` is defined here instead of imported from
//! `texturecraft_core::project` (the same six names).
use std::f32::consts::{PI, TAU};
use glam::{Vec2, Vec3};
use rayon::prelude::*;
/// An equirect HDR image (linear RGB).
#[derive(Clone, Debug)]
pub struct EnvImage {
pub width: u32,
pub height: u32,
pub data: Vec<[f32; 3]>,
}
pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast", "Sunset", "Warehouse", "Night"];
pub fn dir_of(u: f32, v: f32) -> Vec3 {
let (theta, phi) = (v * PI, u * TAU);
Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin())
}
pub fn uv_of(d: Vec3) -> Vec2 {
let phi = d.z.atan2(d.x);
Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI)
}
/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees).
struct SoftBox {
az: f32,
el: f32,
hw: f32,
hh: f32,
color: Vec3,
}
impl SoftBox {
fn eval(&self, d: Vec3) -> Vec3 {
let el = d.y.clamp(-1.0, 1.0).asin().to_degrees();
let az = d.z.atan2(d.x).to_degrees();
let daz = ((az - self.az + 540.0).rem_euclid(360.0)) - 180.0;
let (x, y) = (daz.abs() / self.hw, (el - self.el).abs() / self.hh);
let e = |t: f32| 1.0 - smooth((t - 0.8) / 0.4);
self.color * e(x) * e(y)
}
}
fn smooth(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 {
if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(0.6)) } else { horizon.lerp(ground, (-d.y).powf(0.25)) }
}
fn radiance(name: &str, d: Vec3) -> Vec3 {
match name {
"Studio Contrast" => {
let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01));
base + SoftBox { az: 35.0, el: 30.0, hw: 22.0, hh: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d)
+ SoftBox { az: -150.0, el: 40.0, hw: 6.0, hh: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d)
}
"Overcast" => {
let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15));
base + SoftBox { az: 60.0, el: 55.0, hw: 40.0, hh: 25.0, color: Vec3::splat(0.6) }.eval(d)
}
"Sunset" => {
let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05));
let sun_dir = dir_of(0.12, 0.47);
let sun = smooth((d.dot(sun_dir) - 0.9985) / 0.0012) * 120.0;
base + Vec3::new(1.0, 0.6, 0.3) * sun
}
"Warehouse" => {
let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06));
for k in 0..6 {
c += SoftBox { az: -150.0 + k as f32 * 60.0, el: 50.0, hw: 6.0, hh: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d);
}
c + SoftBox { az: 90.0, el: 5.0, hw: 30.0, hh: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d)
}
"Night" => {
let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005));
base + SoftBox { az: 20.0, el: 15.0, hw: 10.0, hh: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d)
+ SoftBox { az: -110.0, el: 10.0, hw: 12.0, hh: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d)
}
// "Studio Soft" (default)
_ => {
let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07));
base + SoftBox { az: 40.0, el: 35.0, hw: 28.0, hh: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d)
+ SoftBox { az: -125.0, el: 20.0, hw: 35.0, hh: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d)
+ SoftBox { az: 175.0, el: 55.0, hw: 8.0, hh: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d)
}
}
}
/// Render a built-in environment (unknown names give the default studio).
pub fn environment(name: &str, width: u32) -> EnvImage {
let w = width.clamp(16, 4096);
let h = w / 2;
let mut data = vec![[0.0f32; 3]; (w * h) as usize];
data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let d = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
*px = radiance(name, d).to_array();
}
});
EnvImage { width: w, height: h, data }
}
impl EnvImage {
fn get(&self, x: i64, y: i64) -> Vec3 {
let xx = x.rem_euclid(self.width as i64) as u32;
let yy = y.clamp(0, self.height as i64 - 1) as u32;
self.data.get((yy * self.width + xx) as usize).map(|v| Vec3::from(*v)).unwrap_or(Vec3::ZERO)
}
/// Bilinear lookup by direction.
pub fn sample(&self, d: Vec3) -> Vec3 {
let uv = uv_of(d);
let (fx, fy) = (uv.x * self.width as f32 - 0.5, uv.y * self.height as f32 - 0.5);
let (x0, y0) = (fx.floor() as i64, fy.floor() as i64);
let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
let a = self.get(x0, y0).lerp(self.get(x0 + 1, y0), tx);
let b = self.get(x0, y0 + 1).lerp(self.get(x0 + 1, y0 + 1), tx);
a.lerp(b, ty)
}
/// Box-downsample by 2.
pub fn half(&self) -> EnvImage {
let (w, h) = ((self.width / 2).max(1), (self.height / 2).max(1));
let mut data = vec![[0.0f32; 3]; (w * h) as usize];
data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let (sx, sy) = (x as i64 * 2, y as i64 * 2);
let s = (self.get(sx, sy) + self.get(sx + 1, sy) + self.get(sx, sy + 1) + self.get(sx + 1, sy + 1)) * 0.25;
*px = s.to_array();
}
});
EnvImage { width: w, height: h, data }
}
/// An imported equirect image (`rgba` row-major, top row first, sRGB-encoded when `srgb`) as
/// linear radiance: non-finite and negative values become 0, values are capped to the f16
/// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the
/// pixel count does not match the size.
pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option<EnvImage> {
if width == 0 || height == 0 || rgba.len() as u64 != width as u64 * height as u64 {
return None;
}
let lin = |v: f32| {
let v = if v.is_finite() { v.clamp(0.0, 65_000.0) } else { 0.0 };
if srgb { craft_texture::srgb_to_linear(v.min(1.0)) } else { v }
};
let data = rgba.par_iter().map(|p| [lin(p[0]), lin(p[1]), lin(p[2])]).collect();
let mut img = EnvImage { width, height, data };
while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH {
img = img.half();
}
// The mip chain needs at least 4×2 texels at its last level.
if img.width < 128 || img.height < 64 {
let (w, h) = (img.width.max(128), img.height.max(64));
let data =
(0..w * h).map(|i| img.sample(dir_of(((i % w) as f32 + 0.5) / w as f32, ((i / w) as f32 + 0.5) / h as f32)).to_array()).collect();
img = EnvImage { width: w, height: h, data };
}
Some(img)
}
}
/// Widest imported environment kept (2K equirect: about 5.6 texels per degree).
pub const MAX_IMPORT_WIDTH: u32 = 2048;
fn hammersley(i: u32, n: u32) -> Vec2 {
Vec2::new(i as f32 / n as f32, i.reverse_bits() as f32 * 2.328_306_4e-10)
}
/// GGX-prefiltered mip chain: level `l` of `levels` is filtered for roughness `l / (levels-1)`.
pub fn prefilter(env: &EnvImage, levels: u32) -> Vec<EnvImage> {
let levels = levels.clamp(1, 8);
// Clamp fireflies, then build a box pyramid to sample from (filtered importance sampling).
let clamped = EnvImage { data: env.data.iter().map(|c| c.map(|v| v.min(64.0))).collect(), ..env.clone() };
let mut pyramid = vec![clamped];
while pyramid.len() < 10 && pyramid.last().is_some_and(|p| p.width > 8) {
if let Some(next) = pyramid.last().map(EnvImage::half) {
pyramid.push(next);
}
}
let mut out = vec![env.clone()];
let mut size = (env.width, env.height);
for l in 1..levels {
size = ((size.0 / 2).max(4), (size.1 / 2).max(2));
let rough = l as f32 / (levels - 1) as f32;
let a = (rough * rough).max(1e-3);
let samples = 128u32;
let (w, h) = size;
let sa_texel = 4.0 * PI / (env.width as f32 * env.height as f32);
// With n = v, every sample's half vector, n·l and source level depend only on its index:
// tabulate them once per level as (tangent-space half vector, n·l, pyramid level).
let table: Vec<(Vec3, f32, &EnvImage)> = (0..samples)
.filter_map(|i| {
let xi = hammersley(i, samples);
let phi = TAU * xi.x;
let cos_t = ((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y)).max(0.0).sqrt();
let sin_t = (1.0 - cos_t * cos_t).max(0.0).sqrt();
let ndl = 2.0 * cos_t * cos_t - 1.0;
if ndl <= 0.0 {
return None;
}
let dd = a * a / (PI * ((cos_t * cos_t) * (a * a - 1.0) + 1.0).powi(2)).max(1e-8);
let sa_sample = 1.0 / (samples as f32 * dd / 4.0 + 1e-6);
let lod = (0.5 * (sa_sample / sa_texel).log2() + 1.0).clamp(0.0, (pyramid.len() - 1) as f32);
let src = pyramid.get(lod.round() as usize).unwrap_or(&pyramid[0]);
Some((Vec3::new(sin_t * phi.cos(), sin_t * phi.sin(), cos_t), ndl, src))
})
.collect();
let wsum: f32 = table.iter().map(|t| t.1).sum();
let mut data = vec![[0.0f32; 3]; (w * h) as usize];
data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let n = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
let up = if n.y.abs() < 0.999 { Vec3::Y } else { Vec3::X };
let tx = up.cross(n).normalize();
let ty = n.cross(tx);
let mut acc = Vec3::ZERO;
for (hv, ndl, src) in &table {
let hw = tx * hv.x + ty * hv.y + n * hv.z;
acc += src.sample(hw * (2.0 * hv.z) - n) * *ndl;
}
*px = (acc / wsum.max(1e-6)).to_array();
}
});
out.push(EnvImage { width: w, height: h, data });
}
out
}
/// Diffuse irradiance as 9 SH coefficients (already convolved with the cosine lobe and divided
/// by π, so `Σ c·Y(n)` times albedo is the diffuse radiance).
pub fn sh9(env: &EnvImage) -> [[f32; 3]; 9] {
let mut src = env.clone();
while src.width > 128 {
src = src.half();
}
let (w, h) = (src.width, src.height);
let mut c = [Vec3::ZERO; 9];
for y in 0..h {
let theta = PI * (y as f32 + 0.5) / h as f32;
let dw = (TAU / w as f32) * (PI / h as f32) * theta.sin();
for x in 0..w {
let d = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
// No firefly clamp: the projection integrates, so a bright sun lights diffuse fully.
let l = src.get(x as i64, y as i64) * dw;
for (k, ylm) in sh_basis(d).iter().enumerate() {
c[k] += l * *ylm;
}
}
}
let a = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0];
let mut out = [[0.0; 3]; 9];
for k in 0..9 {
out[k] = (c[k] * a[k] / PI).to_array();
}
out
}
pub fn sh_basis(d: Vec3) -> [f32; 9] {
let (x, y, z) = (d.x, d.y, d.z);
[
0.282_095,
0.488_603 * y,
0.488_603 * z,
0.488_603 * x,
1.092_548 * x * y,
1.092_548 * y * z,
0.315_392 * (3.0 * z * z - 1.0),
1.092_548 * x * z,
0.546_274 * (x * x - y * y),
]
}