pub const SH_C0: f32 = 0.282_094_8_f32;
pub const SH_C1: f32 = 0.488_602_52_f32;
pub const SH_C2: [f32; 5] = [
1.092_548_5_f32, -1.092_548_5_f32, 0.315_391_57_f32, -1.092_548_5_f32, 0.546_274_24_f32, ];
pub const SH_C3: [f32; 7] = [
-0.590_043_6_f32, 2.890_611_4_f32, -0.457_045_8_f32, 0.373_176_34_f32, -0.457_045_8_f32, 1.445_305_7_f32, -0.590_043_6_f32, ];
#[derive(Debug, thiserror::Error)]
pub enum ShError {
#[error("Unsupported SH degree: {0}, max is 3")]
UnsupportedDegree(usize),
#[error("Coefficient count mismatch: expected {expected}, got {got}")]
CoeffCountMismatch { expected: usize, got: usize },
#[error("Direction vector must be non-zero")]
ZeroDirection,
#[error("Rotation matrix must be 3x3 row-major")]
InvalidRotationMatrix,
}
#[derive(Debug, Clone)]
pub struct ShBasis {
pub degree: usize,
pub num_coeffs: usize,
}
impl ShBasis {
pub fn new(degree: usize) -> Result<Self, ShError> {
if degree > 3 {
return Err(ShError::UnsupportedDegree(degree));
}
Ok(Self {
degree,
num_coeffs: sh_num_coeffs(degree),
})
}
}
#[inline]
pub fn sh_num_coeffs(degree: usize) -> usize {
(degree + 1) * (degree + 1)
}
#[inline]
fn normalize(direction: [f32; 3]) -> Result<[f32; 3], ShError> {
let [x, y, z] = direction;
let norm = (x * x + y * y + z * z).sqrt();
if norm < 1e-7 {
return Err(ShError::ZeroDirection);
}
Ok([x / norm, y / norm, z / norm])
}
#[inline]
pub fn sh_eval_degree0(_x: f32, _y: f32, _z: f32) -> [f32; 1] {
[SH_C0]
}
#[inline]
pub fn sh_eval_degree1(x: f32, y: f32, z: f32) -> [f32; 4] {
[SH_C0, -SH_C1 * y, SH_C1 * z, -SH_C1 * x]
}
#[inline]
pub fn sh_eval_degree2(x: f32, y: f32, z: f32) -> [f32; 9] {
let [b0, b1, b2, b3] = sh_eval_degree1(x, y, z);
[
b0,
b1,
b2,
b3,
SH_C2[0] * x * y,
SH_C2[1] * y * z,
SH_C2[2] * (2.0 * z * z - x * x - y * y),
SH_C2[3] * x * z,
SH_C2[4] * (x * x - y * y),
]
}
#[inline]
pub fn sh_eval_degree3(x: f32, y: f32, z: f32) -> [f32; 16] {
let [b0, b1, b2, b3, b4, b5, b6, b7, b8] = sh_eval_degree2(x, y, z);
[
b0,
b1,
b2,
b3,
b4,
b5,
b6,
b7,
b8,
SH_C3[0] * y * (3.0 * x * x - y * y),
SH_C3[1] * x * y * z,
SH_C3[2] * y * (4.0 * z * z - x * x - y * y),
SH_C3[3] * z * (2.0 * z * z - 3.0 * x * x - 3.0 * y * y),
SH_C3[4] * x * (4.0 * z * z - x * x - y * y),
SH_C3[5] * z * (x * x - y * y),
SH_C3[6] * x * (x * x - 3.0 * y * y),
]
}
pub fn sh_eval(direction: [f32; 3], degree: usize) -> Result<Vec<f32>, ShError> {
if degree > 3 {
return Err(ShError::UnsupportedDegree(degree));
}
let [x, y, z] = normalize(direction)?;
let out: Vec<f32> = match degree {
0 => sh_eval_degree0(x, y, z).to_vec(),
1 => sh_eval_degree1(x, y, z).to_vec(),
2 => sh_eval_degree2(x, y, z).to_vec(),
_ => sh_eval_degree3(x, y, z).to_vec(),
};
Ok(out)
}
pub fn sh_to_color(
sh_coeffs: &[f32],
direction: [f32; 3],
degree: usize,
) -> Result<[f32; 3], ShError> {
if degree > 3 {
return Err(ShError::UnsupportedDegree(degree));
}
let n = sh_num_coeffs(degree);
let expected = 3 * n;
if sh_coeffs.len() != expected {
return Err(ShError::CoeffCountMismatch {
expected,
got: sh_coeffs.len(),
});
}
let basis = sh_eval(direction, degree)?;
let mut rgb = [0.5_f32; 3];
for (ch, rgb_val) in rgb.iter_mut().enumerate() {
let offset = ch * n;
for (k, &basis_val) in basis.iter().enumerate().take(n) {
*rgb_val += sh_coeffs[offset + k] * basis_val;
}
}
Ok([
rgb[0].clamp(0.0, 1.0),
rgb[1].clamp(0.0, 1.0),
rgb[2].clamp(0.0, 1.0),
])
}
#[inline]
pub fn sh_dc_to_color(dc_r: f32, dc_g: f32, dc_b: f32) -> [f32; 3] {
[
(0.5 + SH_C0 * dc_r).clamp(0.0, 1.0),
(0.5 + SH_C0 * dc_g).clamp(0.0, 1.0),
(0.5 + SH_C0 * dc_b).clamp(0.0, 1.0),
]
}
#[inline]
pub fn color_to_sh_dc(r: f32, g: f32, b: f32) -> [f32; 3] {
[(r - 0.5) / SH_C0, (g - 0.5) / SH_C0, (b - 0.5) / SH_C0]
}
pub fn sh_project_monte_carlo(
samples: &[([f32; 3], [f32; 3])],
degree: usize,
) -> Result<Vec<f32>, ShError> {
if degree > 3 {
return Err(ShError::UnsupportedDegree(degree));
}
let n = sh_num_coeffs(degree);
let num = samples.len();
let mut coeffs = vec![0.0_f32; 3 * n];
if num == 0 {
return Ok(coeffs);
}
let weight = 4.0 * std::f32::consts::PI / num as f32;
for (dir, rgb) in samples {
let basis = sh_eval(*dir, degree)?;
for k in 0..n {
for ch in 0..3 {
coeffs[ch * n + k] += rgb[ch] * basis[k] * weight;
}
}
}
Ok(coeffs)
}
pub fn sh_upsample(
coeffs: &[f32],
from_degree: usize,
to_degree: usize,
) -> Result<Vec<f32>, ShError> {
if from_degree > 3 {
return Err(ShError::UnsupportedDegree(from_degree));
}
if to_degree > 3 {
return Err(ShError::UnsupportedDegree(to_degree));
}
let n_from = sh_num_coeffs(from_degree);
let expected = 3 * n_from;
if coeffs.len() != expected {
return Err(ShError::CoeffCountMismatch {
expected,
got: coeffs.len(),
});
}
if to_degree <= from_degree {
return Ok(coeffs.to_vec());
}
let n_to = sh_num_coeffs(to_degree);
let mut out = vec![0.0_f32; 3 * n_to];
for ch in 0..3 {
let src_offset = ch * n_from;
let dst_offset = ch * n_to;
out[dst_offset..dst_offset + n_from]
.copy_from_slice(&coeffs[src_offset..src_offset + n_from]);
}
Ok(out)
}
pub fn sh_downsample(
coeffs: &[f32],
from_degree: usize,
to_degree: usize,
) -> Result<Vec<f32>, ShError> {
if from_degree > 3 {
return Err(ShError::UnsupportedDegree(from_degree));
}
if to_degree > 3 {
return Err(ShError::UnsupportedDegree(to_degree));
}
let n_from = sh_num_coeffs(from_degree);
let expected = 3 * n_from;
if coeffs.len() != expected {
return Err(ShError::CoeffCountMismatch {
expected,
got: coeffs.len(),
});
}
if to_degree >= from_degree {
return Ok(coeffs.to_vec());
}
let n_to = sh_num_coeffs(to_degree);
let mut out = vec![0.0_f32; 3 * n_to];
for ch in 0..3 {
let src_offset = ch * n_from;
let dst_offset = ch * n_to;
out[dst_offset..dst_offset + n_to].copy_from_slice(&coeffs[src_offset..src_offset + n_to]);
}
Ok(out)
}
pub fn rotate_sh_coeffs_z(
coeffs: &[f32],
angle_rad: f32,
degree: usize,
) -> Result<Vec<f32>, ShError> {
if degree > 3 {
return Err(ShError::UnsupportedDegree(degree));
}
let n = sh_num_coeffs(degree);
let expected = 3 * n;
if coeffs.len() != expected {
return Err(ShError::CoeffCountMismatch {
expected,
got: coeffs.len(),
});
}
let mut out = coeffs.to_vec();
for l in 1..=degree {
for m in 1..=l {
let mf = m as f32;
let c = (mf * angle_rad).cos();
let s = (mf * angle_rad).sin();
let idx_neg = l * l + (l - m); let idx_pos = l * l + (l + m); for ch in 0..3 {
let base = ch * n;
let old_pos = coeffs[base + idx_pos];
let old_neg = coeffs[base + idx_neg];
out[base + idx_pos] = old_pos * c - old_neg * s;
out[base + idx_neg] = old_neg * c + old_pos * s;
}
}
}
Ok(out)
}
pub fn sh_band_energy(coeffs: &[f32], band: usize, num_channels: usize) -> Result<f32, ShError> {
if band > 3 {
return Err(ShError::UnsupportedDegree(band));
}
let coeffs_per_channel = coeffs.len() / num_channels.max(1);
let n_band = 2 * band + 1; let band_start = band * band; let band_end = band_start + n_band;
if band_end > coeffs_per_channel {
return Err(ShError::CoeffCountMismatch {
expected: band_end * num_channels,
got: coeffs.len(),
});
}
let mut sum_sq = 0.0_f32;
let mut count = 0_usize;
for ch in 0..num_channels {
let offset = ch * coeffs_per_channel;
for k in band_start..band_end {
let v = coeffs[offset + k];
sum_sq += v * v;
count += 1;
}
}
if count == 0 {
return Ok(0.0);
}
Ok((sum_sq / count as f32).sqrt())
}
#[cfg(test)]
mod tests {
use super::*;
const EPS: f32 = 1e-5;
fn approx(a: f32, b: f32, tol: f32) -> bool {
(a - b).abs() < tol
}
#[test]
fn test_sh_num_coeffs() {
assert_eq!(sh_num_coeffs(0), 1);
assert_eq!(sh_num_coeffs(1), 4);
assert_eq!(sh_num_coeffs(2), 9);
assert_eq!(sh_num_coeffs(3), 16);
}
#[test]
fn test_sh_eval_degree0_constant() {
let dirs = [[1.0_f32, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5_f32, 0.5, 0.707]];
for [x, y, z] in dirs {
let b = sh_eval_degree0(x, y, z);
assert!(approx(b[0], SH_C0, EPS), "degree0 must equal SH_C0");
}
}
#[test]
fn test_sh_eval_degree1_x_axis() {
let b = sh_eval_degree1(1.0, 0.0, 0.0);
assert!(approx(b[0], SH_C0, EPS));
assert!(approx(b[1], 0.0, EPS)); assert!(approx(b[2], 0.0, EPS)); assert!(approx(b[3], -SH_C1, EPS)); }
#[test]
fn test_sh_eval_normalizes() {
let unit = sh_eval([1.0, 0.0, 0.0], 2).expect("unit ok");
let scaled = sh_eval([3.0, 0.0, 0.0], 2).expect("scaled ok");
for (a, b) in unit.iter().zip(scaled.iter()) {
assert!(
approx(*a, *b, EPS),
"normalized and un-normalized must match"
);
}
}
#[test]
fn test_sh_eval_zero_direction_error() {
let result = sh_eval([0.0, 0.0, 0.0], 1);
assert!(matches!(result, Err(ShError::ZeroDirection)));
}
#[test]
fn test_sh_eval_unsupported_degree() {
let result = sh_eval([1.0, 0.0, 0.0], 4);
assert!(matches!(result, Err(ShError::UnsupportedDegree(4))));
}
#[test]
fn test_sh_to_color_degree0_constant() {
let dc_r = 0.1_f32;
let dc_g = -0.5_f32;
let dc_b = 0.3_f32;
let coeffs = [dc_r, dc_g, dc_b];
let dir1 = sh_to_color(&coeffs, [1.0, 0.0, 0.0], 0).expect("ok");
let dir2 = sh_to_color(&coeffs, [0.0, 1.0, 0.0], 0).expect("ok");
for ch in 0..3 {
assert!(
approx(dir1[ch], dir2[ch], EPS),
"degree-0 color must be view-independent"
);
}
let expected_r = (0.5 + SH_C0 * dc_r).clamp(0.0, 1.0);
assert!(approx(dir1[0], expected_r, EPS));
}
#[test]
fn test_sh_to_color_length_mismatch() {
let bad = [0.0_f32; 5]; let result = sh_to_color(&bad, [1.0, 0.0, 0.0], 1); assert!(matches!(result, Err(ShError::CoeffCountMismatch { .. })));
}
#[test]
fn test_sh_dc_to_color_roundtrip() {
let r = 0.6_f32;
let g = 0.4_f32;
let b = 0.8_f32;
let [dr, dg, db] = color_to_sh_dc(r, g, b);
let recovered = sh_dc_to_color(dr, dg, db);
assert!(approx(recovered[0], r, EPS));
assert!(approx(recovered[1], g, EPS));
assert!(approx(recovered[2], b, EPS));
}
#[test]
fn test_sh_dc_to_color_clamps() {
let out = sh_dc_to_color(100.0, -100.0, 0.0);
assert!(approx(out[0], 1.0, EPS));
assert!(approx(out[1], 0.0, EPS));
}
#[test]
fn test_sh_upsample_0_to_1() {
let coeffs = [0.5_f32, 0.3, 0.2]; let up = sh_upsample(&coeffs, 0, 1).expect("ok");
assert_eq!(up.len(), 3 * 4); assert!(approx(up[0], 0.5, EPS));
assert!(approx(up[4], 0.3, EPS));
assert!(approx(up[8], 0.2, EPS));
for &v in &up[1..4] {
assert!(approx(v, 0.0, EPS));
}
}
#[test]
fn test_sh_upsample_0_to_2() {
let coeffs = [1.0_f32, 2.0, 3.0];
let up = sh_upsample(&coeffs, 0, 2).expect("ok");
assert_eq!(up.len(), 3 * 9);
assert!(approx(up[0], 1.0, EPS));
assert!(approx(up[9], 2.0, EPS));
assert!(approx(up[18], 3.0, EPS));
for (i, &val) in up.iter().enumerate().take(9).skip(1) {
assert!(approx(val, 0.0, EPS), "up[{i}] should be 0");
}
}
#[test]
fn test_sh_downsample_2_to_0() {
let mut coeffs = vec![0.0_f32; 3 * 9];
coeffs[0] = 0.7; coeffs[9] = 0.5; coeffs[18] = 0.3; coeffs[1] = 99.0; let down = sh_downsample(&coeffs, 2, 0).expect("ok");
assert_eq!(down.len(), 3);
assert!(approx(down[0], 0.7, EPS));
assert!(approx(down[1], 0.5, EPS));
assert!(approx(down[2], 0.3, EPS));
}
#[test]
fn test_sh_downsample_2_to_1() {
let mut coeffs = vec![0.0_f32; 3 * 9];
for i in 0..4 {
coeffs[i] = i as f32 + 1.0; coeffs[9 + i] = i as f32 + 5.0; coeffs[18 + i] = i as f32 + 9.0; }
coeffs[4] = 999.0; let down = sh_downsample(&coeffs, 2, 1).expect("ok");
assert_eq!(down.len(), 3 * 4);
for i in 0..4 {
assert!(approx(down[i], i as f32 + 1.0, EPS));
assert!(approx(down[4 + i], i as f32 + 5.0, EPS));
assert!(approx(down[8 + i], i as f32 + 9.0, EPS));
}
}
#[test]
fn test_sh_project_monte_carlo_constant() {
use std::f32::consts::PI;
let target = [0.6_f32, 0.4_f32, 0.2_f32];
let n = 2000_usize;
let golden = (1.0_f32 + 5.0_f32.sqrt()) / 2.0;
let samples: Vec<([f32; 3], [f32; 3])> = (0..n)
.map(|i| {
let fi = i as f32;
let theta = (1.0 - 2.0 * (fi + 0.5) / n as f32).clamp(-1.0, 1.0).acos();
let phi = 2.0 * PI * fi / golden;
let dir = [
theta.sin() * phi.cos(),
theta.cos(),
theta.sin() * phi.sin(),
];
(dir, target)
})
.collect();
let coeffs = sh_project_monte_carlo(&samples, 0).expect("ok");
for ch in 0..3 {
let expected = target[ch] * SH_C0 * 4.0 * PI;
assert!(
approx(coeffs[ch], expected, 0.05),
"ch {ch} DC coeff: got {}, expected {expected}",
coeffs[ch]
);
}
}
#[test]
fn test_sh_band_energy_band0() {
let coeffs = [2.0_f32, 0.0, 0.0]; let energy = sh_band_energy(&coeffs, 0, 3).expect("ok");
let expected = ((4.0 + 0.0 + 0.0) / 3.0_f32).sqrt();
assert!(
approx(energy, expected, EPS),
"got {energy}, expected {expected}"
);
}
#[test]
fn test_rotate_sh_coeffs_z_zero_angle() {
let coeffs: Vec<f32> = (0..3 * 9).map(|i| i as f32 * 0.1).collect();
let rotated = rotate_sh_coeffs_z(&coeffs, 0.0, 2).expect("ok");
for (a, b) in coeffs.iter().zip(rotated.iter()) {
assert!(approx(*a, *b, EPS));
}
}
#[test]
fn test_rotate_sh_coeffs_z_full_revolution() {
let coeffs: Vec<f32> = (0..3 * 16).map(|i| (i as f32 - 24.0) * 0.05).collect();
let rotated = rotate_sh_coeffs_z(&coeffs, 2.0 * std::f32::consts::PI, 3).expect("ok");
for (a, b) in coeffs.iter().zip(rotated.iter()) {
assert!(approx(*a, *b, 1e-4), "original {a} vs rotated {b}");
}
}
#[test]
fn test_sh_to_color_degree1_known() {
let mut coeffs = [0.0_f32; 12];
coeffs[0] = 0.2; coeffs[4] = 0.3; coeffs[8] = 0.4; let dir = [0.0_f32, 1.0, 0.0];
let color = sh_to_color(&coeffs, dir, 1).expect("ok");
let expected_r = (0.5 + SH_C0 * 0.2).clamp(0.0, 1.0);
let expected_g = (0.5 + SH_C0 * 0.3).clamp(0.0, 1.0);
let expected_b = (0.5 + SH_C0 * 0.4).clamp(0.0, 1.0);
assert!(approx(color[0], expected_r, 1e-4));
assert!(approx(color[1], expected_g, 1e-4));
assert!(approx(color[2], expected_b, 1e-4));
}
#[test]
fn test_sh_eval_degree2_cardinal_sum() {
let cards = [
[1.0_f32, 0.0, 0.0],
[-1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, -1.0, 0.0],
[0.0, 0.0, 1.0],
[0.0, 0.0, -1.0],
];
let y20_sum: f32 = cards
.iter()
.map(|&[x, y, z]| {
sh_eval_degree2(x, y, z)[6] })
.sum();
assert!(approx(y20_sum, 0.0, EPS), "Y_2^0 cardinal sum = {y20_sum}");
}
#[test]
fn test_sh_basis_signs_match_shader_convention() {
const SHADER_SH_C1: f32 = 0.488_602_51;
const SHADER_SH_C2_0: f32 = 1.092_548_4;
const SHADER_SH_C2_1: f32 = -1.092_548_4;
const SHADER_SH_C2_2: f32 = 0.315_391_56;
const SHADER_SH_C2_3: f32 = -1.092_548_4;
const SHADER_SH_C2_4: f32 = 0.546_274_2;
const SHADER_SH_C3_0: f32 = -0.590_043_6;
const SHADER_SH_C3_1: f32 = 2.890_611_4;
const SHADER_SH_C3_2: f32 = -0.457_045_8;
const SHADER_SH_C3_3: f32 = 0.373_176_33;
const SHADER_SH_C3_4: f32 = -0.457_045_8;
const SHADER_SH_C3_5: f32 = 1.445_305_7;
const SHADER_SH_C3_6: f32 = -0.590_043_6;
let (x, y, z) = (0.534_522_5_f32, 0.267_261_24_f32, 0.801_783_7_f32);
let tol = 1e-4;
let b1 = sh_eval_degree1(x, y, z);
assert!(approx(b1[1], SHADER_SH_C1 * -y, tol), "Y_1^-1: {}", b1[1]);
assert!(approx(b1[2], SHADER_SH_C1 * z, tol), "Y_1^0: {}", b1[2]);
assert!(approx(b1[3], SHADER_SH_C1 * -x, tol), "Y_1^1: {}", b1[3]);
let b2 = sh_eval_degree2(x, y, z);
assert!(approx(b2[4], SHADER_SH_C2_0 * x * y, tol), "Y_2^-2");
assert!(approx(b2[5], SHADER_SH_C2_1 * y * z, tol), "Y_2^-1");
assert!(
approx(b2[6], SHADER_SH_C2_2 * (2.0 * z * z - x * x - y * y), tol),
"Y_2^0"
);
assert!(approx(b2[7], SHADER_SH_C2_3 * x * z, tol), "Y_2^1");
assert!(
approx(b2[8], SHADER_SH_C2_4 * (x * x - y * y), tol),
"Y_2^2"
);
let b3 = sh_eval_degree3(x, y, z);
assert!(
approx(b3[9], SHADER_SH_C3_0 * y * (3.0 * x * x - y * y), tol),
"Y_3^-3"
);
assert!(approx(b3[10], SHADER_SH_C3_1 * x * y * z, tol), "Y_3^-2");
assert!(
approx(
b3[11],
SHADER_SH_C3_2 * y * (4.0 * z * z - x * x - y * y),
tol
),
"Y_3^-1"
);
assert!(
approx(
b3[12],
SHADER_SH_C3_3 * z * (2.0 * z * z - 3.0 * x * x - 3.0 * y * y),
tol
),
"Y_3^0"
);
assert!(
approx(
b3[13],
SHADER_SH_C3_4 * x * (4.0 * z * z - x * x - y * y),
tol
),
"Y_3^1"
);
assert!(
approx(b3[14], SHADER_SH_C3_5 * z * (x * x - y * y), tol),
"Y_3^2"
);
assert!(
approx(b3[15], SHADER_SH_C3_6 * x * (x * x - 3.0 * y * y), tol),
"Y_3^3"
);
}
#[test]
fn test_sh_eval_degree3_matches_environment_basis() {
let tol = 1e-6;
let dirs = [
[2.0_f32, 1.0, 3.0],
[-1.0_f32, 2.0, -0.5],
[0.3_f32, -0.7, 0.6],
[-0.8_f32, -0.4, -1.3],
];
for dir in dirs {
let unit = normalize(dir).expect("direction is non-zero");
let [x, y, z] = unit;
let mine = sh_eval_degree3(x, y, z);
let theirs = crate::environment::sh_basis_up_to_l3(unit);
for (k, (a, b)) in mine.iter().zip(theirs.iter()).enumerate() {
assert!(
approx(*a, *b, tol),
"basis {k} disagrees for dir {dir:?}: \
spherical_harmonics={a}, environment={b}"
);
}
}
}
#[test]
fn test_sh_eval_matches_environment_basis_all_degrees() {
let tol = 1e-6;
let dir = [2.0_f32, 1.0, 3.0];
let unit = normalize(dir).expect("direction is non-zero");
let reference = crate::environment::sh_basis_up_to_l3(unit);
for degree in 0..=3_usize {
let basis = sh_eval(dir, degree).expect("degree <= 3 and dir non-zero");
assert_eq!(basis.len(), sh_num_coeffs(degree));
for (k, value) in basis.iter().enumerate() {
assert!(
approx(*value, reference[k], tol),
"degree {degree} basis {k}: sh_eval={value}, environment={}",
reference[k]
);
}
}
}
}