use crate::psf::gaussian_blur;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EmulsionBlur {
pub sigma_um: [f64; 3],
pub pixel_um: f64,
}
impl EmulsionBlur {
#[must_use]
pub fn measured(pixel_um: f64) -> Self {
Self {
sigma_um: [3.43, 3.67, 4.64],
pixel_um,
}
}
#[must_use]
pub fn for_stock(film: &crate::emulsion::FilmStock, pixel_um: f64) -> Self {
Self {
sigma_um: film.sigma_um.unwrap_or([3.43, 3.67, 4.64]),
pixel_um,
}
}
#[must_use]
pub fn is_noop(&self) -> bool {
let per_pixel = self.pixel_um.max(1e-9);
self.sigma_um
.iter()
.all(|&sigma| sigma <= 0.0 || sigma / per_pixel < 0.5)
}
pub fn apply(&self, log_e: &mut [[f64; 3]], width: usize, height: usize) {
if self.is_noop() || width == 0 || height == 0 {
return;
}
let pixels = (width * height).min(log_e.len());
let height = pixels / width;
if height == 0 {
return;
}
for channel in 0..3 {
let sigma_px = self.sigma_um[channel] / self.pixel_um.max(1e-9);
if sigma_px <= 0.0 {
continue;
}
let plane: Vec<f64> = log_e[..pixels]
.iter()
.map(|pixel| 10.0_f64.powf(pixel[channel]))
.collect();
let blurred = gaussian_blur(&plane, width, height, sigma_px);
for (pixel, value) in log_e[..pixels].iter_mut().zip(blurred) {
pixel[channel] = value.max(1e-10).log10();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const W: usize = 32;
const H: usize = 32;
#[test]
fn the_blur_preserves_the_total_exposure() {
let mut buffer = vec![[-30.0; 3]; W * H];
buffer[(H / 2) * W + W / 2] = [0.0; 3];
let before = 10.0_f64.powf(0.0);
EmulsionBlur::measured(2.0).apply(&mut buffer, W, H);
let after: f64 = buffer.iter().map(|pixel| 10.0_f64.powf(pixel[0])).sum();
assert!(
(after - before).abs() < 1e-6 * before,
"{after} against {before}"
);
}
#[test]
fn blue_spreads_further_than_red() {
let mut buffer = vec![[-6.0; 3]; W * H];
buffer[(H / 2) * W + W / 2] = [0.0; 3];
EmulsionBlur::measured(2.0).apply(&mut buffer, W, H);
let centre = (H / 2) * W + W / 2;
let nearby = buffer[centre + 2];
assert!(
nearby[0] > nearby[2],
"red {nearby:?} should be sharper than blue"
);
}
#[test]
fn the_blur_is_a_no_op_below_the_film_s_blur() {
assert!(EmulsionBlur::measured(30.0).is_noop());
assert!(!EmulsionBlur::measured(6.0).is_noop());
let fine = EmulsionBlur::measured(3.0);
assert!(!fine.is_noop());
for sigma in fine.sigma_um {
assert!(sigma / 3.0 >= 0.5);
}
}
#[test]
fn a_flat_frame_is_unchanged() {
let mut buffer = vec![[-1.0; 3]; W * H];
EmulsionBlur::measured(2.0).apply(&mut buffer, W, H);
for pixel in &buffer {
assert!((pixel[0] + 1.0).abs() < 1e-9, "{pixel:?}");
}
}
}