use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use printobserver_core::check_image::PlanPosition;
use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
use printobserver_panels::growth::MIN_RISE_MM;
use printobserver_panels::{
CameraCalibration, CheckImage, CheckImageInputs, ComposeError, GrowthInputs,
WHOLE_FRAME_HEIGHT, WHOLE_FRAME_WIDTH, compose_check_image, measure_growth, whole_frame,
};
use printobserver_types::{PrintId, Timestamp};
use crate::alignment::{AlignmentFailure, Alignments, CheckedFrame, PreviousCheck, PrintAlignment};
static WRITES: AtomicU64 = AtomicU64::new(0);
pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
#[derive(Debug, Clone)]
pub struct WholeFrames {
directory: PathBuf,
}
impl WholeFrames {
#[must_use]
pub fn under(state_dir: &Path) -> Self {
Self {
directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
}
}
fn destination(&self, frame: &Path) -> PathBuf {
let named = |part: Option<&std::ffi::OsStr>| {
part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
};
let parent = named(frame.parent().and_then(Path::file_name));
let file = named(frame.file_name());
self.directory.join(format!(
"{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
))
}
}
impl CheckImages for WholeFrames {
fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
let destination = self.destination(frame);
if destination.is_file() {
return Ok(destination);
}
let bytes = std::fs::read(frame)
.map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
if !scaled.scaled {
return Ok(frame.to_path_buf());
}
write_image(&self.directory, &destination, &scaled.jpeg)?;
Ok(destination)
}
}
fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
std::fs::create_dir_all(directory)
.map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
let partial = destination.with_extension(format!(
"{}-{}.partial",
std::process::id(),
WRITES.fetch_add(1, Ordering::Relaxed)
));
let written =
std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
written.map_err(|error| {
let _ = std::fs::remove_file(&partial);
format!("{} cannot be written: {error}", destination.display())
})
}
pub const COMPOSITE_NOTE: &str = "the three-panel check image";
pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
#[derive(Debug, Clone, PartialEq)]
pub enum WholeFrameReason {
NoPrint,
NoCalibration,
NoStream,
NoPosition,
NoObject,
NoLayer,
ToolpathUnread(String),
AlignmentPending,
AlignmentUnavailable,
AlignmentFailed(AlignmentFailure),
Refused(ComposeError),
}
impl core::fmt::Display for WholeFrameReason {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::NoPrint => formatter
.write_str("no print is named, so there is no planned toolpath to draw on it"),
Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
Self::NoStream => formatter.write_str(
"no camera snapshot address is configured, so the frame's stream is unknown",
),
Self::NoPosition => formatter.write_str(
"the print's G-code index gives no file position for this check",
),
Self::NoObject => formatter.write_str(
"the print's G-code names no extruded object laid at this point",
),
Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
Self::ToolpathUnread(detail) => write!(
formatter,
"the layer's planned toolpath could not be read from the print's spool: {detail}"
),
Self::AlignmentPending => formatter.write_str(
"the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
),
Self::AlignmentUnavailable => {
formatter.write_str("the print's G-code lays no object to align")
}
Self::AlignmentFailed(AlignmentFailure::Offset { offset_px }) => write!(
formatter,
"the print's first-layer alignment failed: the printed first layer lies {offset_px:.1} px from where the calibration projects it"
),
Self::AlignmentFailed(AlignmentFailure::Resolution { expected, got }) => write!(
formatter,
"the print's first-layer alignment failed: the camera's frames are {}x{} and the calibration's {}x{}",
got[0], got[1], expected[0], expected[1]
),
Self::AlignmentFailed(AlignmentFailure::Stream) => formatter.write_str(
"the print's first-layer alignment failed: the camera is not the stream the calibration was fitted on",
),
Self::Refused(error) => error.fmt(formatter),
}
}
}
#[must_use]
pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
format!(
"{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}"
)
}
const CAMERA_HOLDS: &str = "the camera does not shift in regular operation and the drawing already accounts for the bed's travel, so ";
#[must_use]
pub fn composite_note(
made_for: ImageUse,
current_at: Timestamp,
previous_at: Option<Timestamp>,
) -> String {
let (current, previous, moved) = match (made_for, previous_at) {
(ImageUse::Look, at) => (
"this layer's planned toolpath drawn on the frame".to_owned(),
if at.is_none() {
"panel 3 empty, no earlier check's frame being at hand".to_owned()
} else {
"panel 3 the previous check's frame".to_owned()
},
String::new(),
),
(ImageUse::Check, None) => (
format!(
"this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
),
"panel 3 empty, no earlier check's frame being at hand".to_owned(),
format!(
"; {CAMERA_HOLDS}a part off its drawn walls in panel 1 has moved unless there is strong evidence otherwise, and no later frame undoes that"
),
),
(ImageUse::Check, Some(at)) => (
format!(
"this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
),
format!("panel 3 the previous check's frame, captured {at}"),
format!(
"; {CAMERA_HOLDS}a part off its drawn walls in panel 1, or moved since panel 3, has moved unless there is strong evidence otherwise, and no later frame undoes that"
),
),
};
format!(
"{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part being printed, {previous}{moved}",
printobserver_panels::compose::PANEL_WIDTH,
printobserver_panels::compose::IMAGE_HEIGHT
)
}
#[must_use]
pub fn not_grown_note(since: Timestamp, rise_mm: f64) -> String {
format!(
"; measured against the check frame captured {since}, {rise_mm:.1} mm lower in the plan: the parts this layer lays have not risen as planned, sitting where that frame had them, carried down with the bed, so nothing has been laid on them since"
)
}
fn plan_z(plan: &PlanPosition) -> Option<f64> {
plan.index
.layer_at(plan.file_position_bytes)
.and_then(|layer| plan.index.layer_z_mm(layer))
}
#[derive(Debug, Clone, Copy)]
pub struct PlanAt<'a> {
pub index: &'a GcodeIndex,
pub file_position_bytes: u64,
}
pub fn compose_at(
plan: PlanAt<'_>,
current: (&[u8], Timestamp),
previous: Option<(&[u8], Timestamp)>,
camera_snapshot_url: &str,
calibration: &CameraCalibration,
) -> Result<CheckImage, WholeFrameReason> {
let index = plan.index;
let position = plan.file_position_bytes;
let active_object = index
.object_at(position)
.filter(|object| *object < index.object_outlines().len())
.ok_or(WholeFrameReason::NoObject)?;
let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
let unread =
|error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
let toolpath = index.layer_toolpath(layer).map_err(unread)?;
let below = if toolpath.carries_object_extrusion() {
None
} else {
index
.object_layer_at_or_below(layer)
.map(|below| index.layer_toolpath(below))
.transpose()
.map_err(unread)?
};
compose_check_image(&CheckImageInputs {
current_jpeg: current.0,
current_at: current.1,
camera_snapshot_url,
previous,
outlines: index.object_outlines(),
active_object,
toolpath: &toolpath,
object_layer_below: below.as_ref(),
print_z_mm,
calibration,
})
.map_err(WholeFrameReason::Refused)
}
pub struct PanelImages {
whole: WholeFrames,
alignments: Arc<Alignments>,
camera_snapshot_url: Option<String>,
}
impl core::fmt::Debug for PanelImages {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("PanelImages")
.field("whole", &self.whole)
.field("camera_snapshot_url", &self.camera_snapshot_url)
.finish_non_exhaustive()
}
}
impl PanelImages {
#[must_use]
pub fn new(
state_dir: &Path,
alignments: Arc<Alignments>,
camera_snapshot_url: Option<String>,
) -> Self {
Self {
whole: WholeFrames::under(state_dir),
alignments,
camera_snapshot_url,
}
}
fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
Ok(ShownImage {
path: self.whole.check_image(None, frame)?,
note: Some(whole_frame_note(reason)),
composite: false,
})
}
fn composite(
&self,
print_id: PrintId,
request: &CheckImageRequest<'_>,
previous: Option<&PreviousCheck>,
) -> Result<Result<ShownImage, WholeFrameReason>, String> {
let Some(calibration) = self.alignments.calibration() else {
return Ok(Err(WholeFrameReason::NoCalibration));
};
let Some(url) = self.camera_snapshot_url.as_deref() else {
return Ok(Err(WholeFrameReason::NoStream));
};
let Some(plan) = &request.plan else {
return Ok(Err(WholeFrameReason::NoPosition));
};
let at = PlanAt {
index: &plan.index,
file_position_bytes: plan.file_position_bytes,
};
if at.index.object_at(at.file_position_bytes).is_none()
|| at.index.object_outlines().is_empty()
{
return Ok(Err(WholeFrameReason::NoObject));
}
if at.index.layer_at(at.file_position_bytes).is_none() {
return Ok(Err(WholeFrameReason::NoLayer));
}
match self.alignments.print_alignment(print_id) {
PrintAlignment::Passed { .. } => {}
PrintAlignment::Pending => return Ok(Err(WholeFrameReason::AlignmentPending)),
PrintAlignment::Unavailable => {
return Ok(Err(WholeFrameReason::AlignmentUnavailable));
}
PrintAlignment::Failed { reason } => {
return Ok(Err(WholeFrameReason::AlignmentFailed(reason)));
}
}
let current = std::fs::read(request.frame)
.map_err(|error| format!("{} is unreadable: {error}", request.frame.display()))?;
let earlier = previous.and_then(|check| {
std::fs::read(&check.frame)
.ok()
.filter(|bytes| whole_frame(bytes).is_ok())
.map(|bytes| (bytes, check.captured_at))
});
let composed = match compose_at(
at,
(¤t, request.captured_at),
earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
url,
calibration,
) {
Ok(composed) => composed,
Err(WholeFrameReason::Refused(
ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
)) => return Err(detail),
Err(reason) => return Ok(Err(reason)),
};
let destination = self.composite_destination(request.frame, previous);
write_image(&self.whole.directory, &destination, &composed.jpeg)?;
let mut note = composite_note(
request.made_for,
request.captured_at,
earlier.as_ref().map(|(_, at)| *at),
);
if request.made_for == ImageUse::Check
&& let Some(clause) = self.growth_clause(print_id, plan, ¤t, url, calibration)
{
note.push_str(&clause);
}
Ok(Ok(ShownImage {
path: destination,
note: Some(note),
composite: true,
}))
}
fn growth_clause(
&self,
print_id: PrintId,
plan: &PlanPosition,
current: &[u8],
url: &str,
calibration: &CameraCalibration,
) -> Option<String> {
let layer = plan.index.layer_at(plan.file_position_bytes)?;
let print_z_mm = plan.index.layer_z_mm(layer)?;
let reference = self
.alignments
.growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
let earlier = std::fs::read(&reference.frame).ok()?;
let toolpath = plan.index.layer_toolpath(layer).ok()?;
let measured = measure_growth(&GrowthInputs {
earlier_jpeg: &earlier,
earlier_print_z_mm: reference.print_z_mm,
current_jpeg: current,
current_print_z_mm: print_z_mm,
camera_snapshot_url: url,
toolpath: &toolpath,
calibration,
})
.ok()??;
let not_grown = measured.not_grown();
eprintln!(
"printobserver: print {print_id}: growth from Z {:.1} ({}) to Z {print_z_mm:.1}: carried {:.2}, held {:.2}, {:.0}% carried over {} samples {:.1} px apart: {}",
reference.print_z_mm,
reference.captured_at,
measured.carried,
measured.held,
measured.carried_share * 100.0,
measured.samples,
measured.separation_px,
if not_grown { "not grown" } else { "no verdict" }
);
not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
}
fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
let named = |frame: &Path| {
let part = |part: Option<&std::ffi::OsStr>| {
part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
};
format!(
"{}-{}",
part(frame.parent().and_then(Path::file_name)),
part(frame.file_name())
)
};
let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
self.whole
.directory
.join(format!("{}-composite-after-{after}.jpg", named(frame)))
}
}
impl CheckImages for PanelImages {
fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
self.whole.check_image(print_id, frame)
}
fn composes(&self, print_id: PrintId) -> bool {
self.alignments.calibration().is_some()
&& self.camera_snapshot_url.is_some()
&& matches!(
self.alignments.print_alignment(print_id),
PrintAlignment::Passed { .. }
)
}
fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
let Some(print_id) = request.print_id else {
return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
};
let previous = self.alignments.previous_check(print_id);
let shown = match self.composite(print_id, request, previous.as_ref())? {
Ok(composite) => composite,
Err(reason) => self.whole_frame(request.frame, &reason)?,
};
if request.made_for == ImageUse::Check {
self.alignments.record_check(
print_id,
&PreviousCheck {
frame: request.frame.to_path_buf(),
captured_at: request.captured_at,
},
);
if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
self.alignments.record_checked_frame(
print_id,
CheckedFrame {
frame: request.frame.to_path_buf(),
captured_at: request.captured_at,
print_z_mm,
},
MIN_RISE_MM,
);
}
}
Ok(shown)
}
}