use image::GrayImage;
use printobserver_core::LayerToolpath;
use crate::calibration::CameraCalibration;
use crate::compose::decode;
use crate::drift::check_frame;
use crate::error::ComposeError;
pub const MIN_RISE_MM: f64 = 3.0;
pub const SAMPLE_MM: f64 = 1.5;
const MAX_SAMPLES: usize = 1500;
const HALF_PATCH: i64 = 6;
const FEATURELESS_GREY: f64 = 5.0;
const BLUR_SIGMA: f32 = 1.0;
pub const MIN_SAMPLES: usize = 50;
pub const MIN_SEPARATION_PX: f64 = 6.0;
pub const NOT_GROWN_CORRELATION: f64 = 0.45;
pub const NOT_GROWN_SHARE: f64 = 0.7;
#[derive(Debug, Clone, Copy)]
pub struct GrowthInputs<'a> {
pub earlier_jpeg: &'a [u8],
pub earlier_print_z_mm: f64,
pub current_jpeg: &'a [u8],
pub current_print_z_mm: f64,
pub camera_snapshot_url: &'a str,
pub toolpath: &'a LayerToolpath,
pub calibration: &'a CameraCalibration,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Growth {
pub samples: usize,
pub separation_px: f64,
pub held: f64,
pub carried: f64,
pub carried_share: f64,
}
impl Growth {
#[must_use]
pub fn not_grown(&self) -> bool {
self.samples >= MIN_SAMPLES
&& self.separation_px >= MIN_SEPARATION_PX
&& self.carried >= NOT_GROWN_CORRELATION
&& self.carried_share >= NOT_GROWN_SHARE
}
}
pub fn measure_growth(inputs: &GrowthInputs<'_>) -> Result<Option<Growth>, ComposeError> {
let earlier = grey(inputs.earlier_jpeg, inputs)?;
let current = grey(inputs.current_jpeg, inputs)?;
let projector = inputs.calibration.projector();
let at_nozzle = f64::from(inputs.toolpath.z_mm) - inputs.current_print_z_mm;
let travelled = inputs.earlier_print_z_mm - inputs.current_print_z_mm;
let mut held = Vec::new();
let mut carried = Vec::new();
let mut separations = Vec::new();
for [x, y] in samples(inputs.toolpath) {
let (Some(here), Some(lowered)) = (
projector.pixel([x, y, at_nozzle]),
projector.pixel([x, y, at_nozzle + travelled]),
) else {
continue;
};
let (Some(then), Some(now_held), Some(now_carried)) = (
patch(&earlier, here),
patch(¤t, here),
patch(¤t, lowered),
) else {
continue;
};
if featureless(&then) && featureless(&now_held) && featureless(&now_carried) {
continue;
}
let (Some(held_at), Some(carried_at)) = (
correlation(&then, &now_held),
correlation(&then, &now_carried),
) else {
continue;
};
held.push(held_at);
carried.push(carried_at);
separations.push((lowered[0] - here[0]).hypot(lowered[1] - here[1]));
}
if held.len() < MIN_SAMPLES {
return Ok(None);
}
let preferring = held
.iter()
.zip(&carried)
.filter(|(held, carried)| carried > held)
.count();
let carried_share = ratio(preferring, held.len());
Ok(Some(Growth {
samples: held.len(),
separation_px: median(&mut separations),
held: median(&mut held),
carried: median(&mut carried),
carried_share,
}))
}
fn grey(jpeg: &[u8], inputs: &GrowthInputs<'_>) -> Result<GrayImage, ComposeError> {
let frame = decode(jpeg)?;
check_frame(
inputs.calibration,
[frame.width(), frame.height()],
inputs.camera_snapshot_url,
)?;
Ok(imageproc::filter::gaussian_blur_f32(
&image::imageops::grayscale(&frame),
BLUR_SIGMA,
))
}
fn samples(toolpath: &LayerToolpath) -> Vec<[f64; 2]> {
let mut points = Vec::new();
for segment in toolpath
.segments
.iter()
.filter(|segment| !segment.kind.is_support())
{
let from = segment.from_mm.map(f64::from);
let to = segment.to_mm.map(f64::from);
let steps = ((to[0] - from[0]).hypot(to[1] - from[1]) / SAMPLE_MM)
.floor()
.clamp(1.0, 4096.0);
let mut k = 0.0;
while k < steps {
let t = k / steps;
points.push([
from[0] + t * (to[0] - from[0]),
from[1] + t * (to[1] - from[1]),
]);
k += 1.0;
}
}
if points.len() <= MAX_SAMPLES {
return points;
}
let last = points.len() - 1;
(0..MAX_SAMPLES)
.map(|k| points[k * last / (MAX_SAMPLES - 1)])
.collect()
}
fn patch(frame: &GrayImage, at: [f64; 2]) -> Option<Vec<f64>> {
let (width, height) = (i64::from(frame.width()), i64::from(frame.height()));
if !(at[0].is_finite() && at[1].is_finite()) {
return None;
}
#[expect(
clippy::cast_possible_truncation,
reason = "a finite pixel coordinate, bounded below before it is used"
)]
let (x, y) = (at[0].round() as i64, at[1].round() as i64);
if x < HALF_PATCH || y < HALF_PATCH || x >= width - HALF_PATCH || y >= height - HALF_PATCH {
return None;
}
let mut values = Vec::with_capacity(169);
for row in (y - HALF_PATCH)..=(y + HALF_PATCH) {
for column in (x - HALF_PATCH)..=(x + HALF_PATCH) {
let (Ok(column), Ok(row)) = (u32::try_from(column), u32::try_from(row)) else {
return None;
};
values.push(f64::from(frame.get_pixel(column, row).0[0]));
}
}
Some(values)
}
fn featureless(values: &[f64]) -> bool {
moments(values).1 < FEATURELESS_GREY
}
fn moments(values: &[f64]) -> (f64, f64) {
let count = ratio(values.len(), 1);
let mean = values.iter().sum::<f64>() / count;
let variance = values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / count;
(mean, variance.sqrt())
}
fn correlation(a: &[f64], b: &[f64]) -> Option<f64> {
let (mean_a, _) = moments(a);
let (mean_b, _) = moments(b);
let mut product = 0.0;
let mut square_a = 0.0;
let mut square_b = 0.0;
for (a, b) in a.iter().zip(b) {
let (a, b) = (a - mean_a, b - mean_b);
product += a * b;
square_a += a * a;
square_b += b * b;
}
let scale = (square_a * square_b).sqrt();
(scale > 1e-9).then(|| product / scale)
}
fn ratio(count: usize, of: usize) -> f64 {
let exact = |count: usize| f64::from(u32::try_from(count).unwrap_or(u32::MAX));
exact(count) / exact(of)
}
fn median(values: &mut [f64]) -> f64 {
values.sort_by(f64::total_cmp);
values[values.len() / 2]
}