use image::{GrayImage, Luma, Rgb, RgbImage};
use imageproc::drawing::{draw_hollow_circle_mut, draw_line_segment_mut, draw_polygon_mut};
use imageproc::point::Point;
use printobserver_core::{ExtrusionKind, LayerFacts};
use crate::geometry::Projected;
use crate::occlusion::Occluders;
pub const TO_PRINT_GREY: Rgb<u8> = Rgb([215, 215, 215]);
pub const HIDDEN_DASH_PX: [f32; 2] = [4.0, 4.0];
pub const HEAD_MARK: Rgb<u8> = Rgb([255, 255, 255]);
pub const SPARSE_WIDTH_PX: f32 = 3.0;
pub const LINE_WIDTH_PX: f32 = 2.0;
const NOMINAL_WIDTH_MM: f64 = 0.45;
#[must_use]
pub const fn colour_of(kind: ExtrusionKind) -> Rgb<u8> {
match kind {
ExtrusionKind::Wall => Rgb([255, 40, 40]),
ExtrusionKind::SparseInfill => Rgb([70, 140, 255]),
ExtrusionKind::SolidInfill => Rgb([255, 214, 0]),
ExtrusionKind::TopSolidInfill => Rgb([255, 128, 0]),
ExtrusionKind::Support => Rgb([0, 200, 255]),
ExtrusionKind::Bridge => Rgb([255, 0, 255]),
ExtrusionKind::Overhang => Rgb([0, 230, 0]),
ExtrusionKind::Other => Rgb([255, 255, 255]),
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Stroke {
Line(f32),
Extrusion,
}
#[must_use]
pub const fn style(kind: ExtrusionKind) -> (Stroke, u8) {
match kind {
ExtrusionKind::SparseInfill => (Stroke::Line(SPARSE_WIDTH_PX), 230),
ExtrusionKind::SolidInfill | ExtrusionKind::TopSolidInfill => (Stroke::Extrusion, 150),
ExtrusionKind::Wall
| ExtrusionKind::Bridge
| ExtrusionKind::Overhang
| ExtrusionKind::Support
| ExtrusionKind::Other => (Stroke::Line(LINE_WIDTH_PX), 255),
}
}
const DRAW_ORDER: [ExtrusionKind; 8] = [
ExtrusionKind::SparseInfill,
ExtrusionKind::SolidInfill,
ExtrusionKind::TopSolidInfill,
ExtrusionKind::Bridge,
ExtrusionKind::Support,
ExtrusionKind::Other,
ExtrusionKind::Overhang,
ExtrusionKind::Wall,
];
pub const KEY: [(&str, ExtrusionKind, &str); 7] = [
("wall", ExtrusionKind::Wall, "red"),
("sparse infill", ExtrusionKind::SparseInfill, "blue"),
("solid infill", ExtrusionKind::SolidInfill, "yellow"),
("top solid", ExtrusionKind::TopSolidInfill, "orange"),
("bridge", ExtrusionKind::Bridge, "magenta"),
("support", ExtrusionKind::Support, "cyan"),
("overhang", ExtrusionKind::Overhang, "green"),
];
#[derive(Clone, Copy)]
pub(crate) struct Plan<'a> {
pub(crate) drawn: &'a [Projected],
pub(crate) below: &'a [Projected],
pub(crate) file_position_bytes: Option<u64>,
pub(crate) occluders: Option<&'a Occluders>,
pub(crate) reported_head_px: Option<[f64; 2]>,
pub(crate) scale: [f64; 2],
pub(crate) project: &'a dyn Fn([f64; 2]) -> Option<[f64; 2]>,
}
const fn sent(piece: &Projected, position: Option<u64>) -> bool {
match position {
Some(position) => piece.ends_at <= position,
None => true,
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Drawn {
pub(crate) hidden_mm: f64,
pub(crate) total_mm: f64,
}
struct Overlay {
colour: RgbImage,
alpha: GrayImage,
}
impl Overlay {
fn over(panel: &RgbImage) -> Self {
Self {
colour: RgbImage::new(panel.width(), panel.height()),
alpha: GrayImage::new(panel.width(), panel.height()),
}
}
fn stroke(&mut self, a: [f32; 2], b: [f32; 2], width: f32, colour: Rgb<u8>, alpha: u8) {
let length = (b[0] - a[0]).hypot(b[1] - a[1]);
if width <= 1.5 || length < 1e-3 {
draw_line_segment_mut(&mut self.colour, (a[0], a[1]), (b[0], b[1]), colour);
draw_line_segment_mut(&mut self.alpha, (a[0], a[1]), (b[0], b[1]), Luma([alpha]));
return;
}
let (nx, ny) = (
-(b[1] - a[1]) / length * width / 2.0,
(b[0] - a[0]) / length * width / 2.0,
);
#[expect(
clippy::cast_possible_truncation,
reason = "a panel pixel; one far off the panel is clipped by the drawing call"
)]
let at = |x: f32, y: f32| Point::new(x.round() as i32, y.round() as i32);
let corners = [
at(a[0] + nx, a[1] + ny),
at(b[0] + nx, b[1] + ny),
at(b[0] - nx, b[1] - ny),
at(a[0] - nx, a[1] - ny),
];
if corners[0] == corners[3] || corners[1] == corners[2] {
draw_line_segment_mut(&mut self.colour, (a[0], a[1]), (b[0], b[1]), colour);
draw_line_segment_mut(&mut self.alpha, (a[0], a[1]), (b[0], b[1]), Luma([alpha]));
return;
}
draw_polygon_mut(&mut self.colour, &corners, colour);
draw_polygon_mut(&mut self.alpha, &corners, Luma([alpha]));
}
fn fill(&mut self, corners: [[f32; 2]; 4], colour: Rgb<u8>, alpha: u8) {
#[expect(
clippy::cast_possible_truncation,
reason = "a panel pixel; one far off the panel is clipped by the drawing call"
)]
let points = corners.map(|[x, y]| Point::new(x.round() as i32, y.round() as i32));
if points[0] == points[3] || points[1] == points[2] {
let (a, b) = (corners[0], corners[1]);
draw_line_segment_mut(&mut self.colour, (a[0], a[1]), (b[0], b[1]), colour);
draw_line_segment_mut(&mut self.alpha, (a[0], a[1]), (b[0], b[1]), Luma([alpha]));
return;
}
draw_polygon_mut(&mut self.colour, &points, colour);
draw_polygon_mut(&mut self.alpha, &points, Luma([alpha]));
}
fn blend(&self, panel: &mut RgbImage) {
for ((pixel, painted), Luma([alpha])) in panel
.pixels_mut()
.zip(self.colour.pixels())
.zip(self.alpha.pixels())
{
if *alpha == 0 {
continue;
}
let a = u16::from(*alpha);
for channel in 0..3 {
let mixed = (u16::from(pixel.0[channel]) * (255 - a)
+ u16::from(painted.0[channel]) * a
+ 127)
/ 255;
pixel.0[channel] = u8::try_from(mixed).unwrap_or(u8::MAX);
}
}
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "a projected pixel is a few thousand at most; one far off the panel is clipped by the drawing call"
)]
fn at_panel([x, y]: [f64; 2], [sx, sy]: [f64; 2]) -> [f32; 2] {
[(x * sx) as f32, (y * sy) as f32]
}
pub(crate) fn draw(panel: &mut RgbImage, plan: &Plan<'_>) -> Drawn {
let hidden = |piece: &Projected| {
plan.occluders
.is_some_and(|occluders| occluders.hides(piece.middle_mm))
};
let mut drawn = Drawn {
hidden_mm: 0.0,
total_mm: 0.0,
};
for piece in plan.drawn {
drawn.total_mm += piece.length_mm;
if hidden(piece) {
drawn.hidden_mm += piece.length_mm;
}
}
let mut overlay = Overlay::over(panel);
let mut dashes = Dashes::default();
for piece in plan.below {
let (a, b) = (
at_panel(piece.from, plan.scale),
at_panel(piece.to, plan.scale),
);
if hidden(piece) {
dashes.stroke(&mut overlay, a, b, crate::compose::BELOW_GREY);
} else {
overlay.stroke(a, b, 1.0, crate::compose::BELOW_GREY, 255);
}
}
for piece in plan
.drawn
.iter()
.filter(|piece| !sent(piece, plan.file_position_bytes) && !hidden(piece))
{
let (a, b) = (
at_panel(piece.from, plan.scale),
at_panel(piece.to, plan.scale),
);
overlay.stroke(a, b, 1.0, TO_PRINT_GREY, 200);
}
for piece in plan.drawn.iter().filter(|piece| hidden(piece)) {
let (a, b) = (
at_panel(piece.from, plan.scale),
at_panel(piece.to, plan.scale),
);
let colour = if sent(piece, plan.file_position_bytes) {
colour_of(piece.kind)
} else {
TO_PRINT_GREY
};
dashes.stroke(&mut overlay, a, b, colour);
}
for kind in DRAW_ORDER {
let (stroke, alpha) = style(kind);
for piece in plan.drawn.iter().filter(|piece| {
piece.kind == kind && sent(piece, plan.file_position_bytes) && !hidden(piece)
}) {
let (a, b) = (
at_panel(piece.from, plan.scale),
at_panel(piece.to, plan.scale),
);
match stroke {
Stroke::Line(width) => overlay.stroke(a, b, width, colour_of(kind), alpha),
Stroke::Extrusion => match extrusion_corners(piece, plan) {
Some(corners) => overlay.fill(corners, colour_of(kind), alpha),
None => overlay.stroke(a, b, 1.0, colour_of(kind), alpha),
},
}
}
}
overlay.blend(panel);
if let Some(head) = plan.reported_head_px {
mark_head(panel, at_panel(head, plan.scale));
}
drawn
}
fn extrusion_corners(piece: &Projected, plan: &Plan<'_>) -> Option<[[f32; 2]; 4]> {
let width_mm = if piece.width_mm > 0.0 {
f64::from(piece.width_mm)
} else {
NOMINAL_WIDTH_MM
};
let [dx, dy] = piece.direction_mm;
let (half_length, half_width) = (piece.length_mm / 2.0, width_mm / 2.0);
let [mx, my] = piece.middle_mm;
let corner = |along: f64, across: f64| {
(plan.project)([mx + dx * along - dy * across, my + dy * along + dx * across])
.map(|pixel| at_panel(pixel, plan.scale))
};
Some([
corner(-half_length, half_width)?,
corner(half_length, half_width)?,
corner(half_length, -half_width)?,
corner(-half_length, -half_width)?,
])
}
#[derive(Default)]
struct Dashes {
walked: f32,
}
impl Dashes {
fn stroke(&mut self, overlay: &mut Overlay, a: [f32; 2], b: [f32; 2], colour: Rgb<u8>) {
let [on, off] = HIDDEN_DASH_PX;
let period = on + off;
let length = (b[0] - a[0]).hypot(b[1] - a[1]);
let mut along = 0.0_f32;
while along < length {
let phase = self.walked.rem_euclid(period);
let (drawing, left) = if phase < on {
(true, on - phase)
} else {
(false, period - phase)
};
let step = left.min(length - along);
if drawing {
let at = |t: f32| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
overlay.stroke(
at(along / length),
at((along + step) / length),
1.0,
colour,
255,
);
}
along += step;
self.walked += step;
}
}
}
fn mark_head(panel: &mut RgbImage, [x, y]: [f32; 2]) {
#[expect(
clippy::cast_possible_truncation,
reason = "a panel pixel; one off the panel is clipped by the drawing call"
)]
let centre = (x.round() as i32, y.round() as i32);
draw_hollow_circle_mut(panel, centre, 14, Rgb([0, 0, 0]));
draw_hollow_circle_mut(panel, centre, 13, HEAD_MARK);
draw_hollow_circle_mut(panel, centre, 12, HEAD_MARK);
}
#[must_use]
pub(crate) fn lines(
facts: Option<&LayerFacts>,
queued_span_mm: Option<[[f64; 2]; 2]>,
drawn: Drawn,
head_marked: bool,
) -> Vec<String> {
let mut lines = facts.map(LayerFacts::lines).unwrap_or_default();
let head = if head_marked {
"white ring: head as reported"
} else {
"no head mark: no position reported"
};
lines.push(format!("{}; {head}", hidden_line(queued_span_mm, drawn)));
lines.push(key_line());
lines
}
fn key_line() -> String {
let kinds = KEY
.iter()
.map(|(name, _, colour)| format!("{colour} {name}"))
.collect::<Vec<_>>()
.join(", ");
format!("colours, sent: {kinds}; thin grey: to print; dashed: hidden")
}
fn hidden_line(queued_span_mm: Option<[[f64; 2]; 2]>, drawn: Drawn) -> String {
let Some([[x0, x1], [y0, y1]]) = queued_span_mm else {
return "head/gantry place unknown: any of the layer may be hidden".to_owned();
};
let reach = format!(
"head somewhere along queued moves X {x0:.0} to {x1:.0}, Y {y0:.0} to {y1:.0} mm: \
what it covers is not visible; judge plastic in view, the head seen is the head"
);
if drawn.hidden_mm <= 0.0 || drawn.total_mm <= 0.0 {
return format!("head/gantry hide none of the layer wherever it is; {reach}");
}
let share = (100.0 * drawn.hidden_mm / drawn.total_mm)
.round()
.clamp(1.0, 100.0);
format!("dashed, under head/gantry wherever it is: {share:.0}%, not visible; {reach}")
}