1use std::path::{Path, PathBuf};
13
14use printobserver_types::PrintId;
15
16pub const OUTLINE_DIRECTIONS: usize = 64;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum ExtrusionKind {
22 Wall,
24 Infill,
26 Support,
28 Bridge,
30 Overhang,
32 Other,
35}
36
37impl ExtrusionKind {
38 #[must_use]
40 pub fn of_type(name: &str) -> Self {
41 match name {
42 "External perimeter" | "Perimeter" => Self::Wall,
43 "Internal infill" | "Solid infill" | "Top solid infill" | "Gap fill" => Self::Infill,
44 "Support material" | "Support material interface" => Self::Support,
45 "Bridge infill" => Self::Bridge,
46 "Overhang perimeter" => Self::Overhang,
47 _ => Self::Other,
48 }
49 }
50
51 #[must_use]
53 pub const fn is_support(self) -> bool {
54 matches!(self, Self::Support)
55 }
56}
57
58#[derive(Debug, Clone, PartialEq)]
62pub struct ObjectOutline {
63 pub hull_mm: Vec<[f32; 2]>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
69pub struct LayerRef(pub(crate) usize);
70
71impl LayerRef {
72 #[must_use]
75 pub const fn of_index(index: usize) -> Self {
76 Self(index)
77 }
78
79 #[must_use]
81 pub const fn index(self) -> usize {
82 self.0
83 }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq)]
88pub struct ToolpathSegment {
89 pub from_mm: [f32; 2],
91 pub to_mm: [f32; 2],
93 pub kind: ExtrusionKind,
95}
96
97#[derive(Debug, Clone, PartialEq)]
99pub struct LayerToolpath {
100 pub z_mm: f32,
102 pub segments: Vec<ToolpathSegment>,
104}
105
106impl LayerToolpath {
107 #[must_use]
111 pub fn carries_object_extrusion(&self) -> bool {
112 self.segments
113 .iter()
114 .any(|segment| !segment.kind.is_support())
115 }
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum SpoolError {
121 NoSpool,
123 UnknownLayer,
125 Io {
127 detail: String,
129 },
130}
131
132impl core::fmt::Display for SpoolError {
133 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
134 match self {
135 Self::NoSpool => formatter.write_str("the print's G-code was indexed with no spool"),
136 Self::UnknownLayer => formatter.write_str("no such layer in the print's index"),
137 Self::Io { detail } => write!(formatter, "the print's G-code spool: {detail}"),
138 }
139 }
140}
141
142impl std::error::Error for SpoolError {}
143
144#[must_use]
146pub fn spool_path(directory: &Path, print_id: PrintId) -> PathBuf {
147 directory.join(format!("{print_id}{SPOOL_SUFFIX}"))
148}
149
150pub(crate) const SPOOL_SUFFIX: &str = ".gcode";
152
153fn direction(k: usize) -> [f64; 2] {
155 let angle = core::f64::consts::TAU * f64::from(u32::try_from(k).unwrap_or(0))
156 / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
157 [angle.cos(), angle.sin()]
158}
159
160#[derive(Debug, Clone, PartialEq)]
165pub(crate) struct Reach {
166 extent: [f64; OUTLINE_DIRECTIONS],
168 any: bool,
170 inside: ([f64; 2], f64),
174}
175
176impl Default for Reach {
177 fn default() -> Self {
178 Self {
179 extent: [f64::NEG_INFINITY; OUTLINE_DIRECTIONS],
180 any: false,
181 inside: ([0.0, 0.0], -1.0),
182 }
183 }
184}
185
186fn directions() -> &'static [[f64; 2]; OUTLINE_DIRECTIONS] {
188 static HELD: std::sync::OnceLock<[[f64; 2]; OUTLINE_DIRECTIONS]> = std::sync::OnceLock::new();
189 HELD.get_or_init(|| {
190 let mut held = [[0.0; 2]; OUTLINE_DIRECTIONS];
191 let mut k = 0;
192 while k < OUTLINE_DIRECTIONS {
193 held[k] = direction(k);
194 k += 1;
195 }
196 held
197 })
198}
199
200impl Reach {
201 pub(crate) fn point(&mut self, x: f64, y: f64) {
204 let ([cx, cy], radius) = self.inside;
205 let (dx, dy) = (x - cx, y - cy);
206 if radius > 0.0 && dx * dx + dy * dy < radius * radius {
207 return;
208 }
209 let held = directions();
210 self.any = true;
211 let mut grew = false;
214 let mut k = 0;
215 while k < OUTLINE_DIRECTIONS {
216 let along = held[k][0] * x + held[k][1] * y;
217 if along > self.extent[k] {
218 self.extent[k] = along;
219 grew = true;
220 }
221 k += 1;
222 }
223 if grew {
224 self.refit_inside();
225 }
226 }
227
228 fn refit_inside(&mut self) {
232 let quarter = OUTLINE_DIRECTIONS / 4;
233 let (right, up) = (self.extent[0], self.extent[quarter]);
234 let (left, down) = (-self.extent[2 * quarter], -self.extent[3 * quarter]);
235 if !(right.is_finite() && up.is_finite() && left.is_finite() && down.is_finite()) {
236 return;
237 }
238 let centre = [f64::midpoint(right, left), f64::midpoint(up, down)];
239 let held = directions();
240 let mut radius = f64::INFINITY;
241 let mut k = 0;
242 while k < OUTLINE_DIRECTIONS {
243 let gap = self.extent[k] - (held[k][0] * centre[0] + held[k][1] * centre[1]);
244 radius = radius.min(gap);
245 k += 1;
246 }
247 self.inside = (centre, radius);
248 }
249
250 pub(crate) fn arc(&mut self, centre: [f64; 2], radius: f64, from: f64, sweep: f64) {
255 let tau = core::f64::consts::TAU;
256 let held = directions();
257 for (k, unit) in held.iter().enumerate() {
258 let angle = tau * f64::from(u32::try_from(k).unwrap_or(0))
259 / f64::from(u32::try_from(OUTLINE_DIRECTIONS).unwrap_or(1));
260 if (angle - from).rem_euclid(tau) <= sweep + 1e-9 {
261 let along = unit[0] * centre[0] + unit[1] * centre[1] + radius;
262 if along > self.extent[k] {
263 self.extent[k] = along;
264 self.any = true;
265 }
266 }
267 }
268 self.refit_inside();
269 }
270
271 pub(crate) fn outline(&self) -> Option<ObjectOutline> {
274 if !self.any {
275 return None;
276 }
277 let far = 1e6;
279 let mut polygon = vec![[-far, -far], [far, -far], [far, far], [-far, far]];
280 for (unit, extent) in directions().iter().zip(self.extent) {
281 polygon = clip(&polygon, *unit, extent);
282 if polygon.is_empty() {
283 return None;
284 }
285 }
286 let mut hull: Vec<[f32; 2]> = Vec::with_capacity(polygon.len());
287 for [x, y] in polygon {
288 #[expect(
289 clippy::cast_possible_truncation,
290 reason = "bed millimetres are far inside f32's range; the outline is drawn, not measured"
291 )]
292 let vertex = [x as f32, y as f32];
293 let repeats = hull.last().is_some_and(|last: &[f32; 2]| {
294 (last[0] - vertex[0]).abs() < 1e-4 && (last[1] - vertex[1]).abs() < 1e-4
295 });
296 if !repeats {
297 hull.push(vertex);
298 }
299 }
300 while hull.len() > 1
301 && hull.first().zip(hull.last()).is_some_and(|(first, last)| {
302 (first[0] - last[0]).abs() < 1e-4 && (first[1] - last[1]).abs() < 1e-4
303 })
304 {
305 hull.pop();
306 }
307 Some(ObjectOutline { hull_mm: hull })
308 }
309}
310
311fn clip(polygon: &[[f64; 2]], unit: [f64; 2], extent: f64) -> Vec<[f64; 2]> {
314 let inside = |p: [f64; 2]| unit[0] * p[0] + unit[1] * p[1] - extent;
315 let mut kept = Vec::with_capacity(polygon.len() + 1);
316 for (at, point) in polygon.iter().enumerate() {
317 let next = polygon[(at + 1) % polygon.len()];
318 let (here, there) = (inside(*point), inside(next));
319 if here <= 0.0 {
320 kept.push(*point);
321 }
322 if (here <= 0.0) != (there <= 0.0) {
323 let t = here / (here - there);
324 kept.push([
325 point[0] + t * (next[0] - point[0]),
326 point[1] + t * (next[1] - point[1]),
327 ]);
328 }
329 }
330 kept
331}
332
333#[cfg(test)]
334mod tests {
335 use super::{ExtrusionKind, OUTLINE_DIRECTIONS, Reach};
336
337 fn area(hull: &[[f32; 2]]) -> f64 {
339 let mut twice = 0.0;
340 for (at, a) in hull.iter().enumerate() {
341 let b = hull[(at + 1) % hull.len()];
342 twice += f64::from(a[0]) * f64::from(b[1]) - f64::from(b[0]) * f64::from(a[1]);
343 }
344 twice / 2.0
345 }
346
347 #[test]
348 fn an_outline_holds_every_point_counter_clockwise_and_is_bounded() {
349 let mut reach = Reach::default();
350 let points = [
351 [10.0, 10.0],
352 [30.0, 12.0],
353 [25.0, 40.0],
354 [12.0, 33.0],
355 [20.0, 20.0],
356 ];
357 for [x, y] in points {
358 reach.point(x, y);
359 }
360 let outline = reach.outline().expect("points were given");
361 assert!(outline.hull_mm.len() <= OUTLINE_DIRECTIONS);
362 assert!(area(&outline.hull_mm) > 0.0, "counter-clockwise");
363 for [x, y] in points {
364 for (at, a) in outline.hull_mm.iter().enumerate() {
365 let b = outline.hull_mm[(at + 1) % outline.hull_mm.len()];
366 let cross = (f64::from(b[0]) - f64::from(a[0])) * (y - f64::from(a[1]))
367 - (f64::from(b[1]) - f64::from(a[1])) * (x - f64::from(a[0]));
368 assert!(cross >= -1e-3, "({x}, {y}) lies inside every edge");
369 }
370 }
371 }
372
373 #[test]
374 fn an_arc_reaches_the_part_of_its_circle_it_sweeps() {
375 let mut reach = Reach::default();
376 reach.point(10.0, 0.0);
377 reach.point(0.0, 10.0);
378 reach.arc([0.0, 0.0], 10.0, 0.0, core::f64::consts::FRAC_PI_2);
379 let outline = reach.outline().expect("points were given");
380 let furthest = outline
381 .hull_mm
382 .iter()
383 .map(|[x, y]| f64::from(*x).hypot(f64::from(*y)))
384 .fold(0.0, f64::max);
385 assert!((10.0..10.1).contains(&furthest), "{furthest}");
386 }
387
388 #[test]
389 fn no_point_is_no_outline_and_types_map_to_kinds() {
390 assert!(Reach::default().outline().is_none());
391 assert_eq!(ExtrusionKind::of_type("Perimeter"), ExtrusionKind::Wall);
392 assert_eq!(ExtrusionKind::of_type("Gap fill"), ExtrusionKind::Infill);
393 assert_eq!(
394 ExtrusionKind::of_type("Support material interface"),
395 ExtrusionKind::Support
396 );
397 assert_eq!(ExtrusionKind::of_type("Skirt/Brim"), ExtrusionKind::Other);
398 }
399}