use thiserror::Error;
fn xorshift64(state: &mut u64) -> u64 {
let mut x = *state;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
*state = x;
x
}
fn xorshift64_f32(state: &mut u64) -> f32 {
(xorshift64(state) >> 11) as f32 / (1u64 << 53) as f32
}
fn safe_seed(seed: u64) -> u64 {
if seed == 0 {
0xDEAD_BEEF_CAFE_1234u64
} else {
seed
}
}
#[derive(Debug, Error)]
pub enum SsaoError {
#[error("SSAO input is empty")]
EmptyInput,
#[error("Invalid normal map: expected {expected} floats (W×H×3), got {got}")]
InvalidNormalMap {
expected: usize,
got: usize,
},
#[error("Size mismatch: depth_len={depth_len} pixels, normal_len={normal_len} pixels")]
SizeMismatch {
depth_len: usize,
normal_len: usize,
},
#[error("Image width and height must both be at least 1")]
ZeroDimension,
#[error("Focal length must be positive")]
ZeroFocalLength,
}
#[derive(Debug, Clone)]
pub struct SsaoConfig {
pub num_samples: usize,
pub radius: f32,
pub bias: f32,
pub power: f32,
pub noise_size: usize,
pub blur: bool,
pub blur_radius: usize,
}
impl Default for SsaoConfig {
fn default() -> Self {
Self {
num_samples: 16,
radius: 0.5,
bias: 0.025,
power: 2.0,
noise_size: 4,
blur: true,
blur_radius: 2,
}
}
}
#[derive(Debug, Clone)]
pub struct SsaoKernel {
pub samples: Vec<[f32; 3]>,
}
impl SsaoKernel {
pub fn generate(num_samples: usize, seed: u64) -> Self {
let mut state = safe_seed(seed);
let mut samples = Vec::with_capacity(num_samples);
for i in 0..num_samples {
let u1 = xorshift64_f32(&mut state);
let u2 = xorshift64_f32(&mut state);
let r = u1.sqrt();
let theta = u2 * 2.0 * core::f32::consts::PI;
let mut sample = [r * theta.cos(), r * theta.sin(), (1.0 - u1).max(0.0).sqrt()];
let t = i as f32 / num_samples.max(1) as f32;
let scale = 0.1 + t * t * 0.9;
let s = xorshift64_f32(&mut state) * scale;
sample[0] *= s;
sample[1] *= s;
sample[2] *= s;
samples.push(sample);
}
Self { samples }
}
fn normalize3(v: [f32; 3]) -> [f32; 3] {
let len2 = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
if len2 < 1e-12 {
return [0.0, 0.0, 0.0];
}
let inv = 1.0 / len2.sqrt();
[v[0] * inv, v[1] * inv, v[2] * inv]
}
}
#[inline]
fn dot3(a: [f32; 3], b: [f32; 3]) -> f32 {
crate::ambient_occlusion::ao_dot(a, b)
}
#[inline]
fn cross3(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
crate::ambient_occlusion::ao_cross(a, b)
}
pub fn generate_noise_texture(size: usize, seed: u64) -> Vec<[f32; 2]> {
let mut state = safe_seed(seed);
let n = size * size;
let mut noise = Vec::with_capacity(n);
let two_pi = 2.0 * core::f32::consts::PI;
for _ in 0..n {
let angle = xorshift64_f32(&mut state) * two_pi;
noise.push([angle.cos(), angle.sin()]);
}
noise
}
pub fn compute_ssao(
depth_map: &[f32],
normal_map: &[f32],
kernel: &SsaoKernel,
config: &SsaoConfig,
focal_length: f32,
image_width: usize,
image_height: usize,
) -> Result<Vec<f32>, SsaoError> {
if image_width == 0 || image_height == 0 {
return Err(SsaoError::ZeroDimension);
}
if focal_length <= 0.0 {
return Err(SsaoError::ZeroFocalLength);
}
if depth_map.is_empty() {
return Err(SsaoError::EmptyInput);
}
let num_pixels = image_width * image_height;
if depth_map.len() != num_pixels {
return Err(SsaoError::SizeMismatch {
depth_len: depth_map.len(),
normal_len: num_pixels,
});
}
let expected_normal_len = num_pixels * 3;
if normal_map.len() != expected_normal_len {
return Err(SsaoError::InvalidNormalMap {
expected: expected_normal_len,
got: normal_map.len(),
});
}
let noise_seed = 0xABCD_EF01_2345_6789u64;
let noise = generate_noise_texture(config.noise_size, noise_seed);
let noise_n = config.noise_size.max(1);
let mut ao_map = Vec::with_capacity(num_pixels);
let cx = image_width as f32 * 0.5;
let cy = image_height as f32 * 0.5;
for py in 0..image_height {
for px in 0..image_width {
let pixel_idx = py * image_width + px;
let pixel_depth = depth_map[pixel_idx];
if !pixel_depth.is_finite() || pixel_depth <= 0.0 {
ao_map.push(1.0_f32);
continue;
}
let view_pos = [
(px as f32 - cx) * pixel_depth / focal_length,
(py as f32 - cy) * pixel_depth / focal_length,
pixel_depth,
];
let normal = SsaoKernel::normalize3([
normal_map[pixel_idx * 3],
normal_map[pixel_idx * 3 + 1],
normal_map[pixel_idx * 3 + 2],
]);
let nx = px % noise_n;
let ny = py % noise_n;
let noise_entry = noise[ny * noise_n + nx];
let random_vec = [noise_entry[0], noise_entry[1], 0.0];
let raw_tangent = {
let d = dot3(random_vec, normal);
[
random_vec[0] - normal[0] * d,
random_vec[1] - normal[1] * d,
random_vec[2] - normal[2] * d,
]
};
let tangent = {
if dot3(raw_tangent, raw_tangent) < 1e-6 {
let fallback = if normal[0].abs() < 0.9 {
[1.0, 0.0, 0.0]
} else {
[0.0, 1.0, 0.0]
};
let d = dot3(fallback, normal);
SsaoKernel::normalize3([
fallback[0] - normal[0] * d,
fallback[1] - normal[1] * d,
fallback[2] - normal[2] * d,
])
} else {
SsaoKernel::normalize3(raw_tangent)
}
};
let bitangent = cross3(normal, tangent);
let mut occlusion = 0.0_f32;
let mut valid_samples = 0usize;
for sample in &kernel.samples {
let (sx, sy, sz) = (sample[0], sample[1], sample[2]);
let local_offset = [
tangent[0] * sx + bitangent[0] * sy + normal[0] * sz,
tangent[1] * sx + bitangent[1] * sy + normal[1] * sz,
tangent[2] * sx + bitangent[2] * sy + normal[2] * sz,
];
let view_offset = [local_offset[0], local_offset[1], -local_offset[2]];
let sample_view = [
view_pos[0] + view_offset[0] * config.radius,
view_pos[1] + view_offset[1] * config.radius,
view_pos[2] + view_offset[2] * config.radius,
];
if sample_view[2] <= 0.0 {
continue; }
let sample_x_f = cx + sample_view[0] * focal_length / sample_view[2];
let sample_y_f = cy + sample_view[1] * focal_length / sample_view[2];
if sample_x_f < 0.0
|| sample_y_f < 0.0
|| sample_x_f >= (image_width as f32 - 1.0)
|| sample_y_f >= (image_height as f32 - 1.0)
{
continue;
}
let sx_i = sample_x_f as usize;
let sy_i = sample_y_f as usize;
let sampled_depth = depth_map[sy_i * image_width + sx_i];
if !sampled_depth.is_finite() || sampled_depth <= 0.0 {
continue;
}
valid_samples += 1;
let depth_diff = (sampled_depth - sample_view[2]).abs();
if depth_diff > config.radius {
continue;
}
let range_weight = 1.0 - depth_diff / config.radius;
if sampled_depth < sample_view[2] - config.bias {
occlusion += range_weight;
}
}
let ao = if valid_samples == 0 {
1.0_f32
} else {
let norm_occ = (occlusion / valid_samples as f32).min(1.0);
(1.0 - norm_occ).powf(config.power)
};
ao_map.push(ao.clamp(0.0, 1.0));
}
}
Ok(ao_map)
}
pub fn blur_ssao(
ao_map: &[f32],
image_width: usize,
image_height: usize,
blur_radius: usize,
) -> Vec<f32> {
if ao_map.is_empty() || image_width == 0 || image_height == 0 {
return ao_map.to_vec();
}
let num_pixels = image_width * image_height;
if ao_map.len() != num_pixels {
return ao_map.to_vec();
}
let mut temp = vec![0.0_f32; num_pixels];
let r = blur_radius as isize;
let diam = (2 * blur_radius + 1) as f32;
for py in 0..image_height {
for px in 0..image_width {
let mut sum = 0.0_f32;
for dx in -r..=r {
let sx = (px as isize + dx).clamp(0, image_width as isize - 1) as usize;
sum += ao_map[py * image_width + sx];
}
temp[py * image_width + px] = sum / diam;
}
}
let mut out = vec![0.0_f32; num_pixels];
for py in 0..image_height {
for px in 0..image_width {
let mut sum = 0.0_f32;
for dy in -r..=r {
let sy = (py as isize + dy).clamp(0, image_height as isize - 1) as usize;
sum += temp[sy * image_width + px];
}
out[py * image_width + px] = sum / diam;
}
}
out
}
pub fn apply_ao_to_image(
image: &[f32],
ao_map: &[f32],
image_width: usize,
image_height: usize,
channels: usize,
ao_strength: f32,
) -> Result<Vec<f32>, SsaoError> {
if image_width == 0 || image_height == 0 {
return Err(SsaoError::ZeroDimension);
}
if image.is_empty() {
return Err(SsaoError::EmptyInput);
}
let num_pixels = image_width * image_height;
if ao_map.len() != num_pixels {
return Err(SsaoError::SizeMismatch {
depth_len: ao_map.len(),
normal_len: num_pixels,
});
}
let strength = ao_strength.clamp(0.0, 1.0);
let mut out = Vec::with_capacity(image.len());
for (pixel_idx, chunk) in image.chunks(channels).enumerate() {
let ao = if pixel_idx < ao_map.len() {
ao_map[pixel_idx]
} else {
1.0
};
let scale = 1.0 + strength * (ao - 1.0);
for &v in chunk {
out.push((v * scale).clamp(0.0, 1.0));
}
}
Ok(out)
}
#[derive(Debug, Clone)]
pub struct SsaoStats {
pub mean_ao: f32,
pub min_ao: f32,
pub max_ao: f32,
pub occluded_fraction: f32,
}
impl SsaoStats {
pub fn compute(ao_map: &[f32]) -> Self {
if ao_map.is_empty() {
return Self {
mean_ao: 1.0,
min_ao: 1.0,
max_ao: 1.0,
occluded_fraction: 0.0,
};
}
let n = ao_map.len();
let mut sum = 0.0_f32;
let mut min_ao = f32::MAX;
let mut max_ao = f32::MIN;
let mut occluded_count = 0usize;
for &ao in ao_map {
sum += ao;
if ao < min_ao {
min_ao = ao;
}
if ao > max_ao {
max_ao = ao;
}
if ao < 0.5 {
occluded_count += 1;
}
}
Self {
mean_ao: sum / n as f32,
min_ao,
max_ao,
occluded_fraction: occluded_count as f32 / n as f32,
}
}
pub fn format_summary(&self) -> String {
format!(
"SSAO: mean={:.3} min={:.3} max={:.3} occluded={:.1}%",
self.mean_ao,
self.min_ao,
self.max_ao,
self.occluded_fraction * 100.0,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
(a - b).abs() < eps
}
#[test]
fn test_kernel_generate_count() {
let kernel = SsaoKernel::generate(16, 42);
assert_eq!(kernel.samples.len(), 16);
}
#[test]
fn test_kernel_generate_hemisphere_z_positive() {
let kernel = SsaoKernel::generate(64, 123_456);
for s in &kernel.samples {
assert!(
s[2] >= 0.0,
"Sample z must be non-negative (hemisphere), got {:?}",
s
);
}
}
#[test]
fn test_kernel_normalize3_unit_vector() {
let v = SsaoKernel::normalize3([3.0, 4.0, 0.0]);
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
assert!(approx_eq(len, 1.0, 1e-5), "Normalised length = {len}");
}
#[test]
fn test_kernel_normalize3_zero_vector() {
let v = SsaoKernel::normalize3([0.0, 0.0, 0.0]);
assert_eq!(v, [0.0, 0.0, 0.0]);
}
#[test]
fn test_noise_texture_size() {
let noise = generate_noise_texture(4, 99);
assert_eq!(noise.len(), 16);
let noise2 = generate_noise_texture(8, 99);
assert_eq!(noise2.len(), 64);
}
#[test]
fn test_noise_texture_unit_magnitude() {
let noise = generate_noise_texture(4, 7);
for entry in &noise {
let mag2 = entry[0] * entry[0] + entry[1] * entry[1];
assert!(
approx_eq(mag2, 1.0, 1e-5),
"cos²+sin² should be 1.0, got {mag2}"
);
}
}
fn flat_depth_normals(w: usize, h: usize, depth: f32) -> (Vec<f32>, Vec<f32>) {
let n = w * h;
let depth_map = vec![depth; n];
let mut normal_map = Vec::with_capacity(n * 3);
for _ in 0..n {
normal_map.push(0.0_f32);
normal_map.push(0.0_f32);
normal_map.push(1.0_f32);
}
(depth_map, normal_map)
}
#[test]
fn test_compute_ssao_open_plane_high_ao() {
let w = 16_usize;
let h = 16_usize;
let (depth_map, normal_map) = flat_depth_normals(w, h, 2.0);
let kernel = SsaoKernel::generate(16, 1);
let config = SsaoConfig::default();
let ao = compute_ssao(&depth_map, &normal_map, &kernel, &config, 500.0, w, h)
.expect("compute_ssao failed");
let mean = ao.iter().sum::<f32>() / ao.len() as f32;
assert!(
mean > 0.8,
"Flat plane should have high mean AO (near 1.0), got {mean:.3}"
);
}
#[test]
fn test_compute_ssao_output_size() {
let w = 8_usize;
let h = 6_usize;
let (depth_map, normal_map) = flat_depth_normals(w, h, 1.5);
let kernel = SsaoKernel::generate(8, 2);
let config = SsaoConfig::default();
let ao = compute_ssao(&depth_map, &normal_map, &kernel, &config, 400.0, w, h)
.expect("compute_ssao failed");
assert_eq!(ao.len(), w * h, "AO map must have W×H elements");
}
#[test]
fn test_compute_ssao_values_in_range() {
let w = 10_usize;
let h = 10_usize;
let (depth_map, normal_map) = flat_depth_normals(w, h, 1.0);
let kernel = SsaoKernel::generate(16, 3);
let config = SsaoConfig::default();
let ao = compute_ssao(&depth_map, &normal_map, &kernel, &config, 300.0, w, h)
.expect("compute_ssao failed");
for &v in &ao {
assert!(
(0.0..=1.0).contains(&v),
"AO value out of [0, 1] range: {v}"
);
}
}
#[test]
fn test_compute_ssao_normal_map_affects_result() {
let w = 16_usize;
let h = 16_usize;
let depth_map = vec![2.0_f32; w * h];
let config = SsaoConfig::default();
let kernel = SsaoKernel::generate(32, 7);
let mut facing_camera = Vec::with_capacity(w * h * 3);
let mut facing_sideways = Vec::with_capacity(w * h * 3);
for _ in 0..(w * h) {
facing_camera.extend_from_slice(&[0.0, 0.0, 1.0]);
facing_sideways.extend_from_slice(&[1.0, 0.0, 0.0]);
}
let ao_camera = compute_ssao(&depth_map, &facing_camera, &kernel, &config, 500.0, w, h)
.expect("compute_ssao failed");
let ao_sideways = compute_ssao(&depth_map, &facing_sideways, &kernel, &config, 500.0, w, h)
.expect("compute_ssao failed");
let differs = ao_camera
.iter()
.zip(ao_sideways.iter())
.any(|(a, b)| (a - b).abs() > 1e-4);
assert!(
differs,
"AO must change when normal_map changes (normal_map was previously ignored entirely)"
);
}
#[test]
fn test_dot3_cross3_basic() {
assert!(approx_eq(dot3([1.0, 0.0, 0.0], [1.0, 0.0, 0.0]), 1.0, 1e-6));
assert!(approx_eq(dot3([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), 0.0, 1e-6));
let c = cross3([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]);
assert!(approx_eq(c[0], 0.0, 1e-6));
assert!(approx_eq(c[1], 0.0, 1e-6));
assert!(approx_eq(c[2], 1.0, 1e-6));
}
#[test]
fn test_dot3_cross3_share_ambient_occlusion_helpers() {
let a = [0.3_f32, -1.7, 2.4];
let b = [-0.9_f32, 0.25, 1.1];
assert_eq!(dot3(a, b), crate::ambient_occlusion::ao_dot(a, b));
assert_eq!(cross3(a, b), crate::ambient_occlusion::ao_cross(a, b));
let ba = cross3(b, a);
let ab = cross3(a, b);
for c in 0..3 {
assert!(approx_eq(ab[c], -ba[c], 1e-6));
}
}
#[test]
fn test_ssao_error_zero_dimension() {
let depth_map = vec![1.0_f32; 0];
let normal_map = vec![0.0_f32; 0];
let kernel = SsaoKernel::generate(4, 1);
let config = SsaoConfig::default();
let result = compute_ssao(&depth_map, &normal_map, &kernel, &config, 400.0, 0, 4);
assert!(
matches!(result, Err(SsaoError::ZeroDimension)),
"Expected ZeroDimension error"
);
}
#[test]
fn test_ssao_error_size_mismatch() {
let depth_map = vec![1.0_f32; 4]; let normal_map = vec![0.0_f32; 4 * 3]; let kernel = SsaoKernel::generate(4, 1);
let config = SsaoConfig::default();
let result = compute_ssao(&depth_map, &normal_map, &kernel, &config, 400.0, 3, 2);
assert!(
matches!(result, Err(SsaoError::SizeMismatch { .. })),
"Expected SizeMismatch error"
);
}
#[test]
fn test_compute_ssao_zero_focal_length_error() {
let (depth_map, normal_map) = flat_depth_normals(4, 4, 1.0);
let kernel = SsaoKernel::generate(4, 1);
let config = SsaoConfig::default();
let result = compute_ssao(&depth_map, &normal_map, &kernel, &config, 0.0, 4, 4);
assert!(matches!(result, Err(SsaoError::ZeroFocalLength)));
}
#[test]
fn test_blur_ssao_output_size() {
let w = 8_usize;
let h = 6_usize;
let ao = vec![0.5_f32; w * h];
let blurred = blur_ssao(&ao, w, h, 2);
assert_eq!(blurred.len(), w * h);
}
#[test]
fn test_blur_ssao_uniform_unchanged() {
let w = 8_usize;
let h = 8_usize;
let ao = vec![0.7_f32; w * h];
let blurred = blur_ssao(&ao, w, h, 3);
for (i, (&a, &b)) in ao.iter().zip(blurred.iter()).enumerate() {
assert!(
approx_eq(a, b, 1e-5),
"pixel {i}: blur changed uniform value from {a} to {b}"
);
}
}
#[test]
fn test_apply_ao_output_size() {
let w = 4_usize;
let h = 4_usize;
let image = vec![0.5_f32; w * h * 3];
let ao = vec![1.0_f32; w * h];
let out = apply_ao_to_image(&image, &ao, w, h, 3, 1.0).expect("apply_ao_to_image failed");
assert_eq!(out.len(), image.len());
}
#[test]
fn test_apply_ao_strength_zero_unchanged() {
let w = 4_usize;
let h = 4_usize;
let image: Vec<f32> = (0..w * h * 3).map(|i| (i % 10) as f32 / 10.0).collect();
let ao = vec![0.0_f32; w * h];
let out = apply_ao_to_image(&image, &ao, w, h, 3, 0.0).expect("apply_ao_to_image failed");
for (i, (&a, &b)) in image.iter().zip(out.iter()).enumerate() {
assert!(
approx_eq(a, b, 1e-5),
"pixel {i}: ao_strength=0 changed value from {a} to {b}"
);
}
}
#[test]
fn test_apply_ao_full_ao_darkens() {
let w = 2_usize;
let h = 2_usize;
let image = vec![1.0_f32; w * h * 3];
let ao = vec![0.0_f32; w * h];
let out = apply_ao_to_image(&image, &ao, w, h, 3, 1.0).expect("apply_ao_to_image failed");
for &v in &out {
assert!(
approx_eq(v, 0.0, 1e-5),
"Expected 0.0 with full AO, got {v}"
);
}
}
#[test]
fn test_ssao_stats_compute() {
let ao = vec![0.0_f32, 0.25, 0.5, 1.0];
let stats = SsaoStats::compute(&ao);
assert!(
approx_eq(stats.mean_ao, 0.4375, 1e-4),
"mean = {}",
stats.mean_ao
);
assert!(approx_eq(stats.min_ao, 0.0, 1e-6), "min = {}", stats.min_ao);
assert!(approx_eq(stats.max_ao, 1.0, 1e-6), "max = {}", stats.max_ao);
assert!(
approx_eq(stats.occluded_fraction, 0.5, 1e-5),
"occluded_fraction = {}",
stats.occluded_fraction
);
}
#[test]
fn test_ssao_stats_empty() {
let stats = SsaoStats::compute(&[]);
assert!(approx_eq(stats.mean_ao, 1.0, 1e-6));
assert!(approx_eq(stats.occluded_fraction, 0.0, 1e-6));
}
#[test]
fn test_ssao_stats_format_summary() {
let ao = vec![0.5_f32; 10];
let stats = SsaoStats::compute(&ao);
let summary = stats.format_summary();
assert!(summary.contains("SSAO:"), "summary: {summary}");
assert!(summary.contains("mean"), "summary: {summary}");
}
#[test]
fn test_config_default() {
let cfg = SsaoConfig::default();
assert_eq!(cfg.num_samples, 16);
assert!(approx_eq(cfg.radius, 0.5, 1e-6));
assert!(approx_eq(cfg.bias, 0.025, 1e-6));
assert!(approx_eq(cfg.power, 2.0, 1e-6));
assert_eq!(cfg.noise_size, 4);
assert!(cfg.blur);
assert_eq!(cfg.blur_radius, 2);
}
}