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, signed_distance};
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
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;
pub const CLEARLY_FOUND_CONTRAST: f64 = 15.0;
pub const TOOLHEAD_MARGIN_PX: f64 = 10.0;
pub const CORRECTION_TAKEN_WITHIN_MM: f64 = 0.3;
#[must_use]
pub fn correction_shift(
found: &AlignmentVerdict,
first_layer: &LayerToolpath,
print_z_mm: f64,
) -> [f64; 2] {
if print_z_mm - f64::from(first_layer.z_mm) <= CORRECTION_TAKEN_WITHIN_MM + 1e-6 {
found.shift_px
} else {
[0.0, 0.0]
}
}
pub const TOOLHEAD_HIDES_MM: f64 = 50.0;
#[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 shift_px: [f64; 2],
pub match_strength: f64,
pub passed: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum InconclusiveReason {
Covered,
NotClearlyFound,
}
impl InconclusiveReason {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Covered => "covered",
Self::NotClearlyFound => "not_clearly_found",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FirstLayerVerdict {
Passed,
Inconclusive(InconclusiveReason),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FirstLayerJudgement {
pub verdict: FirstLayerVerdict,
pub found: Option<AlignmentVerdict>,
}
#[derive(Debug, Clone, Copy)]
pub struct FirstLayerInputs<'a> {
pub alignment: AlignmentInputs<'a>,
pub nozzle_xy_mm: Option<[f64; 2]>,
}
pub fn judge_first_layer(
inputs: &FirstLayerInputs<'_>,
) -> Result<FirstLayerJudgement, ComposeError> {
let alignment = &inputs.alignment;
let found = match verify_first_layer_alignment(alignment) {
Ok(found) => found,
Err(ComposeError::OutlineOffFrame) => {
return Ok(FirstLayerJudgement {
verdict: FirstLayerVerdict::Inconclusive(InconclusiveReason::NotClearlyFound),
found: None,
});
}
Err(other) => return Err(other),
};
let verdict = if covered(inputs) {
FirstLayerVerdict::Inconclusive(InconclusiveReason::Covered)
} else if found.passed {
FirstLayerVerdict::Passed
} else {
FirstLayerVerdict::Inconclusive(InconclusiveReason::NotClearlyFound)
};
Ok(FirstLayerJudgement {
verdict,
found: Some(found),
})
}
#[must_use]
pub fn nozzle_from_first_layer_px(inputs: &FirstLayerInputs<'_>) -> Option<f64> {
let [x, y] = inputs.nozzle_xy_mm?;
let alignment = &inputs.alignment;
let projector = alignment.calibration.projector();
let nozzle = projector.pixel([x, y, 0.0])?;
let pieces = project_toolpath(&projector, alignment.first_layer, alignment.print_z_mm);
let hull = convex_hull(&sample_along(&pieces, SAMPLE_PX));
(hull.len() >= 3).then(|| signed_distance(nozzle, &hull))
}
#[must_use]
pub fn first_layer_span_mm(first_layer: &LayerToolpath) -> f64 {
let mut bounds: Option<[f64; 4]> = None;
for segment in &first_layer.segments {
for [x, y] in [segment.from_mm, segment.to_mm] {
let (x, y) = (f64::from(x), f64::from(y));
bounds = Some(bounds.map_or([x, y, x, y], |[x0, y0, x1, y1]| {
[x0.min(x), y0.min(y), x1.max(x), y1.max(y)]
}));
}
}
bounds.map_or(0.0, |[x0, y0, x1, y1]| (x1 - x0).max(y1 - y0))
}
fn covered(inputs: &FirstLayerInputs<'_>) -> bool {
first_layer_span_mm(inputs.alignment.first_layer) <= TOOLHEAD_HIDES_MM
&& nozzle_from_first_layer_px(inputs).is_some_and(|distance| distance <= TOOLHEAD_MARGIN_PX)
}
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 (match_strength, dx, dy) = best_shift(&grey, &path, &band);
let shift_px = [f64::from(dx), f64::from(dy)];
let offset_px = shift_px[0].hypot(shift_px[1]);
Ok(AlignmentVerdict {
offset_px,
shift_px,
match_strength,
passed: offset_px <= inputs.calibration.alignment_max_offset_px
&& match_strength >= CLEARLY_FOUND_CONTRAST,
})
}
fn best_shift(grey: &GrayImage, path: &[[f64; 2]], band: &[[f64; 2]]) -> (f64, i32, i32) {
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);
}
}
}
best
}
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
}