use image::GrayImage;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
use crate::calibration::CameraCalibration;
use crate::compose::decode;
use crate::drift::{
HIDDEN_BELOW, Located, VIEW_SEARCH_RADIUS_PX, check_frame, locate_landmarks_within,
};
use crate::error::ComposeError;
pub const AGREEMENT_PX: f64 = 25.0;
#[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 ViewModel {
Translation,
Similarity,
Affine,
Homography,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ReferenceLandmark {
pub name: String,
pub offset_px: [f64; 2],
pub score: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct ViewCorrection {
pub model: ViewModel,
pub matrix: [[f64; 3]; 3],
pub landmarks: Vec<ReferenceLandmark>,
pub residual_px: f64,
}
impl ViewCorrection {
#[must_use]
pub fn translation(shift_px: [f64; 2], landmarks: Vec<ReferenceLandmark>) -> Self {
let squares: Vec<f64> = landmarks
.iter()
.map(|landmark| {
let (dx, dy) = (
landmark.offset_px[0] - shift_px[0],
landmark.offset_px[1] - shift_px[1],
);
dx * dx + dy * dy
})
.collect();
let residual_px = if squares.is_empty() {
0.0
} else {
(squares.iter().sum::<f64>() / f64::from(u32::try_from(squares.len()).unwrap_or(1)))
.sqrt()
};
Self {
model: ViewModel::Translation,
matrix: [
[1.0, 0.0, shift_px[0]],
[0.0, 1.0, shift_px[1]],
[0.0, 0.0, 1.0],
],
landmarks,
residual_px,
}
}
#[must_use]
pub const fn shift_px(&self) -> [f64; 2] {
[self.matrix[0][2], self.matrix[1][2]]
}
#[must_use]
pub fn apply(&self, [x, y]: [f64; 2]) -> [f64; 2] {
let m = &self.matrix;
let w = m[2][0] * x + m[2][1] * y + m[2][2];
let w = if w.abs() < 1e-12 { 1.0 } else { w };
[
(m[0][0] * x + m[0][1] * y + m[0][2]) / w,
(m[1][0] * x + m[1][1] * y + m[1][2]) / w,
]
}
}
#[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 ViewOutcome {
Unshifted,
Refit,
LandmarksNotFound,
ViewRefitRejected,
FrameMismatch,
}
impl ViewOutcome {
#[must_use]
pub const fn drawable(self) -> bool {
matches!(self, Self::Unshifted | Self::Refit)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FoundLandmark {
pub name: String,
pub located: Located,
}
impl FoundLandmark {
#[must_use]
pub fn distance_px(&self) -> f64 {
self.located.offset_px[0].hypot(self.located.offset_px[1])
}
#[must_use]
pub fn visible(&self) -> bool {
self.located.score >= HIDDEN_BELOW
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ViewJudgement {
pub outcome: ViewOutcome,
pub reason: Option<String>,
pub landmarks: Vec<FoundLandmark>,
}
impl ViewJudgement {
#[must_use]
pub fn agreeing(&self) -> Vec<ReferenceLandmark> {
let visible: Vec<&FoundLandmark> = self.landmarks.iter().filter(|l| l.visible()).collect();
let mut best: Vec<&FoundLandmark> = Vec::new();
let mut best_score = f64::NEG_INFINITY;
let count = visible.len().min(16);
for mask in 1_u32..(1 << count) {
let members: Vec<&FoundLandmark> = (0..count)
.filter(|bit| mask & (1 << bit) != 0)
.map(|bit| visible[bit])
.collect();
let agree = members.iter().enumerate().all(|(i, a)| {
members.iter().skip(i + 1).all(|b| {
(a.located.offset_px[0] - b.located.offset_px[0])
.hypot(a.located.offset_px[1] - b.located.offset_px[1])
<= AGREEMENT_PX
})
});
if !agree {
continue;
}
let score: f64 = members.iter().map(|l| f64::from(l.located.score)).sum();
if members.len() > best.len() || (members.len() == best.len() && score > best_score) {
best = members;
best_score = score;
}
}
best.into_iter()
.map(|landmark| ReferenceLandmark {
name: landmark.name.clone(),
offset_px: landmark.located.offset_px,
score: f64::from(landmark.located.score),
})
.collect()
}
#[must_use]
pub fn moved(&self, calibration: &CameraCalibration) -> bool {
self.landmarks
.iter()
.filter(|l| l.visible() && l.distance_px() > calibration.drift_tolerance_px)
.count()
>= 2
}
}
#[must_use]
pub fn judge_view(
calibration: &CameraCalibration,
frame: &GrayImage,
correction: Option<&ViewCorrection>,
) -> ViewJudgement {
judge_found(calibration, found_landmarks(calibration, frame), correction)
}
#[must_use]
pub fn found_landmarks(calibration: &CameraCalibration, frame: &GrayImage) -> Vec<FoundLandmark> {
calibration
.landmarks
.iter()
.zip(locate_landmarks_within(
calibration,
frame,
VIEW_SEARCH_RADIUS_PX,
))
.map(|(landmark, located)| FoundLandmark {
name: landmark.name.clone(),
located,
})
.collect()
}
#[must_use]
pub fn judge_found(
calibration: &CameraCalibration,
landmarks: Vec<FoundLandmark>,
correction: Option<&ViewCorrection>,
) -> ViewJudgement {
let tolerance = calibration.drift_tolerance_px;
let judged = |outcome: ViewOutcome, reason: Option<String>, landmarks: Vec<FoundLandmark>| {
ViewJudgement {
outcome,
reason,
landmarks,
}
};
let visible = landmarks.iter().filter(|l| l.visible()).count();
let Some(correction) = correction else {
if visible < 2 {
return judged(
ViewOutcome::LandmarksNotFound,
Some(LANDMARKS_NOT_FOUND.to_owned()),
landmarks,
);
}
let furthest = landmarks
.iter()
.filter(|l| l.visible() && l.distance_px() > tolerance)
.max_by(|a, b| a.distance_px().total_cmp(&b.distance_px()));
let moved = landmarks
.iter()
.filter(|l| l.visible() && l.distance_px() > tolerance)
.count();
if moved >= 2
&& let Some(furthest) = furthest
{
let reason = format!(
"the camera has shifted since it was calibrated, {} being {:.1} px from where it was, and no correction taken from this print's first layer is in force yet",
furthest.name,
furthest.distance_px()
);
return judged(ViewOutcome::ViewRefitRejected, Some(reason), landmarks);
}
return judged(ViewOutcome::Unshifted, None, landmarks);
};
let again: Vec<(&ReferenceLandmark, &FoundLandmark)> = correction
.landmarks
.iter()
.filter_map(|reference| {
landmarks
.iter()
.find(|found| found.name == reference.name && found.visible())
.map(|found| (reference, found))
})
.collect();
if again.len() < 2 {
return judged(
ViewOutcome::LandmarksNotFound,
Some(LANDMARKS_NOT_FOUND_AGAIN.to_owned()),
landmarks,
);
}
let from_reference = |(reference, found): &(&ReferenceLandmark, &FoundLandmark)| {
(found.located.offset_px[0] - reference.offset_px[0])
.hypot(found.located.offset_px[1] - reference.offset_px[1])
};
let moved_again: Vec<(&str, f64)> = again
.iter()
.map(|pair| (pair.0.name.as_str(), from_reference(pair)))
.filter(|(_, distance)| *distance > tolerance)
.collect();
if moved_again.len() >= 2 {
let (name, distance) = moved_again
.iter()
.copied()
.fold(
moved_again[0],
|far, next| if next.1 > far.1 { next } else { far },
);
let reason = format!(
"the camera has moved again since this print's first-layer correction was taken: {name} is {distance:.1} px from where that correction's frame had it"
);
return judged(ViewOutcome::ViewRefitRejected, Some(reason), landmarks);
}
let shifted = landmarks
.iter()
.filter(|l| l.visible() && l.distance_px() > tolerance)
.count()
>= 2;
let outcome = if shifted {
ViewOutcome::Refit
} else {
ViewOutcome::Unshifted
};
judged(outcome, None, landmarks)
}
pub const LANDMARKS_NOT_FOUND: &str = "fewer than two of the calibration's landmarks are found in the frame, so whether the camera has shifted is unknown";
pub const LANDMARKS_NOT_FOUND_AGAIN: &str = "fewer than two of the landmarks this print's first-layer correction was taken against are found in the frame, so whether the camera has moved again is unknown";
pub fn landmarks_in_frame(
calibration: &CameraCalibration,
jpeg: &[u8],
camera_snapshot_url: &str,
) -> Result<Vec<FoundLandmark>, ComposeError> {
let frame = decode(jpeg)?;
check_frame(
calibration,
[frame.width(), frame.height()],
camera_snapshot_url,
)?;
Ok(found_landmarks(
calibration,
&image::imageops::grayscale(&frame),
))
}