Skip to main content

printobserver_panels/
compose.rs

1//! The check image, as one JPEG: panels 1 and 2 at 1024x576, each under a
2//! 40 px label band; and under them panel 3 at
3//! [`PREVIOUS_WIDTH`]x[`PREVIOUS_HEIGHT`], its label in the column beside it.
4//! Panel 3 is nine sixteenths of a full panel's width, the least that still
5//! shows a part's place beside panel 1, so that the image costs a turn fewer
6//! image tokens than the three full panels it replaced. The image carries no
7//! text of the layer's: what panel 1's drawing means is told in the turn's
8//! own text, from [`CheckImage::text`].
9//!
10//! 1. The current frame scaled whole, the current layer's whole plan drawn
11//!    over it ([`crate::panel_one`]): what the job has sent bold in each
12//!    kind's colour, what it has still to send thin and grey, thin dashes
13//!    where the head or gantry may stand, and — when that layer lays supports
14//!    alone — the nearest object layer below it in grey beneath, so the part
15//!    still shows. The turn's text says the layer, its colour, the planned
16//!    change nearest it, how far through it the job is, what is hidden, and
17//!    what each colour drawn means.
18//! 2. The current frame cropped to the active object's outline projected at
19//!    the bed and at the current height, with a [`MARGIN_PX`] margin, widened
20//!    to 16:9, never narrower than [`MIN_CROP_WIDTH_PX`] (so upscaled at most
21//!    2x), clamped inside the frame; nothing drawn.
22//! 3. The previous check's frame scaled whole, nothing drawn, or a
23//!    placeholder on the print's first check.
24
25use image::{Rgb, RgbImage, imageops::FilterType};
26use imageproc::drawing::draw_filled_rect_mut;
27use imageproc::rect::Rect;
28use printobserver_core::{LayerFacts, LayerToolpath, ObjectOutline};
29use printobserver_types::Timestamp;
30
31use crate::calibration::CameraCalibration;
32use crate::drift::{check_drift, check_frame};
33use crate::error::ComposeError;
34use crate::geometry::project_toolpath;
35use crate::occlusion::Occluders;
36use crate::panel_one;
37use crate::text::draw_text;
38use crate::view::ViewCorrection;
39
40/// A panel's width.
41pub const PANEL_WIDTH: u32 = 1024;
42/// A panel's height.
43pub const PANEL_HEIGHT: u32 = 576;
44/// The label band above each panel.
45pub const BAND_HEIGHT: u32 = 40;
46/// Panel 3's width: the previous check's frame, scaled whole.
47pub const PREVIOUS_WIDTH: u32 = 576;
48/// Panel 3's height.
49pub const PREVIOUS_HEIGHT: u32 = 324;
50/// The whole image's height: panels 1 and 2 under their bands, and panel 3,
51/// whose label stands beside it.
52pub const IMAGE_HEIGHT: u32 = 2 * (BAND_HEIGHT + PANEL_HEIGHT) + PREVIOUS_HEIGHT;
53/// The close-up's margin around the active object, in source pixels.
54pub const MARGIN_PX: f64 = 48.0;
55/// The close-up's least width, in source pixels.
56pub const MIN_CROP_WIDTH_PX: f64 = 512.0;
57/// The JPEG quality the image is written at.
58const QUALITY: u8 = 90;
59/// What panel 3 reads on a print's first check.
60pub const NO_EARLIER_CHECK: &str = "no earlier check this print";
61
62/// The grey the nearest object layer below a support-only layer is drawn in.
63pub const BELOW_GREY: Rgb<u8> = Rgb([150, 150, 150]);
64/// The label bands' background.
65const BAND: Rgb<u8> = Rgb([24, 24, 24]);
66/// The label text.
67const TEXT: Rgb<u8> = Rgb([235, 235, 235]);
68
69pub use crate::panel_one::colour_of;
70
71/// What the check image is composed from.
72#[derive(Debug, Clone, Copy)]
73pub struct CheckImageInputs<'a> {
74    /// The frame this check was given.
75    pub current_jpeg: &'a [u8],
76    /// When it was captured. Panel 1 is always the frame being checked, so
77    /// its label names no time; the field is the one the previous frame's
78    /// label is read against by the check that keeps both.
79    pub current_at: Timestamp,
80    /// The snapshot URL it came from.
81    pub camera_snapshot_url: &'a str,
82    /// The previous check's frame and when it was captured; absent on the
83    /// print's first check.
84    pub previous: Option<(&'a [u8], Timestamp)>,
85    /// Every object's outline.
86    pub outlines: &'a [ObjectOutline],
87    /// The object being laid, an index into `outlines`.
88    pub active_object: usize,
89    /// The current layer's toolpath.
90    pub toolpath: &'a LayerToolpath,
91    /// The nearest object layer below, given when `toolpath` lays supports
92    /// alone.
93    pub object_layer_below: Option<&'a LayerToolpath>,
94    /// The print's height, in millimetres.
95    pub print_z_mm: f64,
96    /// The printer's calibration.
97    pub calibration: &'a CameraCalibration,
98    /// The correction every drawn pixel goes through, taken from this print's
99    /// own first layer. With one, the caller has judged the frame's view
100    /// against its reference, and the composer judges no drift of its own;
101    /// with none, the composer refuses a frame the drift check refuses.
102    pub correction: Option<&'a ViewCorrection>,
103    /// The job's file position, counted in the print's own spooled copy of
104    /// its file: what splits the layer into sent and still to send. With
105    /// none, the whole layer is drawn as sent.
106    pub file_position_bytes: Option<u64>,
107    /// What the turn's text says of the layer, when the index answers it.
108    pub facts: Option<&'a LayerFacts>,
109    /// Where the plan has had the nozzle over the moves the printer may still
110    /// hold queued, in bed millimetres: where the head and gantry may stand.
111    /// Empty when that is not known.
112    pub head_trail_mm: &'a [[f64; 2]],
113    /// Where the printer reported the head, in bed millimetres: the only
114    /// place a head mark is drawn at.
115    pub reported_head_mm: Option<[f64; 2]>,
116}
117
118/// The composed check image.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct CheckImage {
121    /// The JPEG.
122    pub jpeg: Vec<u8>,
123    /// Its width: [`PANEL_WIDTH`].
124    pub width: u32,
125    /// Its height: [`IMAGE_HEIGHT`].
126    pub height: u32,
127    /// Panel 2's source, `[x, y, w, h]` in current-frame pixels.
128    pub close_up_source_rect: [u32; 4],
129    /// What panel 1's drawing shows, in lines a check's turn is told: the
130    /// layer's facts, what is hidden, and what each colour drawn means.
131    pub text: Vec<String>,
132}
133
134/// Decode a frame: a JPEG, as a camera serves one, or a PNG, as a lossless
135/// frame derived from one is kept. Anything else is undecodable.
136pub(crate) fn decode(frame: &[u8]) -> Result<RgbImage, ComposeError> {
137    let format = if frame.starts_with(b"\x89PNG\r\n\x1a\n") {
138        image::ImageFormat::Png
139    } else {
140        image::ImageFormat::Jpeg
141    };
142    image::load_from_memory_with_format(frame, format)
143        .map(|frame| frame.to_rgb8())
144        .map_err(|error| ComposeError::Undecodable {
145            detail: error.to_string(),
146        })
147}
148
149/// Compose the check image.
150///
151/// # Errors
152///
153/// In the order they are checked: [`ComposeError::Undecodable`] for a frame
154/// that is no JPEG; [`ComposeError::FrameMismatch`] for a current or previous
155/// frame of another size, or a stream, other than the calibration's;
156/// [`ComposeError::CameraMoved`] or [`ComposeError::DriftUnverified`] from
157/// the drift check; and
158/// [`ComposeError::OutlineOffFrame`] when neither the toolpath nor the active
159/// object lands in the frame.
160pub fn compose_check_image(inputs: &CheckImageInputs<'_>) -> Result<CheckImage, ComposeError> {
161    let current = decode(inputs.current_jpeg)?;
162    let size = [current.width(), current.height()];
163    check_frame(inputs.calibration, size, inputs.camera_snapshot_url)?;
164    if inputs.correction.is_none() {
165        check_drift(inputs.calibration, &image::imageops::grayscale(&current))?;
166    }
167    let previous = inputs
168        .previous
169        .map(|(jpeg, at)| decode(jpeg).map(|frame| (frame, at)))
170        .transpose()?;
171    if let Some((frame, _)) = &previous {
172        // Panel 3 is scaled by the current frame's factors, so a previous
173        // frame of another size would be drawn distorted rather than refused.
174        check_frame(
175            inputs.calibration,
176            [frame.width(), frame.height()],
177            inputs.camera_snapshot_url,
178        )?;
179    }
180
181    let (drawn, below) = drawn_pieces(inputs);
182    let rect = close_up_rect(inputs, size);
183    let in_frame = |[x, y]: [f64; 2]| {
184        (0.0..f64::from(size[0])).contains(&x) && (0.0..f64::from(size[1])).contains(&y)
185    };
186    if rect.is_none() && !drawn.iter().chain(&below).any(|piece| in_frame(piece.from)) {
187        return Err(ComposeError::OutlineOffFrame);
188    }
189    let rect = rect.unwrap_or_else(|| whole_width_rect(size));
190
191    let mut image = RgbImage::from_pixel(PANEL_WIDTH, IMAGE_HEIGHT, BAND);
192    let scale = f64::from(PANEL_WIDTH) / f64::from(size[0]);
193    let scale_y = f64::from(PANEL_HEIGHT) / f64::from(size[1]);
194
195    let (whole, text) = first_panel(inputs, &current, &drawn, &below, [scale, scale_y]);
196    paste(&mut image, &whole, 0);
197    band(
198        &mut image,
199        0,
200        "1 NOW: this layer's plan, sent bold, to print grey",
201    );
202
203    paste(&mut image, &scaled(&current, Some(rect)), 1);
204    band(&mut image, 1, "2 NOW: close-up, nothing drawn");
205
206    let third = panel_top(2);
207    if let Some((frame, at)) = &previous {
208        let whole =
209            image::imageops::resize(frame, PREVIOUS_WIDTH, PREVIOUS_HEIGHT, FilterType::Triangle);
210        image::imageops::replace(&mut image, &whole, 0, i64::from(third));
211        let local = at.as_utc().with_timezone(&chrono::Local).format("%H:%M:%S");
212        beside_panel_three(
213            &mut image,
214            &[
215                "3 PREVIOUS CHECK",
216                &local.to_string(),
217                "whole view,",
218                "nothing drawn",
219            ],
220        );
221    } else {
222        draw_filled_rect_mut(
223            &mut image,
224            Rect::at(0, signed(third)).of_size(PREVIOUS_WIDTH, PREVIOUS_HEIGHT),
225            Rgb([48, 48, 48]),
226        );
227        draw_text(
228            &mut image,
229            TEXT,
230            40,
231            signed(third + PREVIOUS_HEIGHT / 2 - 16),
232            32.0,
233            NO_EARLIER_CHECK,
234        );
235        beside_panel_three(&mut image, &["3 PREVIOUS CHECK:", "none"]);
236    }
237
238    let mut jpeg = Vec::new();
239    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, QUALITY)
240        .encode_image(&image)
241        .map_err(|error| ComposeError::Encode {
242            detail: error.to_string(),
243        })?;
244    Ok(CheckImage {
245        jpeg,
246        width: PANEL_WIDTH,
247        height: IMAGE_HEIGHT,
248        close_up_source_rect: rect,
249        text,
250    })
251}
252
253/// Panel 1: the current frame scaled whole with the layer's plan drawn over
254/// it, and the lines its turn is told of it.
255fn first_panel(
256    inputs: &CheckImageInputs<'_>,
257    current: &RgbImage,
258    drawn: &[crate::geometry::Projected],
259    below: &[crate::geometry::Projected],
260    [scale, scale_y]: [f64; 2],
261) -> (RgbImage, Vec<String>) {
262    let mut whole = scaled(current, None);
263    let occluders = Occluders::along(inputs.calibration, inputs.head_trail_mm);
264    let projector = inputs.calibration.projector();
265    let project = |[x, y]: [f64; 2]| {
266        projector
267            .pixel([x, y, 0.0])
268            .map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
269    };
270    let reported_head_px = inputs.reported_head_mm.and_then(project);
271    let painted = panel_one::draw(
272        &mut whole,
273        &panel_one::Plan {
274            drawn,
275            below,
276            file_position_bytes: inputs.file_position_bytes,
277            occluders: occluders.as_ref(),
278            reported_head_px,
279            scale: [scale, scale_y],
280            project: &project,
281        },
282    );
283    let text = panel_one::lines(
284        inputs.facts,
285        occluders.as_ref().map(Occluders::span_mm),
286        painted,
287        reported_head_px.is_some(),
288    );
289    (whole, text)
290}
291
292/// The current layer's toolpath and, when it lays supports alone, the object
293/// layer below, projected and taken through the correction when there is one.
294fn drawn_pieces(
295    inputs: &CheckImageInputs<'_>,
296) -> (
297    Vec<crate::geometry::Projected>,
298    Vec<crate::geometry::Projected>,
299) {
300    let projector = inputs.calibration.projector();
301    let corrected = |mut pieces: Vec<crate::geometry::Projected>| {
302        if let Some(correction) = inputs.correction {
303            for piece in &mut pieces {
304                piece.from = correction.apply(piece.from);
305                piece.to = correction.apply(piece.to);
306            }
307        }
308        pieces
309    };
310    let drawn = corrected(project_toolpath(
311        &projector,
312        inputs.toolpath,
313        inputs.print_z_mm,
314    ));
315    let below = inputs
316        .object_layer_below
317        .map(|layer| corrected(project_toolpath(&projector, layer, inputs.print_z_mm)))
318        .unwrap_or_default();
319    (drawn, below)
320}
321
322/// A pixel row as the drawing calls take it.
323fn signed(value: u32) -> i32 {
324    i32::try_from(value).unwrap_or(i32::MAX)
325}
326
327/// Where panel `n`'s label starts: panel 1's band at the top, panel 2's below
328/// panel 1, and panel 3's in the column beside panel 3, level with its top.
329#[must_use]
330pub const fn band_top(panel: u32) -> u32 {
331    match panel {
332        0 => 0,
333        1 => BAND_HEIGHT + PANEL_HEIGHT,
334        _ => panel_top(2),
335    }
336}
337
338/// Where panel `n` itself starts: panels 1 and 2 under their bands, and
339/// panel 3 straight under panel 2.
340#[must_use]
341pub const fn panel_top(panel: u32) -> u32 {
342    match panel {
343        0 => BAND_HEIGHT,
344        1 => band_top(1) + BAND_HEIGHT,
345        _ => panel_top(1) + PANEL_HEIGHT,
346    }
347}
348
349/// Copy a panel under its band.
350fn paste(image: &mut RgbImage, panel: &RgbImage, n: u32) {
351    image::imageops::replace(image, panel, 0, i64::from(panel_top(n)));
352}
353
354/// A frame, or a rectangle of it, scaled to one panel.
355fn scaled(frame: &RgbImage, rect: Option<[u32; 4]>) -> RgbImage {
356    let source = match rect {
357        Some([x, y, w, h]) => image::imageops::crop_imm(frame, x, y, w, h).to_image(),
358        None => frame.clone(),
359    };
360    image::imageops::resize(&source, PANEL_WIDTH, PANEL_HEIGHT, FilterType::Triangle)
361}
362
363/// One label band's text.
364fn band(image: &mut RgbImage, n: u32, text: &str) {
365    draw_text(image, TEXT, 8, signed(band_top(n)) + 9, 20.0, text);
366}
367
368/// Panel 3's label, one line under another in the column beside it.
369fn beside_panel_three(image: &mut RgbImage, lines: &[&str]) {
370    let mut y = signed(panel_top(2)) + 9;
371    for line in lines {
372        draw_text(image, TEXT, signed(PREVIOUS_WIDTH) + 10, y, 20.0, line);
373        y += 28;
374    }
375}
376
377/// The whole frame's width at 16:9, centred: what panel 2 shows when the
378/// active object lands nowhere in the frame.
379fn whole_width_rect(size: [u32; 2]) -> [u32; 4] {
380    fit_rect([0.0, 0.0, f64::from(size[0]), f64::from(size[1])], size)
381}
382
383/// The close-up's source rectangle: the box holding the active object's
384/// outline projected at the bed and at the current height, with its margin,
385/// widened to 16:9 and to the least width, clamped inside the frame. Nothing
386/// when no vertex of the outline projects at all.
387fn close_up_rect(inputs: &CheckImageInputs<'_>, size: [u32; 2]) -> Option<[u32; 4]> {
388    let outline = inputs.outlines.get(inputs.active_object)?;
389    let projector = inputs.calibration.projector();
390    let points: Vec<[f64; 2]> = outline
391        .hull_mm
392        .iter()
393        .flat_map(|vertex| {
394            let (x, y) = (f64::from(vertex[0]), f64::from(vertex[1]));
395            [
396                projector.pixel([x, y, -inputs.print_z_mm]),
397                projector.pixel([x, y, 0.0]),
398            ]
399        })
400        .flatten()
401        .map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
402        .collect();
403    let first = points.first()?;
404    let (mut x0, mut y0, mut x1, mut y1) = (first[0], first[1], first[0], first[1]);
405    for [x, y] in &points {
406        x0 = x0.min(*x);
407        y0 = y0.min(*y);
408        x1 = x1.max(*x);
409        y1 = y1.max(*y);
410    }
411    let (w, h) = (f64::from(size[0]), f64::from(size[1]));
412    if x1 < 0.0 || y1 < 0.0 || x0 >= w || y0 >= h {
413        return None;
414    }
415    Some(fit_rect(
416        [
417            x0 - MARGIN_PX,
418            y0 - MARGIN_PX,
419            x1 + MARGIN_PX,
420            y1 + MARGIN_PX,
421        ],
422        size,
423    ))
424}
425
426/// A box `[x0, y0, x1, y1]` widened about its centre to 16:9 and to the least
427/// width, then moved — and only if it must, shrunk at 16:9 — inside the frame.
428fn fit_rect(bounds: [f64; 4], size: [u32; 2]) -> [u32; 4] {
429    let (frame_w, frame_h) = (f64::from(size[0]), f64::from(size[1]));
430    let centre = [
431        f64::midpoint(bounds[0], bounds[2]),
432        f64::midpoint(bounds[1], bounds[3]),
433    ];
434    let mut width = (bounds[2] - bounds[0])
435        .max((bounds[3] - bounds[1]) * 16.0 / 9.0)
436        .max(MIN_CROP_WIDTH_PX);
437    width = width.min(frame_w).min(frame_h * 16.0 / 9.0);
438    let height = width * 9.0 / 16.0;
439    let x = (centre[0] - width / 2.0).clamp(0.0, frame_w - width);
440    let y = (centre[1] - height / 2.0).clamp(0.0, frame_h - height);
441    #[expect(
442        clippy::cast_possible_truncation,
443        clippy::cast_sign_loss,
444        reason = "each is clamped inside the frame, whose size fits a u32"
445    )]
446    let whole = |value: f64| value.round() as u32;
447    let (rx, ry) = (whole(x), whole(y));
448    let rw = whole(width).min(size[0] - rx);
449    let rh = whole(height).min(size[1] - ry);
450    [rx, ry, rw, rh]
451}