use thiserror::Error;
#[derive(Debug, Error)]
pub enum DofError {
#[error("Image or depth map is empty")]
EmptyImage,
#[error("Size mismatch: image_len={image_len}, depth_len={depth_len}")]
SizeMismatch {
image_len: usize,
depth_len: usize,
},
#[error("Channel count must be at least 1")]
ZeroChannels,
#[error("Image width and height must both be at least 1")]
ZeroDimension,
}
#[derive(Debug, Clone)]
pub struct DofConfig {
pub focal_distance: f32,
pub focal_range: f32,
pub max_blur_radius: f32,
}
impl Default for DofConfig {
fn default() -> Self {
Self {
focal_distance: 2.0,
focal_range: 0.3,
max_blur_radius: 15.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DofKernelShape {
Circular,
Hexagonal,
Square,
}
#[derive(Debug, Clone)]
pub struct DofStats {
pub mean_coc: f32,
pub max_coc: f32,
pub sharp_pixel_fraction: f32,
pub blurred_pixel_fraction: f32,
}
impl DofStats {
pub fn compute(coc_map: &[f32], threshold: f32) -> Self {
if coc_map.is_empty() {
return Self {
mean_coc: 0.0,
max_coc: 0.0,
sharp_pixel_fraction: 1.0,
blurred_pixel_fraction: 0.0,
};
}
let n = coc_map.len() as f32;
let mut sum = 0.0_f32;
let mut max_coc = 0.0_f32;
let mut sharp_count = 0usize;
for &c in coc_map {
sum += c;
if c > max_coc {
max_coc = c;
}
if c < threshold {
sharp_count += 1;
}
}
let mean_coc = sum / n;
let sharp_pixel_fraction = sharp_count as f32 / n;
let blurred_pixel_fraction = 1.0 - sharp_pixel_fraction;
Self {
mean_coc,
max_coc,
sharp_pixel_fraction,
blurred_pixel_fraction,
}
}
pub fn format_summary(&self) -> String {
format!(
"DoF: mean_coc={:.2}px max_coc={:.2}px sharp={:.1}% blurred={:.1}%",
self.mean_coc,
self.max_coc,
self.sharp_pixel_fraction * 100.0,
self.blurred_pixel_fraction * 100.0,
)
}
}
pub fn compute_coc(
depth_map: &[f32],
config: &DofConfig,
image_width: usize,
image_height: usize,
) -> Result<Vec<f32>, DofError> {
if image_width == 0 || image_height == 0 {
return Err(DofError::ZeroDimension);
}
let expected = image_width * image_height;
if depth_map.is_empty() {
return Err(DofError::EmptyImage);
}
if depth_map.len() != expected {
return Err(DofError::SizeMismatch {
image_len: expected,
depth_len: depth_map.len(),
});
}
let half_range = config.focal_range / 2.0;
let half_range = if half_range <= 0.0 {
f32::EPSILON
} else {
half_range
};
let mut coc_map = Vec::with_capacity(expected);
for &depth in depth_map {
let coc = if !depth.is_finite() || depth == 0.0 {
config.max_blur_radius
} else {
let diff = (depth - config.focal_distance).abs();
let norm = (diff / half_range).min(1.0);
norm * config.max_blur_radius
};
coc_map.push(coc.clamp(0.0, config.max_blur_radius));
}
Ok(coc_map)
}
pub fn generate_dof_kernel(radius: f32, shape: DofKernelShape) -> (Vec<f32>, usize) {
let radius = radius.max(0.0);
let r_ceil = radius.ceil() as isize;
let side = (2 * r_ceil + 1) as usize;
let mut kernel = vec![0.0_f32; side * side];
let sqrt3_over2: f32 = (3.0_f32).sqrt() / 2.0;
for iy in 0..side {
for ix in 0..side {
let dy = iy as f32 - r_ceil as f32;
let dx = ix as f32 - r_ceil as f32;
let inside = match shape {
DofKernelShape::Circular => dx * dx + dy * dy <= radius * radius,
DofKernelShape::Hexagonal => {
let term_a = dx.abs();
let term_b = (dx / 2.0 + dy * sqrt3_over2).abs();
let term_c = (dx / 2.0 - dy * sqrt3_over2).abs();
term_a.max(term_b).max(term_c) <= radius
}
DofKernelShape::Square => dx.abs() <= radius && dy.abs() <= radius,
};
if inside {
kernel[iy * side + ix] = 1.0;
}
}
}
let total: f32 = kernel.iter().sum();
if total > 0.0 {
for v in &mut kernel {
*v /= total;
}
} else {
let centre = r_ceil as usize * side + r_ceil as usize;
if centre < kernel.len() {
kernel[centre] = 1.0;
}
}
(kernel, side)
}
pub fn apply_dof(
image: &[f32],
depth_map: &[f32],
config: &DofConfig,
kernel_shape: DofKernelShape,
image_width: usize,
image_height: usize,
channels: usize,
) -> Result<Vec<f32>, DofError> {
if image_width == 0 || image_height == 0 {
return Err(DofError::ZeroDimension);
}
if channels == 0 {
return Err(DofError::ZeroChannels);
}
if image.is_empty() {
return Err(DofError::EmptyImage);
}
let num_pixels = image_width * image_height;
let expected_image = num_pixels * channels;
let expected_depth = num_pixels;
if image.len() != expected_image || depth_map.len() != expected_depth {
return Err(DofError::SizeMismatch {
image_len: image.len(),
depth_len: depth_map.len(),
});
}
let coc_map = compute_coc(depth_map, config, image_width, image_height)?;
const MAX_GATHER_RADIUS: f32 = 20.0;
let sqrt3_over2: f32 = (3.0_f32).sqrt() / 2.0;
let mut output = vec![0.0_f32; expected_image];
let mut acc = vec![0.0_f32; channels];
for py in 0..image_height {
for px in 0..image_width {
let pixel_idx = py * image_width + px;
let coc_r = coc_map[pixel_idx];
if coc_r < 0.5 {
let base = pixel_idx * channels;
output[base..base + channels].copy_from_slice(&image[base..base + channels]);
continue;
}
let r = coc_r.min(MAX_GATHER_RADIUS);
let r_ceil = r.ceil() as isize;
let r2 = r * r;
acc.fill(0.0);
let mut weight_sum = 0.0_f32;
let y_lo = (py as isize - r_ceil).max(0) as usize;
let y_hi = (py as isize + r_ceil).min(image_height as isize - 1) as usize;
let x_lo = (px as isize - r_ceil).max(0) as usize;
let x_hi = (px as isize + r_ceil).min(image_width as isize - 1) as usize;
for sy in y_lo..=y_hi {
for sx in x_lo..=x_hi {
let dy = sy as f32 - py as f32;
let dx = sx as f32 - px as f32;
let inside = match kernel_shape {
DofKernelShape::Circular => dx * dx + dy * dy <= r2,
DofKernelShape::Hexagonal => {
let term_a = dx.abs();
let term_b = (dx / 2.0 + dy * sqrt3_over2).abs();
let term_c = (dx / 2.0 - dy * sqrt3_over2).abs();
term_a.max(term_b).max(term_c) <= r
}
DofKernelShape::Square => dx.abs() <= r && dy.abs() <= r,
};
if inside {
let src_base = (sy * image_width + sx) * channels;
for c in 0..channels {
acc[c] += image[src_base + c];
}
weight_sum += 1.0;
}
}
}
let dst_base = pixel_idx * channels;
if weight_sum > 0.0 {
let inv = 1.0 / weight_sum;
for c in 0..channels {
output[dst_base + c] = acc[c] * inv;
}
} else {
output[dst_base..dst_base + channels]
.copy_from_slice(&image[dst_base..dst_base + channels]);
}
}
}
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
fn default_cfg() -> DofConfig {
DofConfig::default()
}
fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
(a - b).abs() < eps
}
#[test]
fn test_coc_at_focal_distance() {
let cfg = default_cfg(); let depth_map = vec![2.0_f32; 4];
let coc = compute_coc(&depth_map, &cfg, 2, 2).expect("compute_coc failed");
for &c in &coc {
assert!(
approx_eq(c, 0.0, 1e-4),
"Expected 0 coc at focal distance, got {c}"
);
}
}
#[test]
fn test_coc_far_from_focus() {
let cfg = DofConfig {
focal_distance: 2.0,
focal_range: 0.3,
max_blur_radius: 15.0,
};
let depth_map = vec![100.0_f32; 4];
let coc = compute_coc(&depth_map, &cfg, 2, 2).expect("compute_coc failed");
for &c in &coc {
assert!(
approx_eq(c, 15.0, 1e-3),
"Expected max_blur_radius=15.0, got {c}"
);
}
}
#[test]
fn test_coc_linear_falloff() {
let cfg = DofConfig {
focal_distance: 2.0,
focal_range: 0.4, max_blur_radius: 10.0,
};
let depth_map = vec![2.2_f32; 1];
let coc = compute_coc(&depth_map, &cfg, 1, 1).expect("compute_coc failed");
assert!(
approx_eq(coc[0], 10.0, 1e-3),
"Expected 10.0, got {}",
coc[0]
);
let depth_map2 = vec![2.1_f32; 1];
let coc2 = compute_coc(&depth_map2, &cfg, 1, 1).expect("compute_coc failed");
assert!(
approx_eq(coc2[0], 5.0, 1e-3),
"Expected 5.0, got {}",
coc2[0]
);
}
#[test]
fn test_coc_clamp_at_max() {
let cfg = DofConfig {
focal_distance: 1.0,
focal_range: 0.1,
max_blur_radius: 8.0,
};
let depth_map = vec![999.0_f32; 1];
let coc = compute_coc(&depth_map, &cfg, 1, 1).expect("compute_coc failed");
assert!(coc[0] <= 8.0 + 1e-6, "CoC must not exceed max_blur_radius");
assert!(approx_eq(coc[0], 8.0, 1e-3), "Expected 8.0, got {}", coc[0]);
}
#[test]
fn test_coc_zero_depth_gets_max() {
let cfg = default_cfg();
let depth_map = vec![0.0_f32; 1];
let coc = compute_coc(&depth_map, &cfg, 1, 1).expect("compute_coc failed");
assert!(
approx_eq(coc[0], cfg.max_blur_radius, 1e-4),
"depth=0 should give max coc, got {}",
coc[0]
);
}
#[test]
fn test_coc_infinite_depth_gets_max() {
let cfg = default_cfg();
let depth_map = vec![f32::INFINITY; 1];
let coc = compute_coc(&depth_map, &cfg, 1, 1).expect("compute_coc failed");
assert!(
approx_eq(coc[0], cfg.max_blur_radius, 1e-4),
"depth=inf should give max coc, got {}",
coc[0]
);
}
#[test]
fn test_generate_kernel_circular_sum_one() {
let (kernel, side) = generate_dof_kernel(3.0, DofKernelShape::Circular);
assert_eq!(kernel.len(), side * side);
let sum: f32 = kernel.iter().sum();
assert!(approx_eq(sum, 1.0, 1e-5), "Circular kernel sum = {sum}");
}
#[test]
fn test_generate_kernel_hexagonal_sum_one() {
let (kernel, side) = generate_dof_kernel(4.0, DofKernelShape::Hexagonal);
assert_eq!(kernel.len(), side * side);
let sum: f32 = kernel.iter().sum();
assert!(approx_eq(sum, 1.0, 1e-5), "Hexagonal kernel sum = {sum}");
}
#[test]
fn test_generate_kernel_square_sum_one() {
let (kernel, side) = generate_dof_kernel(2.0, DofKernelShape::Square);
assert_eq!(kernel.len(), side * side);
let sum: f32 = kernel.iter().sum();
assert!(approx_eq(sum, 1.0, 1e-5), "Square kernel sum = {sum}");
}
#[test]
fn test_generate_kernel_radius_zero() {
let (kernel, side) = generate_dof_kernel(0.0, DofKernelShape::Circular);
assert_eq!(side, 1, "side for radius=0 should be 1");
assert_eq!(kernel.len(), 1);
assert!(approx_eq(kernel[0], 1.0, 1e-6), "1x1 kernel must be [1.0]");
}
#[test]
fn test_generate_kernel_side_matches_radius() {
let (_, side) = generate_dof_kernel(5.0, DofKernelShape::Square);
assert_eq!(side, 11, "side for r=5 should be 11");
let (_, side2) = generate_dof_kernel(2.7, DofKernelShape::Circular);
assert_eq!(side2, 7, "side for r=2.7 (ceil=3) should be 7");
}
#[test]
fn test_apply_dof_sharp_region_unchanged() {
let cfg = DofConfig {
focal_distance: 2.0,
focal_range: 0.3,
max_blur_radius: 15.0,
};
let w = 4_usize;
let h = 4_usize;
let c = 3_usize;
let image: Vec<f32> = (0..w * h * c).map(|i| i as f32 / 100.0).collect();
let depth_map = vec![2.0_f32; w * h];
let output = apply_dof(&image, &depth_map, &cfg, DofKernelShape::Circular, w, h, c)
.expect("apply_dof failed");
assert_eq!(output.len(), image.len());
for (i, (&a, &b)) in image.iter().zip(output.iter()).enumerate() {
assert!(approx_eq(a, b, 1e-5), "pixel {i}: expected {a}, got {b}");
}
}
#[test]
fn test_apply_dof_uniform_image_unchanged() {
let cfg = default_cfg();
let w = 8_usize;
let h = 8_usize;
let c = 3_usize;
let colour = [0.4_f32, 0.6_f32, 0.8_f32];
let image: Vec<f32> = (0..w * h).flat_map(|_| colour).collect();
let depth_map = vec![0.0_f32; w * h];
let output = apply_dof(&image, &depth_map, &cfg, DofKernelShape::Circular, w, h, c)
.expect("apply_dof failed");
for chunk in output.chunks_exact(c) {
for (ci, &expected) in colour.iter().enumerate() {
assert!(
approx_eq(chunk[ci], expected, 1e-4),
"Uniform image: channel {ci} expected {expected}, got {}",
chunk[ci]
);
}
}
}
#[test]
fn test_apply_dof_size_mismatch_error() {
let cfg = default_cfg();
let image = vec![0.5_f32; 3 * 4 * 3]; let depth_map = vec![2.0_f32; 3 * 5];
let result = apply_dof(&image, &depth_map, &cfg, DofKernelShape::Circular, 4, 3, 3);
assert!(
matches!(result, Err(DofError::SizeMismatch { .. })),
"Expected SizeMismatch error"
);
}
#[test]
fn test_apply_dof_output_size_matches_input() {
let cfg = default_cfg();
let w = 5_usize;
let h = 6_usize;
let c = 4_usize;
let image = vec![0.5_f32; w * h * c];
let depth_map = vec![2.0_f32; w * h];
let output = apply_dof(&image, &depth_map, &cfg, DofKernelShape::Square, w, h, c)
.expect("apply_dof failed");
assert_eq!(
output.len(),
image.len(),
"Output size must match input size"
);
}
#[test]
fn test_dof_stats_compute() {
let coc = vec![0.0_f32, 0.0, 5.0, 10.0];
let stats = DofStats::compute(&coc, 0.5);
assert!(
approx_eq(stats.mean_coc, 3.75, 1e-4),
"mean = {}",
stats.mean_coc
);
assert!(
approx_eq(stats.max_coc, 10.0, 1e-4),
"max = {}",
stats.max_coc
);
assert!(
approx_eq(stats.sharp_pixel_fraction, 0.5, 1e-4),
"sharp_frac = {}",
stats.sharp_pixel_fraction
);
assert!(
approx_eq(stats.blurred_pixel_fraction, 0.5, 1e-4),
"blurred_frac = {}",
stats.blurred_pixel_fraction
);
}
#[test]
fn test_dof_stats_sharp_fraction() {
let coc = vec![0.0_f32; 10];
let stats = DofStats::compute(&coc, 0.5);
assert!(approx_eq(stats.sharp_pixel_fraction, 1.0, 1e-5));
assert!(approx_eq(stats.blurred_pixel_fraction, 0.0, 1e-5));
}
#[test]
fn test_dof_stats_empty() {
let stats = DofStats::compute(&[], 0.5);
assert!(approx_eq(stats.mean_coc, 0.0, 1e-6));
assert!(approx_eq(stats.max_coc, 0.0, 1e-6));
assert!(approx_eq(stats.sharp_pixel_fraction, 1.0, 1e-6));
assert!(approx_eq(stats.blurred_pixel_fraction, 0.0, 1e-6));
}
#[test]
fn test_dof_stats_format_summary_non_empty() {
let coc = vec![2.0_f32, 4.0_f32];
let stats = DofStats::compute(&coc, 0.5);
let summary = stats.format_summary();
assert!(summary.contains("DoF:"), "summary: {summary}");
assert!(summary.contains("mean_coc"), "summary: {summary}");
assert!(summary.contains("max_coc"), "summary: {summary}");
}
#[test]
fn test_dof_config_default() {
let cfg = DofConfig::default();
assert!(approx_eq(cfg.focal_distance, 2.0, 1e-6));
assert!(approx_eq(cfg.focal_range, 0.3, 1e-6));
assert!(approx_eq(cfg.max_blur_radius, 15.0, 1e-6));
}
#[test]
fn test_apply_dof_hexagonal_kernel_runs() {
let cfg = DofConfig {
focal_distance: 5.0,
focal_range: 0.1,
max_blur_radius: 5.0,
};
let w = 6_usize;
let h = 6_usize;
let c = 3_usize;
let image: Vec<f32> = (0..w * h * c).map(|i| (i % 256) as f32 / 255.0).collect();
let depth_map = vec![1.0_f32; w * h];
let output = apply_dof(&image, &depth_map, &cfg, DofKernelShape::Hexagonal, w, h, c)
.expect("Hexagonal apply_dof failed");
assert_eq!(output.len(), image.len());
}
#[test]
fn test_coc_error_zero_dimension() {
let cfg = default_cfg();
let result = compute_coc(&[1.0], &cfg, 0, 1);
assert!(matches!(result, Err(DofError::ZeroDimension)));
}
#[test]
fn test_apply_dof_zero_channels_error() {
let cfg = default_cfg();
let image = vec![0.5_f32; 4];
let depth_map = vec![2.0_f32; 4];
let result = apply_dof(&image, &depth_map, &cfg, DofKernelShape::Circular, 2, 2, 0);
assert!(matches!(result, Err(DofError::ZeroChannels)));
}
#[test]
fn test_compute_coc_size_mismatch_reports_correct_fields() {
let cfg = default_cfg();
let depth_map = vec![1.0_f32; 5]; let result = compute_coc(&depth_map, &cfg, 3, 2);
match result {
Err(DofError::SizeMismatch {
image_len,
depth_len,
}) => {
assert_eq!(
depth_len, 5,
"depth_len must be the depth buffer's actual length"
);
assert_eq!(image_len, 6, "image_len must be the expected pixel count");
}
other => panic!("expected SizeMismatch, got {other:?}"),
}
}
}