use crate::psf::gaussian_blur;
#[derive(Debug, Clone, Copy)]
pub struct InterImage {
pub gain: f64,
pub sigma_um: f64,
pub pixel_um: f64,
}
impl InterImage {
#[must_use]
pub fn typical(pixel_um: f64) -> Self {
Self {
gain: 0.12,
sigma_um: 20.0,
pixel_um,
}
}
#[must_use]
pub fn is_noop(&self) -> bool {
self.gain <= 0.0
}
pub fn apply(&self, density: &mut [[f64; 3]], light: &[f64], width: usize, height: usize) {
if self.is_noop() || width == 0 || height == 0 {
return;
}
let pixels = (width * height).min(density.len()).min(light.len());
let height = pixels / width;
if height == 0 {
return;
}
let mean = light[..pixels].iter().sum::<f64>() / pixels as f64;
if !mean.is_finite() || mean <= 0.0 {
return;
}
let sigma_px = self.sigma_um / self.pixel_um.max(1e-9);
let diffused = gaussian_blur(&light[..pixels], width, height, sigma_px);
for (index, pixel) in density[..pixels].iter_mut().enumerate() {
let local = light[index];
let deviation = if local > 0.0 {
(diffused[index] / local - 1.0).clamp(-1.0, 1.0)
} else if diffused[index] > 0.0 {
1.0
} else {
0.0
};
pixel[0] = (pixel[0] * (1.0 - self.gain * deviation)).max(0.0);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn light_from(values: impl Fn(usize) -> f64, count: usize) -> Vec<f64> {
(0..count).map(values).collect()
}
#[test]
fn a_uniform_frame_is_untouched() {
let stage = InterImage::typical(6.0);
let mut density = vec![[1.0, 0.8, 0.6]; 64];
let expected = density.clone();
stage.apply(&mut density, &light_from(|_| 3.7, 64), 8, 8);
for (left, right) in density.iter().zip(&expected) {
assert!((left[0] - right[0]).abs() < 1e-12, "{left:?} vs {right:?}");
}
}
#[test]
fn a_step_takes_cyan_off_the_shadow_side() {
let stage = InterImage {
gain: 0.12,
sigma_um: 3.0,
pixel_um: 1.0,
};
let mut density = vec![[1.0, 1.0, 1.0]; 64];
let light = light_from(|index| if index < 32 { 0.0 } else { 4.0 }, 64);
stage.apply(&mut density, &light, 64, 1);
let shadow = density[31][0];
let bright = density[32][0];
assert!(shadow < 0.93, "the shadow kept the inhibitor: {shadow:.4}");
assert!(
bright > 1.01,
"the bright side lost instead of gaining: {bright:.4}"
);
assert!(
density
.iter()
.all(|pixel| (0.88..=1.12).contains(&pixel[0]))
);
assert!((density[0][0] - 1.0).abs() < 1e-9, "{:?}", density[0]);
assert!((density[63][0] - 1.0).abs() < 1e-9, "{:?}", density[63]);
assert_eq!([density[31][1], density[31][2]], [1.0, 1.0]);
}
#[test]
fn a_dark_frame_is_untouched() {
let stage = InterImage::typical(6.0);
let mut density = vec![[0.5, 0.5, 0.5]; 4];
stage.apply(&mut density, &[0.0; 4], 2, 2);
assert_eq!(density[0], [0.5, 0.5, 0.5]);
}
#[test]
fn a_zero_gain_changes_nothing() {
let stage = InterImage {
gain: 0.0,
..InterImage::typical(6.0)
};
assert!(stage.is_noop());
let mut density = vec![[1.0, 1.0, 1.0]; 8];
stage.apply(&mut density, &light_from(|index| index as f64, 8), 8, 1);
assert_eq!(density[3], [1.0, 1.0, 1.0]);
}
}