use std::path::{Path, PathBuf};
use printobserver_types::PrintId;
pub const OUTLINE_DIRECTIONS: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ExtrusionKind {
Wall,
SparseInfill,
SolidInfill,
TopSolidInfill,
Support,
Bridge,
Overhang,
Other,
}
impl ExtrusionKind {
#[must_use]
pub fn of_type(name: &str) -> Self {
match name {
"External perimeter" | "Perimeter" => Self::Wall,
"Internal infill" => Self::SparseInfill,
"Solid infill" | "Gap fill" => Self::SolidInfill,
"Top solid infill" => Self::TopSolidInfill,
"Support material" | "Support material interface" => Self::Support,
"Bridge infill" => Self::Bridge,
"Overhang perimeter" => Self::Overhang,
_ => Self::Other,
}
}
#[must_use]
pub const fn is_support(self) -> bool {
matches!(self, Self::Support)
}
#[must_use]
pub const fn is_infill(self) -> bool {
matches!(
self,
Self::SparseInfill | Self::SolidInfill | Self::TopSolidInfill
)
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Wall => "wall",
Self::SparseInfill => "sparse infill",
Self::SolidInfill => "solid infill",
Self::TopSolidInfill => "top solid infill",
Self::Support => "support",
Self::Bridge => "bridge",
Self::Overhang => "overhang",
Self::Other => "skirt, brim or other",
}
}
#[must_use]
pub const fn short_name(self) -> &'static str {
match self {
Self::Wall => "wall",
Self::SparseInfill => "sparse",
Self::SolidInfill => "solid",
Self::TopSolidInfill => "top solid",
Self::Support => "support",
Self::Bridge => "bridge",
Self::Overhang => "overhang",
Self::Other => "other",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ObjectOutline {
pub hull_mm: Vec<[f32; 2]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LayerRef(pub(crate) usize);
impl LayerRef {
#[must_use]
pub const fn of_index(index: usize) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> usize {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ToolpathSegment {
pub from_mm: [f32; 2],
pub to_mm: [f32; 2],
pub kind: ExtrusionKind,
pub width_mm: f32,
pub ends_at: u64,
}
impl ToolpathSegment {
#[must_use]
pub fn length_mm(&self) -> f64 {
let dx = f64::from(self.to_mm[0]) - f64::from(self.from_mm[0]);
let dy = f64::from(self.to_mm[1]) - f64::from(self.from_mm[1]);
dx.hypot(dy)
}
#[must_use]
pub const fn sent_by(&self, file_position_bytes: u64) -> bool {
self.ends_at <= file_position_bytes
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LayerToolpath {
pub z_mm: f32,
pub segments: Vec<ToolpathSegment>,
}
impl LayerToolpath {
#[must_use]
pub fn carries_object_extrusion(&self) -> bool {
self.segments
.iter()
.any(|segment| !segment.kind.is_support())
}
#[must_use]
pub fn progress(&self, file_position_bytes: u64) -> LayerProgress {
let mut progress = LayerProgress::default();
for segment in &self.segments {
let length = segment.length_mm();
progress.total_mm += length;
let (kinds, sent) = if segment.sent_by(file_position_bytes) {
(&mut progress.kinds_sent, length)
} else {
(&mut progress.kinds_left, 0.0)
};
progress.sent_mm += sent;
if !kinds.contains(&segment.kind) {
kinds.push(segment.kind);
}
}
progress
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LayerProgress {
pub sent_mm: f64,
pub total_mm: f64,
pub kinds_sent: Vec<ExtrusionKind>,
pub kinds_left: Vec<ExtrusionKind>,
}
impl LayerProgress {
#[must_use]
pub fn percent_sent(&self) -> u32 {
if self.total_mm <= 0.0 {
return 0;
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a share of 0 to 100 percent, rounded"
)]
let percent = (100.0 * self.sent_mm / self.total_mm)
.round()
.clamp(0.0, 100.0) as u32;
percent
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct LayerFacts {
pub number: usize,
pub count: usize,
pub z_mm: f64,
pub expected_colour: Option<String>,
pub change: Option<ChangeFact>,
pub progress: LayerProgress,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChangeFact {
pub just_made: bool,
pub number: u32,
pub colour_change: bool,
pub layer: u32,
pub z_mm: f64,
pub colour: Option<String>,
}
impl LayerFacts {
#[must_use]
pub fn lines(&self) -> Vec<String> {
let colour = self.expected_colour.as_deref().map_or_else(
|| "no colour expected".to_owned(),
|c| format!("expect {c}"),
);
let change = self
.change
.as_ref()
.map_or_else(|| "no change ahead".to_owned(), ChangeFact::line);
let named = |kinds: &[ExtrusionKind]| {
if kinds.is_empty() {
"nothing".to_owned()
} else {
kinds
.iter()
.map(|kind| kind.short_name())
.collect::<Vec<_>>()
.join(", ")
}
};
vec![
format!(
"layer {}/{}, Z {:.2} mm, {colour}; {change}",
self.number, self.count, self.z_mm
),
format!(
"{}% sent by length, bold: {}",
self.progress.percent_sent(),
named(&self.progress.kinds_sent)
),
format!("to print, grey: {}", named(&self.progress.kinds_left)),
]
}
}
impl ChangeFact {
#[must_use]
pub fn line(&self) -> String {
let what = if self.colour_change {
"colour change"
} else {
"pause"
};
let to = self
.colour
.as_deref()
.map_or_else(String::new, |colour| format!(", to {colour}"));
if self.just_made {
format!("{what} {} just made{to}", self.number)
} else {
format!(
"{what} {} next: layer {}, Z {:.2} mm{to}",
self.number, self.layer, self.z_mm
)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpoolError {
NoSpool,
UnknownLayer,
Io {
detail: String,
},
}
impl core::fmt::Display for SpoolError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::NoSpool => formatter.write_str("the print's G-code was indexed with no spool"),
Self::UnknownLayer => formatter.write_str("no such layer in the print's index"),
Self::Io { detail } => write!(formatter, "the print's G-code spool: {detail}"),
}
}
}
impl std::error::Error for SpoolError {}
#[must_use]
pub fn spool_path(directory: &Path, print_id: PrintId) -> PathBuf {
directory.join(format!("{print_id}{SPOOL_SUFFIX}"))
}
pub(crate) const SPOOL_SUFFIX: &str = ".gcode";
fn direction(k: usize) -> [f64; 2] {
let angle = core::f64::consts::TAU * f64::from(u32::try_from(k).unwrap_or(0))
/ f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
[angle.cos(), angle.sin()]
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Reach {
extent: [f64; OUTLINE_DIRECTIONS],
any: bool,
inside: ([f64; 2], f64),
}
impl Default for Reach {
fn default() -> Self {
Self {
extent: [f64::NEG_INFINITY; OUTLINE_DIRECTIONS],
any: false,
inside: ([0.0, 0.0], -1.0),
}
}
}
fn directions() -> &'static [[f64; 2]; OUTLINE_DIRECTIONS] {
static HELD: std::sync::OnceLock<[[f64; 2]; OUTLINE_DIRECTIONS]> = std::sync::OnceLock::new();
HELD.get_or_init(|| {
let mut held = [[0.0; 2]; OUTLINE_DIRECTIONS];
let mut k = 0;
while k < OUTLINE_DIRECTIONS {
held[k] = direction(k);
k += 1;
}
held
})
}
impl Reach {
pub(crate) fn point(&mut self, x: f64, y: f64) {
let ([cx, cy], radius) = self.inside;
let (dx, dy) = (x - cx, y - cy);
if radius > 0.0 && dx * dx + dy * dy < radius * radius {
return;
}
let held = directions();
self.any = true;
let mut grew = false;
let mut k = 0;
while k < OUTLINE_DIRECTIONS {
let along = held[k][0] * x + held[k][1] * y;
if along > self.extent[k] {
self.extent[k] = along;
grew = true;
}
k += 1;
}
if grew {
self.refit_inside();
}
}
fn refit_inside(&mut self) {
let quarter = OUTLINE_DIRECTIONS / 4;
let (right, up) = (self.extent[0], self.extent[quarter]);
let (left, down) = (-self.extent[2 * quarter], -self.extent[3 * quarter]);
if !(right.is_finite() && up.is_finite() && left.is_finite() && down.is_finite()) {
return;
}
let centre = [f64::midpoint(right, left), f64::midpoint(up, down)];
let held = directions();
let mut radius = f64::INFINITY;
let mut k = 0;
while k < OUTLINE_DIRECTIONS {
let gap = self.extent[k] - (held[k][0] * centre[0] + held[k][1] * centre[1]);
radius = radius.min(gap);
k += 1;
}
self.inside = (centre, radius);
}
pub(crate) fn arc(&mut self, centre: [f64; 2], radius: f64, from: f64, sweep: f64) {
let tau = core::f64::consts::TAU;
let held = directions();
for (k, unit) in held.iter().enumerate() {
let angle = tau * f64::from(u32::try_from(k).unwrap_or(0))
/ f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
if (angle - from).rem_euclid(tau) <= sweep + 1e-9 {
let along = unit[0] * centre[0] + unit[1] * centre[1] + radius;
if along > self.extent[k] {
self.extent[k] = along;
self.any = true;
}
}
}
self.refit_inside();
}
pub(crate) fn outline(&self) -> Option<ObjectOutline> {
if !self.any {
return None;
}
let far = 1e6;
let mut polygon = vec![[-far, -far], [far, -far], [far, far], [-far, far]];
for (unit, extent) in directions().iter().zip(self.extent) {
polygon = clip(&polygon, *unit, extent);
if polygon.is_empty() {
return None;
}
}
let mut hull: Vec<[f32; 2]> = Vec::with_capacity(polygon.len());
for [x, y] in polygon {
#[expect(
clippy::cast_possible_truncation,
reason = "bed millimetres are far inside f32's range; the outline is drawn, not measured"
)]
let vertex = [x as f32, y as f32];
let repeats = hull.last().is_some_and(|last: &[f32; 2]| {
(last[0] - vertex[0]).abs() < 1e-4 && (last[1] - vertex[1]).abs() < 1e-4
});
if !repeats {
hull.push(vertex);
}
}
while hull.len() > 1
&& hull.first().zip(hull.last()).is_some_and(|(first, last)| {
(first[0] - last[0]).abs() < 1e-4 && (first[1] - last[1]).abs() < 1e-4
})
{
hull.pop();
}
Some(ObjectOutline { hull_mm: hull })
}
}
fn clip(polygon: &[[f64; 2]], unit: [f64; 2], extent: f64) -> Vec<[f64; 2]> {
let inside = |p: [f64; 2]| unit[0] * p[0] + unit[1] * p[1] - extent;
let mut kept = Vec::with_capacity(polygon.len() + 1);
for (at, point) in polygon.iter().enumerate() {
let next = polygon[(at + 1) % polygon.len()];
let (here, there) = (inside(*point), inside(next));
if here <= 0.0 {
kept.push(*point);
}
if (here <= 0.0) != (there <= 0.0) {
let t = here / (here - there);
kept.push([
point[0] + t * (next[0] - point[0]),
point[1] + t * (next[1] - point[1]),
]);
}
}
kept
}
#[cfg(test)]
mod tests {
use super::{ExtrusionKind, OUTLINE_DIRECTIONS, Reach};
fn area(hull: &[[f32; 2]]) -> f64 {
let mut twice = 0.0;
for (at, a) in hull.iter().enumerate() {
let b = hull[(at + 1) % hull.len()];
twice += f64::from(a[0]) * f64::from(b[1]) - f64::from(b[0]) * f64::from(a[1]);
}
twice / 2.0
}
#[test]
fn an_outline_holds_every_point_counter_clockwise_and_is_bounded() {
let mut reach = Reach::default();
let points = [
[10.0, 10.0],
[30.0, 12.0],
[25.0, 40.0],
[12.0, 33.0],
[20.0, 20.0],
];
for [x, y] in points {
reach.point(x, y);
}
let outline = reach.outline().expect("points were given");
assert!(outline.hull_mm.len() <= OUTLINE_DIRECTIONS);
assert!(area(&outline.hull_mm) > 0.0, "counter-clockwise");
for [x, y] in points {
for (at, a) in outline.hull_mm.iter().enumerate() {
let b = outline.hull_mm[(at + 1) % outline.hull_mm.len()];
let cross = (f64::from(b[0]) - f64::from(a[0])) * (y - f64::from(a[1]))
- (f64::from(b[1]) - f64::from(a[1])) * (x - f64::from(a[0]));
assert!(cross >= -1e-3, "({x}, {y}) lies inside every edge");
}
}
}
#[test]
fn an_arc_reaches_the_part_of_its_circle_it_sweeps() {
let mut reach = Reach::default();
reach.point(10.0, 0.0);
reach.point(0.0, 10.0);
reach.arc([0.0, 0.0], 10.0, 0.0, core::f64::consts::FRAC_PI_2);
let outline = reach.outline().expect("points were given");
let furthest = outline
.hull_mm
.iter()
.map(|[x, y]| f64::from(*x).hypot(f64::from(*y)))
.fold(0.0, f64::max);
assert!((10.0..10.1).contains(&furthest), "{furthest}");
}
#[test]
fn no_point_is_no_outline_and_types_map_to_kinds() {
assert!(Reach::default().outline().is_none());
assert_eq!(ExtrusionKind::of_type("Perimeter"), ExtrusionKind::Wall);
assert_eq!(
ExtrusionKind::of_type("Gap fill"),
ExtrusionKind::SolidInfill
);
assert_eq!(
ExtrusionKind::of_type("Internal infill"),
ExtrusionKind::SparseInfill
);
assert_eq!(
ExtrusionKind::of_type("Top solid infill"),
ExtrusionKind::TopSolidInfill
);
assert_eq!(
ExtrusionKind::of_type("Support material interface"),
ExtrusionKind::Support
);
assert_eq!(ExtrusionKind::of_type("Skirt/Brim"), ExtrusionKind::Other);
}
}