Skip to main content

printobserver_core/
toolpath.rs

1//! The planned geometry of a print, read from its G-code by the one read the
2//! [`GcodeIndex`](crate::GcodeIndex) makes: each object's footprint outline,
3//! and one layer's toolpath read back from the print's spool.
4//!
5//! The index's single streamed read of a print's file also copies its bytes
6//! to a per-print spool file and records each layer's byte range, so a
7//! toolpath is read from that range of the spool and never from a second read
8//! of the printer's file. The core alone reads G-code; what leaves it is
9//! segments in bed millimetres, each with the [`ExtrusionKind`] its
10//! `;TYPE:` maps to.
11
12use std::path::{Path, PathBuf};
13
14use printobserver_types::PrintId;
15
16/// How many directions an outline is bounded in: its most vertices.
17pub const OUTLINE_DIRECTIONS: usize = 64;
18
19/// What a toolpath segment lays, from `PrusaSlicer`'s `;TYPE:` label.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ExtrusionKind {
22    /// `External perimeter` and `Perimeter`.
23    Wall,
24    /// `Internal infill`: the sparse pattern inside the part.
25    SparseInfill,
26    /// `Solid infill` and `Gap fill`: solid layers inside the part, and the
27    /// gaps between its walls.
28    SolidInfill,
29    /// `Top solid infill`: the part's top surface at this layer.
30    TopSolidInfill,
31    /// `Support material` and `Support material interface`.
32    Support,
33    /// `Bridge infill`.
34    Bridge,
35    /// `Overhang perimeter`.
36    Overhang,
37    /// Anything else: the skirt or brim, the slicer's own start and end
38    /// G-code, or an unlabelled move.
39    Other,
40}
41
42impl ExtrusionKind {
43    /// The kind a `;TYPE:` label names.
44    #[must_use]
45    pub fn of_type(name: &str) -> Self {
46        match name {
47            "External perimeter" | "Perimeter" => Self::Wall,
48            "Internal infill" => Self::SparseInfill,
49            "Solid infill" | "Gap fill" => Self::SolidInfill,
50            "Top solid infill" => Self::TopSolidInfill,
51            "Support material" | "Support material interface" => Self::Support,
52            "Bridge infill" => Self::Bridge,
53            "Overhang perimeter" => Self::Overhang,
54            _ => Self::Other,
55        }
56    }
57
58    /// Whether this kind holds the part up rather than making it.
59    #[must_use]
60    pub const fn is_support(self) -> bool {
61        matches!(self, Self::Support)
62    }
63
64    /// Whether this kind fills the part's inside: sparse, solid or top solid
65    /// infill.
66    #[must_use]
67    pub const fn is_infill(self) -> bool {
68        matches!(
69            self,
70            Self::SparseInfill | Self::SolidInfill | Self::TopSolidInfill
71        )
72    }
73
74    /// What a person calls it, as the check image's text and a turn's line
75    /// name it.
76    #[must_use]
77    pub const fn name(self) -> &'static str {
78        match self {
79            Self::Wall => "wall",
80            Self::SparseInfill => "sparse infill",
81            Self::SolidInfill => "solid infill",
82            Self::TopSolidInfill => "top solid infill",
83            Self::Support => "support",
84            Self::Bridge => "bridge",
85            Self::Overhang => "overhang",
86            Self::Other => "skirt, brim or other",
87        }
88    }
89
90    /// The kind as the check image's colour key names it.
91    #[must_use]
92    pub const fn short_name(self) -> &'static str {
93        match self {
94            Self::Wall => "wall",
95            Self::SparseInfill => "sparse",
96            Self::SolidInfill => "solid",
97            Self::TopSolidInfill => "top solid",
98            Self::Support => "support",
99            Self::Bridge => "bridge",
100            Self::Overhang => "overhang",
101            Self::Other => "other",
102        }
103    }
104}
105
106/// One object's footprint: an outward bound of the convex hull of every
107/// extrusion move laying it, in bed millimetres, counter-clockwise, with at
108/// most [`OUTLINE_DIRECTIONS`] vertices.
109#[derive(Debug, Clone, PartialEq)]
110pub struct ObjectOutline {
111    /// The vertices, counter-clockwise.
112    pub hull_mm: Vec<[f32; 2]>,
113}
114
115/// One layer of an index, as the index that answered it numbers it.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
117pub struct LayerRef(pub(crate) usize);
118
119impl LayerRef {
120    /// The layer at one place among a file's layers, the first being 0; an
121    /// index answers [`SpoolError::UnknownLayer`] for one it does not have.
122    #[must_use]
123    pub const fn of_index(index: usize) -> Self {
124        Self(index)
125    }
126
127    /// Its place among the file's layers, the first being 0.
128    #[must_use]
129    pub const fn index(self) -> usize {
130        self.0
131    }
132}
133
134/// One extrusion move, or one chord of an arc, of a layer.
135#[derive(Debug, Clone, Copy, PartialEq)]
136pub struct ToolpathSegment {
137    /// Where it starts, in bed millimetres.
138    pub from_mm: [f32; 2],
139    /// Where it ends.
140    pub to_mm: [f32; 2],
141    /// What it lays.
142    pub kind: ExtrusionKind,
143    /// The extrusion width the slicer laid it at, from the last `;WIDTH:`
144    /// before it, in millimetres; 0 when the file states none.
145    pub width_mm: f32,
146    /// The file offset just past the line laying it: a job whose file
147    /// position has reached this has sent it to the printer.
148    pub ends_at: u64,
149}
150
151impl ToolpathSegment {
152    /// Its length on the bed, in millimetres.
153    #[must_use]
154    pub fn length_mm(&self) -> f64 {
155        let dx = f64::from(self.to_mm[0]) - f64::from(self.from_mm[0]);
156        let dy = f64::from(self.to_mm[1]) - f64::from(self.from_mm[1]);
157        dx.hypot(dy)
158    }
159
160    /// Whether a job standing at `file_position_bytes` has sent it.
161    #[must_use]
162    pub const fn sent_by(&self, file_position_bytes: u64) -> bool {
163        self.ends_at <= file_position_bytes
164    }
165}
166
167/// Every extrusion move of one layer, in file order.
168#[derive(Debug, Clone, PartialEq)]
169pub struct LayerToolpath {
170    /// The layer's height, from its `;Z:`; 0 when the file states none.
171    pub z_mm: f32,
172    /// Its segments.
173    pub segments: Vec<ToolpathSegment>,
174}
175
176impl LayerToolpath {
177    /// Whether any segment is object extrusion: anything but supports, as
178    /// `GcodeIndex::object_layer_at_or_below` reads it, so an `Other` segment
179    /// (skirt, brim or custom G-code) counts.
180    #[must_use]
181    pub fn carries_object_extrusion(&self) -> bool {
182        self.segments
183            .iter()
184            .any(|segment| !segment.kind.is_support())
185    }
186
187    /// How far a job standing at `file_position_bytes` is through this layer:
188    /// what it has sent and what it has still to send, by path length and by
189    /// kind.
190    #[must_use]
191    pub fn progress(&self, file_position_bytes: u64) -> LayerProgress {
192        let mut progress = LayerProgress::default();
193        for segment in &self.segments {
194            let length = segment.length_mm();
195            progress.total_mm += length;
196            let (kinds, sent) = if segment.sent_by(file_position_bytes) {
197                (&mut progress.kinds_sent, length)
198            } else {
199                (&mut progress.kinds_left, 0.0)
200            };
201            progress.sent_mm += sent;
202            if !kinds.contains(&segment.kind) {
203                kinds.push(segment.kind);
204            }
205        }
206        progress
207    }
208}
209
210/// How far a job is through one layer's toolpath.
211#[derive(Debug, Clone, Default, PartialEq)]
212pub struct LayerProgress {
213    /// The path length of the segments sent, in millimetres.
214    pub sent_mm: f64,
215    /// The path length of every segment of the layer.
216    pub total_mm: f64,
217    /// The kinds any sent segment lays, in the order the layer first lays
218    /// them.
219    pub kinds_sent: Vec<ExtrusionKind>,
220    /// The kinds any segment still to send lays, in the same order: a kind
221    /// part-way through is in both.
222    pub kinds_left: Vec<ExtrusionKind>,
223}
224
225impl LayerProgress {
226    /// The share of the layer's path length sent, in whole percent; 0 for a
227    /// layer that lays nothing.
228    #[must_use]
229    pub fn percent_sent(&self) -> u32 {
230        if self.total_mm <= 0.0 {
231            return 0;
232        }
233        #[expect(
234            clippy::cast_possible_truncation,
235            clippy::cast_sign_loss,
236            reason = "a share of 0 to 100 percent, rounded"
237        )]
238        let percent = (100.0 * self.sent_mm / self.total_mm)
239            .round()
240            .clamp(0.0, 100.0) as u32;
241        percent
242    }
243}
244
245/// What a check is told of the layer a job stands in: where it is among the
246/// file's layers, the colour it should be laying, the planned change nearest
247/// it, and how far through the layer the job has sent.
248#[derive(Debug, Clone, PartialEq)]
249pub struct LayerFacts {
250    /// The layer's number, counting the file's first as 1.
251    pub number: usize,
252    /// How many layers the file plans.
253    pub count: usize,
254    /// The layer's height, in millimetres.
255    pub z_mm: f64,
256    /// The colour the job should be laying, as `#RRGGBB`, when the file plans
257    /// a colour change and names the colour of the stretch the job is in;
258    /// none for a file planning no change, whose sliced colour says nothing
259    /// of the spool loaded.
260    pub expected_colour: Option<String>,
261    /// The planned change just made before this layer, else the next one.
262    pub change: Option<ChangeFact>,
263    /// How far through the layer the job has sent.
264    pub progress: LayerProgress,
265}
266
267/// A planned change as a check is told of it.
268#[derive(Debug, Clone, PartialEq)]
269pub struct ChangeFact {
270    /// Whether it was made just before this layer, rather than still ahead.
271    pub just_made: bool,
272    /// Its number among the file's changes, counting from 1 in file order.
273    pub number: u32,
274    /// Whether it is a colour change rather than a planned pause.
275    pub colour_change: bool,
276    /// The first layer printed after it, counting the first as 1.
277    pub layer: u32,
278    /// That layer's height, in millimetres.
279    pub z_mm: f64,
280    /// The colour loaded at it, as `#RRGGBB`, when the file names one.
281    pub colour: Option<String>,
282}
283
284impl LayerFacts {
285    /// The facts as three short lines of text, as a check's turn is told
286    /// them of panel 1: the layer, its colour and the planned change; how
287    /// far through the layer the job has sent and the kinds sent; and the
288    /// kinds still to print.
289    #[must_use]
290    pub fn lines(&self) -> Vec<String> {
291        let colour = self.expected_colour.as_deref().map_or_else(
292            || "no colour expected".to_owned(),
293            |c| format!("expect {c}"),
294        );
295        let change = self
296            .change
297            .as_ref()
298            .map_or_else(|| "no change ahead".to_owned(), ChangeFact::line);
299        let named = |kinds: &[ExtrusionKind]| {
300            if kinds.is_empty() {
301                "nothing".to_owned()
302            } else {
303                kinds
304                    .iter()
305                    .map(|kind| kind.short_name())
306                    .collect::<Vec<_>>()
307                    .join(", ")
308            }
309        };
310        vec![
311            format!(
312                "layer {}/{}, Z {:.2} mm, {colour}; {change}",
313                self.number, self.count, self.z_mm
314            ),
315            format!(
316                "{}% sent by length, bold: {}",
317                self.progress.percent_sent(),
318                named(&self.progress.kinds_sent)
319            ),
320            format!("to print, grey: {}", named(&self.progress.kinds_left)),
321        ]
322    }
323}
324
325impl ChangeFact {
326    /// The change as one clause.
327    #[must_use]
328    pub fn line(&self) -> String {
329        let what = if self.colour_change {
330            "colour change"
331        } else {
332            "pause"
333        };
334        let to = self
335            .colour
336            .as_deref()
337            .map_or_else(String::new, |colour| format!(", to {colour}"));
338        if self.just_made {
339            format!("{what} {} just made{to}", self.number)
340        } else {
341            format!(
342                "{what} {} next: layer {}, Z {:.2} mm{to}",
343                self.number, self.layer, self.z_mm
344            )
345        }
346    }
347}
348
349/// Why a layer's toolpath could not be read back.
350#[derive(Debug, Clone, PartialEq, Eq)]
351pub enum SpoolError {
352    /// The index was built with no spool beside it.
353    NoSpool,
354    /// The layer is not one of this index's.
355    UnknownLayer,
356    /// The spool could not be read, or is shorter than the index recorded.
357    Io {
358        /// What the filesystem said.
359        detail: String,
360    },
361}
362
363impl core::fmt::Display for SpoolError {
364    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
365        match self {
366            Self::NoSpool => formatter.write_str("the print's G-code was indexed with no spool"),
367            Self::UnknownLayer => formatter.write_str("no such layer in the print's index"),
368            Self::Io { detail } => write!(formatter, "the print's G-code spool: {detail}"),
369        }
370    }
371}
372
373impl std::error::Error for SpoolError {}
374
375/// The spool file of one print under a spool directory.
376#[must_use]
377pub fn spool_path(directory: &Path, print_id: PrintId) -> PathBuf {
378    directory.join(format!("{print_id}{SPOOL_SUFFIX}"))
379}
380
381/// What every spool file's name ends in.
382pub(crate) const SPOOL_SUFFIX: &str = ".gcode";
383
384/// The unit vectors an outline is bounded along, counter-clockwise from +X.
385fn direction(k: usize) -> [f64; 2] {
386    let angle = core::f64::consts::TAU * f64::from(u32::try_from(k).unwrap_or(0))
387        / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
388    [angle.cos(), angle.sin()]
389}
390
391/// How far an outline reaches along each of its directions: the support
392/// function of every point it was given. Its polygon is the intersection of
393/// one half-plane per direction, so it holds every point and only grows
394/// outward from the hull.
395#[derive(Debug, Clone, PartialEq)]
396pub(crate) struct Reach {
397    /// The furthest point's projection on each direction.
398    extent: [f64; OUTLINE_DIRECTIONS],
399    /// Whether any point was given.
400    any: bool,
401    /// A circle inside the polygon so far: its centre and radius. A point
402    /// within it reaches no further in any direction, so it is passed over
403    /// without the per-direction work, which is most of a print's moves.
404    inside: ([f64; 2], f64),
405}
406
407impl Default for Reach {
408    fn default() -> Self {
409        Self {
410            extent: [f64::NEG_INFINITY; OUTLINE_DIRECTIONS],
411            any: false,
412            inside: ([0.0, 0.0], -1.0),
413        }
414    }
415}
416
417/// The directions, computed once.
418fn directions() -> &'static [[f64; 2]; OUTLINE_DIRECTIONS] {
419    static HELD: std::sync::OnceLock<[[f64; 2]; OUTLINE_DIRECTIONS]> = std::sync::OnceLock::new();
420    HELD.get_or_init(|| {
421        let mut held = [[0.0; 2]; OUTLINE_DIRECTIONS];
422        let mut k = 0;
423        while k < OUTLINE_DIRECTIONS {
424            held[k] = direction(k);
425            k += 1;
426        }
427        held
428    })
429}
430
431impl Reach {
432    /// Push every direction's extent out to `(x, y)`; a point inside the
433    /// cached inner circle cannot move any extent, so it is skipped.
434    pub(crate) fn point(&mut self, x: f64, y: f64) {
435        let ([cx, cy], radius) = self.inside;
436        let (dx, dy) = (x - cx, y - cy);
437        if radius > 0.0 && dx * dx + dy * dy < radius * radius {
438            return;
439        }
440        let held = directions();
441        self.any = true;
442        // A plain loop: this runs for every extrusion move of a print that
443        // the circle inside does not hold.
444        let mut grew = false;
445        let mut k = 0;
446        while k < OUTLINE_DIRECTIONS {
447            let along = held[k][0] * x + held[k][1] * y;
448            if along > self.extent[k] {
449                self.extent[k] = along;
450                grew = true;
451            }
452            k += 1;
453        }
454        if grew {
455            self.refit_inside();
456        }
457    }
458
459    /// The circle inside the polygon about the middle of its extents: the
460    /// nearest of its half-planes from that centre. The four axis directions
461    /// are among the directions, a quarter turn apart.
462    fn refit_inside(&mut self) {
463        let quarter = OUTLINE_DIRECTIONS / 4;
464        let (right, up) = (self.extent[0], self.extent[quarter]);
465        let (left, down) = (-self.extent[2 * quarter], -self.extent[3 * quarter]);
466        if !(right.is_finite() && up.is_finite() && left.is_finite() && down.is_finite()) {
467            return;
468        }
469        let centre = [f64::midpoint(right, left), f64::midpoint(up, down)];
470        let held = directions();
471        let mut radius = f64::INFINITY;
472        let mut k = 0;
473        while k < OUTLINE_DIRECTIONS {
474            let gap = self.extent[k] - (held[k][0] * centre[0] + held[k][1] * centre[1]);
475            radius = radius.min(gap);
476            k += 1;
477        }
478        self.inside = (centre, radius);
479    }
480
481    /// Push out the extents of the directions whose circle point the arc
482    /// sweeps over: `sweep` radians counter-clockwise from the angle `from`
483    /// about `centre`. The arc's ends are not reached here; the caller gives
484    /// them to `point`.
485    pub(crate) fn arc(&mut self, centre: [f64; 2], radius: f64, from: f64, sweep: f64) {
486        let tau = core::f64::consts::TAU;
487        let held = directions();
488        for (k, unit) in held.iter().enumerate() {
489            let angle = tau * f64::from(u32::try_from(k).unwrap_or(0))
490                / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
491            if (angle - from).rem_euclid(tau) <= sweep + 1e-9 {
492                let along = unit[0] * centre[0] + unit[1] * centre[1] + radius;
493                if along > self.extent[k] {
494                    self.extent[k] = along;
495                    self.any = true;
496                }
497            }
498        }
499        self.refit_inside();
500    }
501
502    /// The outline's polygon, counter-clockwise; nothing when no point was
503    /// given.
504    pub(crate) fn outline(&self) -> Option<ObjectOutline> {
505        if !self.any {
506            return None;
507        }
508        // A box far past any bed, clipped by each half-plane in turn.
509        let far = 1e6;
510        let mut polygon = vec![[-far, -far], [far, -far], [far, far], [-far, far]];
511        for (unit, extent) in directions().iter().zip(self.extent) {
512            polygon = clip(&polygon, *unit, extent);
513            if polygon.is_empty() {
514                return None;
515            }
516        }
517        let mut hull: Vec<[f32; 2]> = Vec::with_capacity(polygon.len());
518        for [x, y] in polygon {
519            #[expect(
520                clippy::cast_possible_truncation,
521                reason = "bed millimetres are far inside f32's range; the outline is drawn, not measured"
522            )]
523            let vertex = [x as f32, y as f32];
524            let repeats = hull.last().is_some_and(|last: &[f32; 2]| {
525                (last[0] - vertex[0]).abs() < 1e-4 && (last[1] - vertex[1]).abs() < 1e-4
526            });
527            if !repeats {
528                hull.push(vertex);
529            }
530        }
531        while hull.len() > 1
532            && hull.first().zip(hull.last()).is_some_and(|(first, last)| {
533                (first[0] - last[0]).abs() < 1e-4 && (first[1] - last[1]).abs() < 1e-4
534            })
535        {
536            hull.pop();
537        }
538        Some(ObjectOutline { hull_mm: hull })
539    }
540}
541
542/// One Sutherland–Hodgman step: what of a convex polygon lies on the side of
543/// `unit · p <= extent`.
544fn clip(polygon: &[[f64; 2]], unit: [f64; 2], extent: f64) -> Vec<[f64; 2]> {
545    let inside = |p: [f64; 2]| unit[0] * p[0] + unit[1] * p[1] - extent;
546    let mut kept = Vec::with_capacity(polygon.len() + 1);
547    for (at, point) in polygon.iter().enumerate() {
548        let next = polygon[(at + 1) % polygon.len()];
549        let (here, there) = (inside(*point), inside(next));
550        if here <= 0.0 {
551            kept.push(*point);
552        }
553        if (here <= 0.0) != (there <= 0.0) {
554            let t = here / (here - there);
555            kept.push([
556                point[0] + t * (next[0] - point[0]),
557                point[1] + t * (next[1] - point[1]),
558            ]);
559        }
560    }
561    kept
562}
563
564#[cfg(test)]
565mod tests {
566    use super::{ExtrusionKind, OUTLINE_DIRECTIONS, Reach};
567
568    /// Signed area of a polygon: positive when counter-clockwise.
569    fn area(hull: &[[f32; 2]]) -> f64 {
570        let mut twice = 0.0;
571        for (at, a) in hull.iter().enumerate() {
572            let b = hull[(at + 1) % hull.len()];
573            twice += f64::from(a[0]) * f64::from(b[1]) - f64::from(b[0]) * f64::from(a[1]);
574        }
575        twice / 2.0
576    }
577
578    #[test]
579    fn an_outline_holds_every_point_counter_clockwise_and_is_bounded() {
580        let mut reach = Reach::default();
581        let points = [
582            [10.0, 10.0],
583            [30.0, 12.0],
584            [25.0, 40.0],
585            [12.0, 33.0],
586            [20.0, 20.0],
587        ];
588        for [x, y] in points {
589            reach.point(x, y);
590        }
591        let outline = reach.outline().expect("points were given");
592        assert!(outline.hull_mm.len() <= OUTLINE_DIRECTIONS);
593        assert!(area(&outline.hull_mm) > 0.0, "counter-clockwise");
594        for [x, y] in points {
595            for (at, a) in outline.hull_mm.iter().enumerate() {
596                let b = outline.hull_mm[(at + 1) % outline.hull_mm.len()];
597                let cross = (f64::from(b[0]) - f64::from(a[0])) * (y - f64::from(a[1]))
598                    - (f64::from(b[1]) - f64::from(a[1])) * (x - f64::from(a[0]));
599                assert!(cross >= -1e-3, "({x}, {y}) lies inside every edge");
600            }
601        }
602    }
603
604    #[test]
605    fn an_arc_reaches_the_part_of_its_circle_it_sweeps() {
606        let mut reach = Reach::default();
607        reach.point(10.0, 0.0);
608        reach.point(0.0, 10.0);
609        reach.arc([0.0, 0.0], 10.0, 0.0, core::f64::consts::FRAC_PI_2);
610        let outline = reach.outline().expect("points were given");
611        let furthest = outline
612            .hull_mm
613            .iter()
614            .map(|[x, y]| f64::from(*x).hypot(f64::from(*y)))
615            .fold(0.0, f64::max);
616        assert!((10.0..10.1).contains(&furthest), "{furthest}");
617    }
618
619    #[test]
620    fn no_point_is_no_outline_and_types_map_to_kinds() {
621        assert!(Reach::default().outline().is_none());
622        assert_eq!(ExtrusionKind::of_type("Perimeter"), ExtrusionKind::Wall);
623        assert_eq!(
624            ExtrusionKind::of_type("Gap fill"),
625            ExtrusionKind::SolidInfill
626        );
627        assert_eq!(
628            ExtrusionKind::of_type("Internal infill"),
629            ExtrusionKind::SparseInfill
630        );
631        assert_eq!(
632            ExtrusionKind::of_type("Top solid infill"),
633            ExtrusionKind::TopSolidInfill
634        );
635        assert_eq!(
636            ExtrusionKind::of_type("Support material interface"),
637            ExtrusionKind::Support
638        );
639        assert_eq!(ExtrusionKind::of_type("Skirt/Brim"), ExtrusionKind::Other);
640    }
641}