pub const MAX_LEVEL: u32 = 8;
pub const GAUSS_MAX: f32 = 4.0;
pub const TRUNCATION: f32 = 3.5;
pub const MAX_RADIUS: u32 = 16;
pub const COPY_BELOW: f32 = 0.2;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Filter {
pub level: u32,
pub sigma: f32,
pub radius: u32,
}
pub fn fixed_variance(level: u32) -> f32 {
if level == 0 {
return 0.0;
}
let steps: f32 = (1..=level).map(|k| 1.25 * 4.0_f32.powi(k as i32 - 1)).sum();
steps + 4.0_f32.powi(level as i32) / 3.0
}
pub fn filter(sigma: f32) -> Filter {
if !(sigma >= COPY_BELOW) {
return Filter {
level: 0,
sigma: 0.0,
radius: 0,
};
}
let mut level = 0;
let sigma_at = |level: u32| {
let left = sigma * sigma - fixed_variance(level);
(left.max(0.0) / 4.0_f32.powi(level as i32)).sqrt()
};
while level < MAX_LEVEL && sigma_at(level) > GAUSS_MAX {
level += 1;
}
let sigma = sigma_at(level);
let radius = if sigma < COPY_BELOW {
0
} else {
((sigma * TRUNCATION).ceil() as u32).clamp(1, MAX_RADIUS)
};
Filter {
level,
sigma,
radius,
}
}
pub fn level_size([width, height]: [u32; 2], level: u32) -> [u32; 2] {
[
width.div_ceil(1 << level).max(1),
height.div_ceil(1 << level).max(1),
]
}
pub fn gaussian_fetches(sigma: f32, radius: u32) -> Vec<(f32, f32)> {
let weight = |i: u32| (-0.5 * (i * i) as f32 / (sigma * sigma)).exp();
(1..=radius)
.step_by(2)
.map(|i| {
let (w1, w2) = (weight(i), if i < radius { weight(i + 1) } else { 0.0 });
let w = w1 + w2;
((i as f32 * w1 + (i + 1) as f32 * w2) / w, w)
})
.collect()
}