use image::GrayImage;
use printobserver_core::LayerToolpath;
use crate::calibration::CameraCalibration;
use crate::compose::decode;
use crate::drift::check_frame;
use crate::error::ComposeError;
use crate::geometry::{band_outside, convex_hull, project_toolpath, sample_along};
pub const SAMPLE_PX: f64 = 4.0;
pub const BAND_PX: f64 = 10.0;
pub const SEARCH_PX: i32 = 60;
const SHIFT_STEP: i32 = 2;
const SMOOTHING: i32 = 2;
const BLUR_SIGMA: f32 = 1.5;
#[derive(Debug, Clone, Copy)]
pub struct AlignmentInputs<'a> {
pub frame_jpeg: &'a [u8],
pub camera_snapshot_url: &'a str,
pub first_layer: &'a LayerToolpath,
pub print_z_mm: f64,
pub calibration: &'a CameraCalibration,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AlignmentVerdict {
pub offset_px: f64,
pub passed: bool,
}
pub fn verify_first_layer_alignment(
inputs: &AlignmentInputs<'_>,
) -> Result<AlignmentVerdict, ComposeError> {
let frame = decode(inputs.frame_jpeg)?;
check_frame(
inputs.calibration,
[frame.width(), frame.height()],
inputs.camera_snapshot_url,
)?;
let grey =
imageproc::filter::gaussian_blur_f32(&image::imageops::grayscale(&frame), BLUR_SIGMA);
let pieces = project_toolpath(
&inputs.calibration.projector(),
inputs.first_layer,
inputs.print_z_mm,
);
let (w, h) = (f64::from(frame.width()), f64::from(frame.height()));
let path: Vec<[f64; 2]> = sample_along(&pieces, SAMPLE_PX)
.into_iter()
.filter(|[x, y]| (0.0..w).contains(x) && (0.0..h).contains(y))
.collect();
if path.len() < 3 {
return Err(ComposeError::OutlineOffFrame);
}
let band = band_outside(&convex_hull(&path), BAND_PX, SAMPLE_PX);
let offset_px = best_shift(&grey, &path, &band);
Ok(AlignmentVerdict {
offset_px,
passed: offset_px <= inputs.calibration.alignment_max_offset_px,
})
}
fn best_shift(grey: &GrayImage, path: &[[f64; 2]], band: &[[f64; 2]]) -> f64 {
let side = usize::try_from(2 * SEARCH_PX / SHIFT_STEP + 1).unwrap_or(1);
let index = |shift: i32| usize::try_from((shift + SEARCH_PX) / SHIFT_STEP).unwrap_or(0);
let mut contrast = vec![0.0_f64; side * side];
let shifts = || (-SEARCH_PX..=SEARCH_PX).step_by(usize::try_from(SHIFT_STEP).unwrap_or(1));
for dx in shifts() {
for dy in shifts() {
let inside = mean_at(grey, path, dx, dy);
let outside = mean_at(grey, band, dx, dy);
contrast[index(dy) * side + index(dx)] = (inside - outside).abs();
}
}
let mut best = (f64::NEG_INFINITY, 0, 0);
for dx in shifts() {
for dy in shifts() {
if dx * dx + dy * dy > SEARCH_PX * SEARCH_PX {
continue;
}
let mut sum = 0.0;
let mut count = 0.0;
for ox in -SMOOTHING..=SMOOTHING {
for oy in -SMOOTHING..=SMOOTHING {
let x = (index(dx).cast_signed() + isize::try_from(ox).unwrap_or(0))
.clamp(0, side.cast_signed() - 1)
.cast_unsigned();
let y = (index(dy).cast_signed() + isize::try_from(oy).unwrap_or(0))
.clamp(0, side.cast_signed() - 1)
.cast_unsigned();
sum += contrast[y * side + x];
count += 1.0;
}
}
let score = sum / count;
if score > best.0 {
best = (score, dx, dy);
}
}
}
f64::from(best.1).hypot(f64::from(best.2))
}
fn mean_at(grey: &GrayImage, points: &[[f64; 2]], dx: i32, dy: i32) -> f64 {
if points.is_empty() {
return 0.0;
}
let (w, h) = (f64::from(grey.width() - 1), f64::from(grey.height() - 1));
let mut sum = 0.0;
for [x, y] in points {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped into the frame, whose size fits a u32"
)]
let (px, py) = (
(x + f64::from(dx)).round().clamp(0.0, w) as u32,
(y + f64::from(dy)).round().clamp(0.0, h) as u32,
);
sum += f64::from(grey.get_pixel(px, py).0[0]);
}
#[expect(
clippy::cast_precision_loss,
reason = "a path holds at most some tens of thousands of samples"
)]
let count = points.len() as f64;
sum / count
}