use image::{Rgb, RgbImage, imageops::FilterType};
use imageproc::drawing::draw_filled_rect_mut;
use imageproc::rect::Rect;
use printobserver_core::{LayerFacts, LayerToolpath, ObjectOutline};
use printobserver_types::Timestamp;
use crate::calibration::CameraCalibration;
use crate::drift::{check_drift, check_frame};
use crate::error::ComposeError;
use crate::geometry::project_toolpath;
use crate::occlusion::Occluders;
use crate::panel_one;
use crate::text::draw_text;
use crate::view::ViewCorrection;
pub const PANEL_WIDTH: u32 = 1024;
pub const PANEL_HEIGHT: u32 = 576;
pub const BAND_HEIGHT: u32 = 40;
pub const PREVIOUS_WIDTH: u32 = 576;
pub const PREVIOUS_HEIGHT: u32 = 324;
pub const IMAGE_HEIGHT: u32 = 2 * (BAND_HEIGHT + PANEL_HEIGHT) + PREVIOUS_HEIGHT;
pub const MARGIN_PX: f64 = 48.0;
pub const MIN_CROP_WIDTH_PX: f64 = 512.0;
const QUALITY: u8 = 90;
pub const NO_EARLIER_CHECK: &str = "no earlier check this print";
pub const BELOW_GREY: Rgb<u8> = Rgb([150, 150, 150]);
const BAND: Rgb<u8> = Rgb([24, 24, 24]);
const TEXT: Rgb<u8> = Rgb([235, 235, 235]);
pub use crate::panel_one::colour_of;
#[derive(Debug, Clone, Copy)]
pub struct CheckImageInputs<'a> {
pub current_jpeg: &'a [u8],
pub current_at: Timestamp,
pub camera_snapshot_url: &'a str,
pub previous: Option<(&'a [u8], Timestamp)>,
pub outlines: &'a [ObjectOutline],
pub active_object: usize,
pub toolpath: &'a LayerToolpath,
pub object_layer_below: Option<&'a LayerToolpath>,
pub print_z_mm: f64,
pub calibration: &'a CameraCalibration,
pub correction: Option<&'a ViewCorrection>,
pub file_position_bytes: Option<u64>,
pub facts: Option<&'a LayerFacts>,
pub head_trail_mm: &'a [[f64; 2]],
pub reported_head_mm: Option<[f64; 2]>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckImage {
pub jpeg: Vec<u8>,
pub width: u32,
pub height: u32,
pub close_up_source_rect: [u32; 4],
pub text: Vec<String>,
}
pub(crate) fn decode(jpeg: &[u8]) -> Result<RgbImage, ComposeError> {
image::load_from_memory_with_format(jpeg, image::ImageFormat::Jpeg)
.map(|frame| frame.to_rgb8())
.map_err(|error| ComposeError::Undecodable {
detail: error.to_string(),
})
}
pub fn compose_check_image(inputs: &CheckImageInputs<'_>) -> Result<CheckImage, ComposeError> {
let current = decode(inputs.current_jpeg)?;
let size = [current.width(), current.height()];
check_frame(inputs.calibration, size, inputs.camera_snapshot_url)?;
if inputs.correction.is_none() {
check_drift(inputs.calibration, &image::imageops::grayscale(¤t))?;
}
let previous = inputs
.previous
.map(|(jpeg, at)| decode(jpeg).map(|frame| (frame, at)))
.transpose()?;
if let Some((frame, _)) = &previous {
check_frame(
inputs.calibration,
[frame.width(), frame.height()],
inputs.camera_snapshot_url,
)?;
}
let (drawn, below) = drawn_pieces(inputs);
let rect = close_up_rect(inputs, size);
let in_frame = |[x, y]: [f64; 2]| {
(0.0..f64::from(size[0])).contains(&x) && (0.0..f64::from(size[1])).contains(&y)
};
if rect.is_none() && !drawn.iter().chain(&below).any(|piece| in_frame(piece.from)) {
return Err(ComposeError::OutlineOffFrame);
}
let rect = rect.unwrap_or_else(|| whole_width_rect(size));
let mut image = RgbImage::from_pixel(PANEL_WIDTH, IMAGE_HEIGHT, BAND);
let scale = f64::from(PANEL_WIDTH) / f64::from(size[0]);
let scale_y = f64::from(PANEL_HEIGHT) / f64::from(size[1]);
let (whole, text) = first_panel(inputs, ¤t, &drawn, &below, [scale, scale_y]);
paste(&mut image, &whole, 0);
band(
&mut image,
0,
"1 NOW: this layer's plan, sent bold, to print grey",
);
paste(&mut image, &scaled(¤t, Some(rect)), 1);
band(&mut image, 1, "2 NOW: close-up, nothing drawn");
let third = panel_top(2);
if let Some((frame, at)) = &previous {
let whole =
image::imageops::resize(frame, PREVIOUS_WIDTH, PREVIOUS_HEIGHT, FilterType::Triangle);
image::imageops::replace(&mut image, &whole, 0, i64::from(third));
let local = at.as_utc().with_timezone(&chrono::Local).format("%H:%M:%S");
beside_panel_three(
&mut image,
&[
"3 PREVIOUS CHECK",
&local.to_string(),
"whole view,",
"nothing drawn",
],
);
} else {
draw_filled_rect_mut(
&mut image,
Rect::at(0, signed(third)).of_size(PREVIOUS_WIDTH, PREVIOUS_HEIGHT),
Rgb([48, 48, 48]),
);
draw_text(
&mut image,
TEXT,
40,
signed(third + PREVIOUS_HEIGHT / 2 - 16),
32.0,
NO_EARLIER_CHECK,
);
beside_panel_three(&mut image, &["3 PREVIOUS CHECK:", "none"]);
}
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, QUALITY)
.encode_image(&image)
.map_err(|error| ComposeError::Encode {
detail: error.to_string(),
})?;
Ok(CheckImage {
jpeg,
width: PANEL_WIDTH,
height: IMAGE_HEIGHT,
close_up_source_rect: rect,
text,
})
}
fn first_panel(
inputs: &CheckImageInputs<'_>,
current: &RgbImage,
drawn: &[crate::geometry::Projected],
below: &[crate::geometry::Projected],
[scale, scale_y]: [f64; 2],
) -> (RgbImage, Vec<String>) {
let mut whole = scaled(current, None);
let occluders = Occluders::along(inputs.calibration, inputs.head_trail_mm);
let projector = inputs.calibration.projector();
let project = |[x, y]: [f64; 2]| {
projector
.pixel([x, y, 0.0])
.map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
};
let reported_head_px = inputs.reported_head_mm.and_then(project);
let painted = panel_one::draw(
&mut whole,
&panel_one::Plan {
drawn,
below,
file_position_bytes: inputs.file_position_bytes,
occluders: occluders.as_ref(),
reported_head_px,
scale: [scale, scale_y],
project: &project,
},
);
let text = panel_one::lines(
inputs.facts,
occluders.as_ref().map(Occluders::span_mm),
painted,
reported_head_px.is_some(),
);
(whole, text)
}
fn drawn_pieces(
inputs: &CheckImageInputs<'_>,
) -> (
Vec<crate::geometry::Projected>,
Vec<crate::geometry::Projected>,
) {
let projector = inputs.calibration.projector();
let corrected = |mut pieces: Vec<crate::geometry::Projected>| {
if let Some(correction) = inputs.correction {
for piece in &mut pieces {
piece.from = correction.apply(piece.from);
piece.to = correction.apply(piece.to);
}
}
pieces
};
let drawn = corrected(project_toolpath(
&projector,
inputs.toolpath,
inputs.print_z_mm,
));
let below = inputs
.object_layer_below
.map(|layer| corrected(project_toolpath(&projector, layer, inputs.print_z_mm)))
.unwrap_or_default();
(drawn, below)
}
fn signed(value: u32) -> i32 {
i32::try_from(value).unwrap_or(i32::MAX)
}
#[must_use]
pub const fn band_top(panel: u32) -> u32 {
match panel {
0 => 0,
1 => BAND_HEIGHT + PANEL_HEIGHT,
_ => panel_top(2),
}
}
#[must_use]
pub const fn panel_top(panel: u32) -> u32 {
match panel {
0 => BAND_HEIGHT,
1 => band_top(1) + BAND_HEIGHT,
_ => panel_top(1) + PANEL_HEIGHT,
}
}
fn paste(image: &mut RgbImage, panel: &RgbImage, n: u32) {
image::imageops::replace(image, panel, 0, i64::from(panel_top(n)));
}
fn scaled(frame: &RgbImage, rect: Option<[u32; 4]>) -> RgbImage {
let source = match rect {
Some([x, y, w, h]) => image::imageops::crop_imm(frame, x, y, w, h).to_image(),
None => frame.clone(),
};
image::imageops::resize(&source, PANEL_WIDTH, PANEL_HEIGHT, FilterType::Triangle)
}
fn band(image: &mut RgbImage, n: u32, text: &str) {
draw_text(image, TEXT, 8, signed(band_top(n)) + 9, 20.0, text);
}
fn beside_panel_three(image: &mut RgbImage, lines: &[&str]) {
let mut y = signed(panel_top(2)) + 9;
for line in lines {
draw_text(image, TEXT, signed(PREVIOUS_WIDTH) + 10, y, 20.0, line);
y += 28;
}
}
fn whole_width_rect(size: [u32; 2]) -> [u32; 4] {
fit_rect([0.0, 0.0, f64::from(size[0]), f64::from(size[1])], size)
}
fn close_up_rect(inputs: &CheckImageInputs<'_>, size: [u32; 2]) -> Option<[u32; 4]> {
let outline = inputs.outlines.get(inputs.active_object)?;
let projector = inputs.calibration.projector();
let points: Vec<[f64; 2]> = outline
.hull_mm
.iter()
.flat_map(|vertex| {
let (x, y) = (f64::from(vertex[0]), f64::from(vertex[1]));
[
projector.pixel([x, y, -inputs.print_z_mm]),
projector.pixel([x, y, 0.0]),
]
})
.flatten()
.map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
.collect();
let first = points.first()?;
let (mut x0, mut y0, mut x1, mut y1) = (first[0], first[1], first[0], first[1]);
for [x, y] in &points {
x0 = x0.min(*x);
y0 = y0.min(*y);
x1 = x1.max(*x);
y1 = y1.max(*y);
}
let (w, h) = (f64::from(size[0]), f64::from(size[1]));
if x1 < 0.0 || y1 < 0.0 || x0 >= w || y0 >= h {
return None;
}
Some(fit_rect(
[
x0 - MARGIN_PX,
y0 - MARGIN_PX,
x1 + MARGIN_PX,
y1 + MARGIN_PX,
],
size,
))
}
fn fit_rect(bounds: [f64; 4], size: [u32; 2]) -> [u32; 4] {
let (frame_w, frame_h) = (f64::from(size[0]), f64::from(size[1]));
let centre = [
f64::midpoint(bounds[0], bounds[2]),
f64::midpoint(bounds[1], bounds[3]),
];
let mut width = (bounds[2] - bounds[0])
.max((bounds[3] - bounds[1]) * 16.0 / 9.0)
.max(MIN_CROP_WIDTH_PX);
width = width.min(frame_w).min(frame_h * 16.0 / 9.0);
let height = width * 9.0 / 16.0;
let x = (centre[0] - width / 2.0).clamp(0.0, frame_w - width);
let y = (centre[1] - height / 2.0).clamp(0.0, frame_h - height);
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "each is clamped inside the frame, whose size fits a u32"
)]
let whole = |value: f64| value.round() as u32;
let (rx, ry) = (whole(x), whole(y));
let rw = whole(width).min(size[0] - rx);
let rh = whole(height).min(size[1] - ry);
[rx, ry, rw, rh]
}