use thiserror::Error;
#[derive(Debug, Error)]
pub enum HdrBloomError {
#[error("Invalid bloom configuration: {0}")]
InvalidConfig(String),
#[error("Invalid image: {0}")]
InvalidImage(String),
#[error("Empty image (zero pixels)")]
EmptyImage,
}
#[inline]
fn luminance_bt709(r: f32, g: f32, b: f32) -> f32 {
0.2126 * r + 0.7152 * g + 0.0722 * b
}
fn validate_rgb(image: &[f32], width: usize, height: usize) -> Result<(), HdrBloomError> {
if width == 0 || height == 0 {
return Err(HdrBloomError::EmptyImage);
}
let expected = width * height * 3;
if image.len() != expected {
return Err(HdrBloomError::InvalidImage(format!(
"expected {} values for {}×{}×3, got {}",
expected,
width,
height,
image.len()
)));
}
Ok(())
}
pub fn extract_bright(
image: &[f32],
width: usize,
height: usize,
threshold: f32,
) -> Result<Vec<f32>, HdrBloomError> {
validate_rgb(image, width, height)?;
let n_pixels = width * height;
let mut out = vec![0.0_f32; n_pixels * 3];
for i in 0..n_pixels {
let base = i * 3;
let (r, g, b) = (image[base], image[base + 1], image[base + 2]);
let lum = luminance_bt709(r, g, b);
if lum > threshold {
out[base] = r;
out[base + 1] = g;
out[base + 2] = b;
}
}
Ok(out)
}
pub fn soft_knee_weight(luminance: f32, threshold: f32, knee: f32) -> f32 {
if knee <= 0.0 {
return if luminance > threshold { 1.0 } else { 0.0 };
}
let lo = threshold - knee;
let hi = threshold + knee;
if luminance <= lo {
return 0.0;
}
if luminance >= hi {
return 1.0;
}
let t = (luminance - lo) / (2.0 * knee);
t * t * (3.0 - 2.0 * t)
}
pub fn gaussian_kernel_1d(radius: usize, sigma: f32) -> Vec<f32> {
let len = 2 * radius + 1;
let center = radius as f32;
let mut kernel: Vec<f32> = (0..len)
.map(|i| {
let x = i as f32 - center;
if sigma <= f32::EPSILON {
if i == radius {
1.0
} else {
0.0
}
} else {
(-(x * x) / (2.0 * sigma * sigma)).exp()
}
})
.collect();
let sum: f32 = kernel.iter().sum();
if sum > f32::EPSILON {
kernel.iter_mut().for_each(|v| *v /= sum);
} else {
let mid = radius;
kernel = vec![0.0; len];
kernel[mid] = 1.0;
}
kernel
}
pub fn gaussian_blur_rgb(
image: &[f32],
width: usize,
height: usize,
radius: usize,
sigma: f32,
) -> Result<Vec<f32>, HdrBloomError> {
validate_rgb(image, width, height)?;
let kernel = gaussian_kernel_1d(radius, sigma);
let mut h_pass = vec![0.0_f32; width * height * 3];
for y in 0..height {
for x in 0..width {
let mut acc = [0.0_f32; 3];
for (k, &w) in kernel.iter().enumerate() {
let sx = (x as isize + k as isize - radius as isize).clamp(0, width as isize - 1)
as usize;
let base = (y * width + sx) * 3;
acc[0] += image[base] * w;
acc[1] += image[base + 1] * w;
acc[2] += image[base + 2] * w;
}
let out_base = (y * width + x) * 3;
h_pass[out_base] = acc[0];
h_pass[out_base + 1] = acc[1];
h_pass[out_base + 2] = acc[2];
}
}
let mut v_pass = vec![0.0_f32; width * height * 3];
for y in 0..height {
for x in 0..width {
let mut acc = [0.0_f32; 3];
for (k, &w) in kernel.iter().enumerate() {
let sy = (y as isize + k as isize - radius as isize).clamp(0, height as isize - 1)
as usize;
let base = (sy * width + x) * 3;
acc[0] += h_pass[base] * w;
acc[1] += h_pass[base + 1] * w;
acc[2] += h_pass[base + 2] * w;
}
let out_base = (y * width + x) * 3;
v_pass[out_base] = acc[0];
v_pass[out_base + 1] = acc[1];
v_pass[out_base + 2] = acc[2];
}
}
Ok(v_pass)
}
pub fn downsample_2x(image: &[f32], width: usize, height: usize) -> (Vec<f32>, usize, usize) {
if width == 0 || height == 0 {
return (Vec::new(), 0, 0);
}
let ow = (width / 2).max(1);
let oh = (height / 2).max(1);
let mut out = vec![0.0_f32; ow * oh * 3];
for oy in 0..oh {
for ox in 0..ow {
let sx0 = (ox * 2).min(width.saturating_sub(1));
let sx1 = (ox * 2 + 1).min(width.saturating_sub(1));
let sy0 = (oy * 2).min(height.saturating_sub(1));
let sy1 = (oy * 2 + 1).min(height.saturating_sub(1));
let b00 = (sy0 * width + sx0) * 3;
let b01 = (sy0 * width + sx1) * 3;
let b10 = (sy1 * width + sx0) * 3;
let b11 = (sy1 * width + sx1) * 3;
let out_base = (oy * ow + ox) * 3;
for c in 0..3 {
out[out_base + c] =
(image[b00 + c] + image[b01 + c] + image[b10 + c] + image[b11 + c]) * 0.25;
}
}
}
(out, ow, oh)
}
pub fn upsample_2x(image: &[f32], width: usize, height: usize) -> Vec<f32> {
let ow = width * 2;
let oh = height * 2;
let mut out = vec![0.0_f32; ow * oh * 3];
let sample = |sx: f32, sy: f32, c: usize| -> f32 {
let x0 = (sx.floor() as isize).clamp(0, width as isize - 1) as usize;
let x1 = (sx.ceil() as isize).clamp(0, width as isize - 1) as usize;
let y0 = (sy.floor() as isize).clamp(0, height as isize - 1) as usize;
let y1 = (sy.ceil() as isize).clamp(0, height as isize - 1) as usize;
let tx = sx - sx.floor();
let ty = sy - sy.floor();
let v00 = image[(y0 * width + x0) * 3 + c];
let v01 = image[(y0 * width + x1) * 3 + c];
let v10 = image[(y1 * width + x0) * 3 + c];
let v11 = image[(y1 * width + x1) * 3 + c];
(v00 * (1.0 - tx) + v01 * tx) * (1.0 - ty) + (v10 * (1.0 - tx) + v11 * tx) * ty
};
for oy in 0..oh {
for ox in 0..ow {
let sx = ((ox as f32 + 0.5) * 0.5 - 0.5).max(0.0);
let sy = ((oy as f32 + 0.5) * 0.5 - 0.5).max(0.0);
let out_base = (oy * ow + ox) * 3;
for c in 0..3 {
out[out_base + c] = sample(sx, sy, c);
}
}
}
out
}
pub fn build_mip_pyramid(
image: &[f32],
width: usize,
height: usize,
num_levels: usize,
) -> Result<Vec<(Vec<f32>, usize, usize)>, HdrBloomError> {
if num_levels == 0 {
return Err(HdrBloomError::InvalidConfig(
"num_levels must be at least 1".to_string(),
));
}
validate_rgb(image, width, height)?;
let mut levels: Vec<(Vec<f32>, usize, usize)> = Vec::with_capacity(num_levels);
levels.push((image.to_vec(), width, height));
for _ in 1..num_levels {
let blurred_level = match levels.last().map(|l| (&l.0, l.1, l.2)) {
Some((prev_pixels, prev_w, prev_h)) => {
let blurred = gaussian_blur_rgb(prev_pixels, prev_w, prev_h, 1, 1.0)?;
(blurred, prev_w, prev_h)
}
None => break,
};
let (blurred, prev_w, prev_h) = blurred_level;
let (down_pixels, down_w, down_h) = downsample_2x(&blurred, prev_w, prev_h);
levels.push((down_pixels, down_w, down_h));
if down_w == 1 && down_h == 1 {
break;
}
}
Ok(levels)
}
#[derive(Debug, Clone)]
pub struct HdrBloomConfig {
pub threshold: f32,
pub knee: f32,
pub num_levels: usize,
pub blur_radius: usize,
pub blur_sigma: f32,
pub intensity: f32,
pub level_weights: Vec<f32>,
}
impl Default for HdrBloomConfig {
fn default() -> Self {
Self {
threshold: 1.0,
knee: 0.1,
num_levels: 5,
blur_radius: 3,
blur_sigma: 1.5,
intensity: 0.5,
level_weights: vec![],
}
}
}
impl HdrBloomConfig {
pub fn validate(&self) -> Result<(), HdrBloomError> {
if self.threshold < 0.0 {
return Err(HdrBloomError::InvalidConfig(
"threshold must be >= 0".to_string(),
));
}
if self.knee < 0.0 {
return Err(HdrBloomError::InvalidConfig(
"knee must be >= 0".to_string(),
));
}
if self.num_levels == 0 {
return Err(HdrBloomError::InvalidConfig(
"num_levels must be >= 1".to_string(),
));
}
if self.blur_radius == 0 {
return Err(HdrBloomError::InvalidConfig(
"blur_radius must be >= 1".to_string(),
));
}
if self.blur_sigma <= 0.0 {
return Err(HdrBloomError::InvalidConfig(
"blur_sigma must be > 0".to_string(),
));
}
if self.intensity < 0.0 {
return Err(HdrBloomError::InvalidConfig(
"intensity must be >= 0".to_string(),
));
}
if !self.level_weights.is_empty() && self.level_weights.len() != self.num_levels {
return Err(HdrBloomError::InvalidConfig(format!(
"level_weights length {} must equal num_levels {}",
self.level_weights.len(),
self.num_levels
)));
}
Ok(())
}
pub fn level_weight(&self, i: usize) -> f32 {
if self.level_weights.is_empty() {
return 1.0 / self.num_levels as f32;
}
let sum: f32 = self.level_weights.iter().sum();
if sum <= f32::EPSILON {
return 1.0 / self.num_levels as f32;
}
let w = self.level_weights.get(i).copied().unwrap_or(0.0);
w / sum
}
pub fn wide() -> Self {
Self {
num_levels: 7,
blur_radius: 5,
blur_sigma: 2.5,
intensity: 0.7,
..Self::default()
}
}
pub fn tight() -> Self {
Self {
num_levels: 3,
blur_radius: 2,
blur_sigma: 1.0,
intensity: 0.3,
..Self::default()
}
}
}
pub fn apply_hdr_bloom(
image: &[f32],
width: usize,
height: usize,
config: &HdrBloomConfig,
) -> Result<Vec<f32>, HdrBloomError> {
config.validate()?;
validate_rgb(image, width, height)?;
let n = width * height;
let mut bright = vec![0.0_f32; n * 3];
for i in 0..n {
let base = i * 3;
let (r, g, b) = (image[base], image[base + 1], image[base + 2]);
let lum = luminance_bt709(r, g, b);
let weight = soft_knee_weight(lum, config.threshold, config.knee);
if weight > 0.0 {
bright[base] = r * weight;
bright[base + 1] = g * weight;
bright[base + 2] = b * weight;
}
}
let pyramid = build_mip_pyramid(&bright, width, height, config.num_levels)?;
let mut bloom_acc = vec![0.0_f32; n * 3];
for (level_idx, (level_pixels, level_w, level_h)) in pyramid.iter().enumerate() {
let level_weight = config.level_weight(level_idx);
if level_weight <= 0.0 {
continue;
}
let blurred = gaussian_blur_rgb(
level_pixels,
*level_w,
*level_h,
config.blur_radius,
config.blur_sigma,
)?;
let up = crate::bloom_simple::bloom_upsample(&blurred, *level_w, *level_h, width, height);
for i in 0..n * 3 {
bloom_acc[i] += up[i] * level_weight;
}
}
let mut out = vec![0.0_f32; n * 3];
for i in 0..n * 3 {
out[i] = image[i] + bloom_acc[i] * config.intensity;
}
Ok(out)
}
#[inline]
fn aces_filmic(x: f32) -> f32 {
let x = x.max(0.0);
((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)).clamp(0.0, 1.0)
}
#[inline]
fn srgb_gamma(x: f32) -> f32 {
x.max(0.0).powf(1.0 / 2.2)
}
pub fn apply_hdr_bloom_and_tonemap(
image: &[f32],
width: usize,
height: usize,
config: &HdrBloomConfig,
) -> Result<Vec<f32>, HdrBloomError> {
let bloomed = apply_hdr_bloom(image, width, height, config)?;
let out: Vec<f32> = bloomed
.iter()
.map(|&v| srgb_gamma(aces_filmic(v)))
.collect();
Ok(out)
}
pub fn apply_hdr_bloom_rgba(
image: &[f32],
width: usize,
height: usize,
config: &HdrBloomConfig,
) -> Result<Vec<f32>, HdrBloomError> {
if width == 0 || height == 0 {
return Err(HdrBloomError::EmptyImage);
}
let n_pixels = width * height;
let expected = n_pixels * 4;
if image.len() != expected {
return Err(HdrBloomError::InvalidImage(format!(
"expected {} values for {}×{}×4, got {}",
expected,
width,
height,
image.len()
)));
}
config.validate()?;
let mut rgb = vec![0.0_f32; n_pixels * 3];
let mut alpha = vec![0.0_f32; n_pixels];
for (i, alpha_val) in alpha.iter_mut().enumerate().take(n_pixels) {
let src = i * 4;
let dst = i * 3;
rgb[dst] = image[src];
rgb[dst + 1] = image[src + 1];
rgb[dst + 2] = image[src + 2];
*alpha_val = image[src + 3];
}
let bloomed_rgb = apply_hdr_bloom(&rgb, width, height, config)?;
let mut out = vec![0.0_f32; n_pixels * 4];
for (i, &alpha_val) in alpha.iter().enumerate().take(n_pixels) {
let src = i * 3;
let dst = i * 4;
out[dst] = bloomed_rgb[src];
out[dst + 1] = bloomed_rgb[src + 1];
out[dst + 2] = bloomed_rgb[src + 2];
out[dst + 3] = alpha_val;
}
Ok(out)
}
#[derive(Debug, Clone)]
pub struct HdrBloomStats {
pub bright_fraction: f32,
pub mean_bloom_luminance: f32,
pub max_bloom_luminance: f32,
pub bloom_to_original_ratio: f32,
}
pub fn compute_hdr_bloom_stats(
original: &[f32],
bloomed: &[f32],
width: usize,
height: usize,
threshold: f32,
) -> Result<HdrBloomStats, HdrBloomError> {
validate_rgb(original, width, height)?;
if bloomed.len() != original.len() {
return Err(HdrBloomError::InvalidImage(format!(
"bloomed image length {} does not match original {}",
bloomed.len(),
original.len()
)));
}
let n_pixels = width * height;
let mut bright_count = 0usize;
let mut sum_orig_lum = 0.0_f32;
let mut sum_bloom_lum = 0.0_f32;
let mut max_bloom_lum = 0.0_f32;
for i in 0..n_pixels {
let base = i * 3;
let (or_, og, ob) = (original[base], original[base + 1], original[base + 2]);
let (br, bg, bb) = (bloomed[base], bloomed[base + 1], bloomed[base + 2]);
let orig_lum = luminance_bt709(or_, og, ob);
let bloom_lum = luminance_bt709(br - or_, bg - og, bb - ob);
let bloom_lum = bloom_lum.max(0.0);
if orig_lum > threshold {
bright_count += 1;
}
sum_orig_lum += orig_lum;
sum_bloom_lum += bloom_lum;
if bloom_lum > max_bloom_lum {
max_bloom_lum = bloom_lum;
}
}
let n = n_pixels as f32;
let mean_orig_lum = sum_orig_lum / n;
let mean_bloom_lum = sum_bloom_lum / n;
Ok(HdrBloomStats {
bright_fraction: bright_count as f32 / n,
mean_bloom_luminance: mean_bloom_lum,
max_bloom_luminance: max_bloom_lum,
bloom_to_original_ratio: mean_bloom_lum / (mean_orig_lum + 1e-8),
})
}
pub use crate::bloom_simple::{
apply_bloom, bloom_accumulate_mip_chain, bloom_build_mip_chain, bloom_composite,
bloom_convolve_horizontal, bloom_convolve_vertical, bloom_coverage, bloom_downsample,
bloom_extract_bright, bloom_gaussian_blur, bloom_luminance_map, bloom_make_kernel,
bloom_upsample, format_bloom_config, BloomConfig, BloomError,
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gaussian_kernel_sums_to_one() {
let k = gaussian_kernel_1d(5, 2.0);
let sum: f32 = k.iter().sum();
assert!(
(sum - 1.0).abs() < 1e-5,
"kernel sum should be 1.0, got {sum}"
);
}
#[test]
fn test_gaussian_kernel_radius_zero() {
let k = gaussian_kernel_1d(0, 1.0);
assert_eq!(k.len(), 1);
assert!((k[0] - 1.0).abs() < 1e-6);
}
#[test]
fn test_gaussian_kernel_length() {
let radius = 3;
let k = gaussian_kernel_1d(radius, 1.5);
assert_eq!(k.len(), 2 * radius + 1);
}
#[test]
fn test_gaussian_kernel_symmetric() {
let k = gaussian_kernel_1d(4, 2.0);
let n = k.len();
for i in 0..n / 2 {
assert!(
(k[i] - k[n - 1 - i]).abs() < 1e-6,
"kernel not symmetric at {i}"
);
}
}
#[test]
fn test_soft_knee_below_threshold_returns_zero() {
let w = soft_knee_weight(0.5, 1.0, 0.2);
assert_eq!(w, 0.0);
}
#[test]
fn test_soft_knee_above_threshold_returns_one() {
let w = soft_knee_weight(2.0, 1.0, 0.2);
assert_eq!(w, 1.0);
}
#[test]
fn test_soft_knee_at_midpoint_approx_half() {
let w = soft_knee_weight(1.0, 1.0, 0.2);
assert!((w - 0.5).abs() < 1e-5, "expected ~0.5 at midpoint, got {w}");
}
#[test]
fn test_soft_knee_hard_threshold_fallback() {
assert_eq!(soft_knee_weight(0.9, 1.0, 0.0), 0.0);
assert_eq!(soft_knee_weight(1.1, 1.0, 0.0), 1.0);
}
#[test]
fn test_extract_bright_all_dark() {
let img = vec![0.3_f32; 4 * 4 * 3];
let out = extract_bright(&img, 4, 4, 1.0).unwrap();
assert!(out.iter().all(|&v| v == 0.0));
}
#[test]
fn test_extract_bright_all_bright() {
let img: Vec<f32> = (0..2 * 2 * 3).map(|_| 2.0).collect();
let out = extract_bright(&img, 2, 2, 1.0).unwrap();
assert_eq!(out, img);
}
#[test]
fn test_extract_bright_mixed() {
let mut img = vec![0.0_f32; 2 * 3];
img[0] = 0.5;
img[1] = 0.0;
img[2] = 0.0;
img[3] = 6.0;
img[4] = 0.5;
img[5] = 0.0;
let out = extract_bright(&img, 2, 1, 1.0).unwrap();
assert_eq!(out[0], 0.0);
assert_eq!(out[1], 0.0);
assert_eq!(out[2], 0.0);
assert_eq!(out[3], img[3]);
assert_eq!(out[4], img[4]);
assert_eq!(out[5], img[5]);
}
#[test]
fn test_extract_bright_error_on_mismatch() {
let img = vec![0.5_f32; 10]; assert!(extract_bright(&img, 2, 2, 1.0).is_err());
}
#[test]
fn test_gaussian_blur_uniform_stays_uniform() {
let v = 0.5_f32;
let img = vec![v; 8 * 8 * 3];
let out = gaussian_blur_rgb(&img, 8, 8, 2, 1.0).unwrap();
for &x in &out {
assert!(
(x - v).abs() < 1e-4,
"uniform image should stay uniform after blur, got {x}"
);
}
}
#[test]
fn test_gaussian_blur_identity_with_tiny_sigma() {
let img: Vec<f32> = (0..3 * 3 * 3).map(|i| (i as f32) * 0.1).collect();
let out = gaussian_blur_rgb(&img, 3, 3, 0, 0.00001).unwrap();
for (a, b) in img.iter().zip(out.iter()) {
assert!(
(a - b).abs() < 1e-3,
"identity blur should leave image unchanged"
);
}
}
#[test]
fn test_downsample_2x_4x4_to_2x2() {
let img = vec![1.0_f32; 4 * 4 * 3];
let (out, ow, oh) = downsample_2x(&img, 4, 4);
assert_eq!(ow, 2);
assert_eq!(oh, 2);
assert_eq!(out.len(), 2 * 2 * 3);
}
#[test]
fn test_downsample_2x_uniform_stays_uniform() {
let v = 0.7_f32;
let img = vec![v; 6 * 6 * 3];
let (out, _, _) = downsample_2x(&img, 6, 6);
for &x in &out {
assert!(
(x - v).abs() < 1e-5,
"uniform downsample should remain uniform"
);
}
}
#[test]
fn test_downsample_2x_zero_width_no_panic() {
let (out, ow, oh) = downsample_2x(&[], 0, 4);
assert_eq!((out.len(), ow, oh), (0, 0, 0));
}
#[test]
fn test_downsample_2x_zero_height_no_panic() {
let (out, ow, oh) = downsample_2x(&[], 4, 0);
assert_eq!((out.len(), ow, oh), (0, 0, 0));
}
#[test]
fn test_downsample_2x_zero_width_and_height_no_panic() {
let (out, ow, oh) = downsample_2x(&[], 0, 0);
assert_eq!((out.len(), ow, oh), (0, 0, 0));
}
#[test]
fn test_upsample_2x_2x2_to_4x4() {
let img = vec![0.5_f32; 2 * 2 * 3];
let out = upsample_2x(&img, 2, 2);
assert_eq!(out.len(), 4 * 4 * 3);
}
#[test]
fn test_upsample_2x_single_pixel_expands() {
let img = vec![0.8_f32, 0.4_f32, 0.2_f32];
let out = upsample_2x(&img, 1, 1);
assert_eq!(out.len(), 2 * 2 * 3);
for i in 0..4 {
let b = i * 3;
assert!((out[b] - 0.8).abs() < 1e-6);
assert!((out[b + 1] - 0.4).abs() < 1e-6);
assert!((out[b + 2] - 0.2).abs() < 1e-6);
}
}
#[test]
fn test_upsample_2x_pixel_center_aligned() {
let width = 4;
let height = 1;
let mut img = vec![0.0_f32; width * height * 3];
for x in 0..width {
img[x * 3] = x as f32;
}
let out = upsample_2x(&img, width, height);
assert_eq!(out.len(), 8 * 2 * 3);
let expected_r = [0.0_f32, 0.25, 0.75, 1.25];
let corner_aligned_r = [0.0_f32, 0.5, 1.0, 1.5];
for (ox, &exp) in expected_r.iter().enumerate() {
let r = out[ox * 3];
assert!(
(r - exp).abs() < 1e-4,
"pixel-centre-aligned upsample at ox={ox}: expected r={exp}, got {r} \
(corner-aligned sampling would give {})",
corner_aligned_r[ox]
);
}
}
#[test]
fn test_build_mip_pyramid_level_count() {
let img = vec![0.5_f32; 16 * 16 * 3];
let levels = build_mip_pyramid(&img, 16, 16, 4).unwrap();
assert!(levels.len() <= 4);
assert!(!levels.is_empty());
}
#[test]
fn test_build_mip_pyramid_level0_matches_input() {
let img: Vec<f32> = (0..8 * 8 * 3).map(|i| (i as f32) * 0.01).collect();
let levels = build_mip_pyramid(&img, 8, 8, 3).unwrap();
let (ref pixels, w, h) = levels[0];
assert_eq!(w, 8);
assert_eq!(h, 8);
assert_eq!(pixels, &img);
}
#[test]
fn test_build_mip_pyramid_zero_levels_error() {
let img = vec![0.5_f32; 4 * 4 * 3];
assert!(build_mip_pyramid(&img, 4, 4, 0).is_err());
}
#[test]
fn test_build_mip_pyramid_level1_reflects_blur() {
let mut img = vec![0.0_f32; 8 * 8 * 3];
let center = (4 * 8 + 4) * 3;
img[center] = 1.0;
img[center + 1] = 1.0;
img[center + 2] = 1.0;
let levels = build_mip_pyramid(&img, 8, 8, 2).expect("pyramid build failed");
assert_eq!(levels.len(), 2);
let (ref level1_pixels, w1, h1) = levels[1];
assert_eq!((w1, h1), (4, 4));
let (unblurred_down, _, _) = downsample_2x(&img, 8, 8);
assert_ne!(
level1_pixels, &unblurred_down,
"level 1 should reflect the blur pass, not a plain downsample of \
the unblurred image"
);
}
#[test]
fn test_bloom_config_validate_valid() {
assert!(HdrBloomConfig::default().validate().is_ok());
}
#[test]
fn test_bloom_config_validate_negative_threshold() {
let cfg = HdrBloomConfig {
threshold: -0.1,
..HdrBloomConfig::default()
};
assert!(cfg.validate().is_err());
}
#[test]
fn test_bloom_config_validate_zero_num_levels() {
let cfg = HdrBloomConfig {
num_levels: 0,
..HdrBloomConfig::default()
};
assert!(cfg.validate().is_err());
}
#[test]
fn test_bloom_config_validate_mismatched_weights() {
let cfg = HdrBloomConfig {
num_levels: 3,
level_weights: vec![1.0, 1.0], ..HdrBloomConfig::default()
};
assert!(cfg.validate().is_err());
}
#[test]
fn test_bloom_config_level_weight_uniform() {
let cfg = HdrBloomConfig::default(); let expected = 1.0 / cfg.num_levels as f32;
for i in 0..cfg.num_levels {
assert!((cfg.level_weight(i) - expected).abs() < 1e-6);
}
}
#[test]
fn test_bloom_config_level_weight_custom_normalised() {
let cfg = HdrBloomConfig {
num_levels: 3,
level_weights: vec![1.0, 2.0, 3.0],
..HdrBloomConfig::default()
};
let sum: f32 = (0..3).map(|i| cfg.level_weight(i)).sum();
assert!(
(sum - 1.0).abs() < 1e-5,
"weights should sum to 1, got {sum}"
);
}
#[test]
fn test_apply_bloom_dark_image_unchanged() {
let img = vec![0.3_f32; 8 * 8 * 3];
let cfg = HdrBloomConfig {
threshold: 1.0,
knee: 0.0,
intensity: 1.0,
num_levels: 3,
blur_radius: 1,
blur_sigma: 1.0,
level_weights: vec![],
};
let out = apply_hdr_bloom(&img, 8, 8, &cfg).unwrap();
for (a, b) in img.iter().zip(out.iter()) {
assert!(
(a - b).abs() < 1e-5,
"dark image should not be changed by bloom"
);
}
}
#[test]
fn test_apply_bloom_adds_positive_values_for_bright_pixels() {
let mut img = vec![0.0_f32; 8 * 8 * 3];
let cx = 4;
let cy = 4;
let base = (cy * 8 + cx) * 3;
img[base] = 10.0;
img[base + 1] = 10.0;
img[base + 2] = 10.0;
let cfg = HdrBloomConfig {
threshold: 1.0,
knee: 0.1,
intensity: 1.0,
num_levels: 3,
blur_radius: 2,
blur_sigma: 1.5,
level_weights: vec![],
};
let out = apply_hdr_bloom(&img, 8, 8, &cfg).unwrap();
let sum_in: f32 = img.iter().sum();
let sum_out: f32 = out.iter().sum();
assert!(sum_out >= sum_in, "bloom should add light, not remove it");
}
#[test]
fn test_apply_hdr_bloom_non_power_of_two_stays_centered() {
let width = 37;
let height = 23;
let n = width * height;
let mut img = vec![0.0_f32; n * 3];
let cx = 20;
let cy = 12;
let base = (cy * width + cx) * 3;
img[base] = 4.0;
img[base + 1] = 4.0;
img[base + 2] = 4.0;
let cfg = HdrBloomConfig {
threshold: 1.0,
knee: 0.1,
intensity: 1.0,
num_levels: 4,
blur_radius: 2,
blur_sigma: 1.5,
level_weights: vec![],
};
let out = apply_hdr_bloom(&img, width, height, &cfg).expect("bloom failed");
assert_eq!(out.len(), n * 3);
for &v in &out {
assert!(v.is_finite(), "bloom output must stay finite, got {v}");
}
let mut best_idx = 0usize;
let mut best_val = f32::MIN;
for i in 0..n {
let b = i * 3;
let contribution =
(out[b] - img[b]) + (out[b + 1] - img[b + 1]) + (out[b + 2] - img[b + 2]);
if contribution > best_val {
best_val = contribution;
best_idx = i;
}
}
let peak_x = best_idx % width;
let peak_y = best_idx / width;
let dx = (peak_x as isize - cx as isize).abs();
let dy = (peak_y as isize - cy as isize).abs();
assert!(
dx <= 2 && dy <= 2,
"bloom peak should stay near the source pixel ({cx},{cy}); got \
({peak_x},{peak_y}) — a row-skewed buffer would displace this \
far more than a couple of pixels"
);
}
#[test]
fn test_bloom_and_tonemap_returns_values_in_01() {
let img: Vec<f32> = (0..4 * 4 * 3).map(|i| (i as f32) * 0.1 + 0.5).collect();
let cfg = HdrBloomConfig::tight();
let out = apply_hdr_bloom_and_tonemap(&img, 4, 4, &cfg).unwrap();
for &v in &out {
assert!(
(0.0..=1.0).contains(&v),
"tone-mapped output must be in [0,1], got {v}"
);
}
}
#[test]
fn test_bloom_rgba_alpha_passthrough() {
let mut img = vec![0.0_f32; 4 * 4 * 4];
for i in 0..16 {
img[i * 4] = 2.0; img[i * 4 + 1] = 2.0; img[i * 4 + 2] = 2.0; img[i * 4 + 3] = 0.42 * (i as f32 / 16.0); }
let cfg = HdrBloomConfig::default();
let out = apply_hdr_bloom_rgba(&img, 4, 4, &cfg).unwrap();
for i in 0..16 {
let expected_alpha = img[i * 4 + 3];
let actual_alpha = out[i * 4 + 3];
assert!(
(actual_alpha - expected_alpha).abs() < 1e-6,
"alpha[{i}] should be unchanged: expected {expected_alpha}, got {actual_alpha}"
);
}
}
#[test]
fn test_bloom_stats_dark_image_bright_fraction_zero() {
let img = vec![0.3_f32; 4 * 4 * 3];
let cfg = HdrBloomConfig {
threshold: 1.0,
knee: 0.0,
..HdrBloomConfig::default()
};
let bloomed = apply_hdr_bloom(&img, 4, 4, &cfg).unwrap();
let stats = compute_hdr_bloom_stats(&img, &bloomed, 4, 4, 1.0).unwrap();
assert_eq!(
stats.bright_fraction, 0.0,
"no pixels above threshold → bright_fraction must be 0"
);
}
#[test]
fn test_bloom_stats_bright_image_nonzero_fraction() {
let img = vec![2.0_f32; 4 * 4 * 3];
let cfg = HdrBloomConfig {
threshold: 1.0,
..HdrBloomConfig::default()
};
let bloomed = apply_hdr_bloom(&img, 4, 4, &cfg).unwrap();
let stats = compute_hdr_bloom_stats(&img, &bloomed, 4, 4, 1.0).unwrap();
assert_eq!(
stats.bright_fraction, 1.0,
"all pixels above threshold → bright_fraction must be 1"
);
assert!(
stats.mean_bloom_luminance >= 0.0,
"mean bloom luminance should be non-negative"
);
}
}