1use core::future::Future;
67use core::ops::ControlFlow;
68use core::pin::Pin;
69use core::task::{Context, Poll, Waker};
70use std::collections::BTreeMap;
71use std::sync::{Arc, Mutex, PoisonError};
72
73use printobserver_printer_api::GcodeSink;
74use printobserver_types::contract::Sample;
75use printobserver_types::schemars::JsonSchema;
76use printobserver_types::serde::{Deserialize, Serialize};
77use printobserver_types::{PrintId, Timestamp};
78
79use crate::toolpath::{
80 ExtrusionKind, LayerRef, LayerToolpath, ObjectOutline, Reach, SpoolError, ToolpathSegment,
81};
82
83const LINE_LIMIT: usize = 4096;
88
89const TYPE_LIMIT: usize = 64;
92
93const RISE_WINDOW_S: i64 = 30 * 60;
96
97const LAYERS_SHOWN_BELOW: usize = 5;
100
101const FLOW_WELL_UNDER_ONE: f64 = 0.9;
103
104const OVER_AIR: [&str; 2] = ["Bridge infill", "Overhang perimeter"];
106
107const SUPPORTS: [&str; 2] = ["Support material", "Support material interface"];
109
110const WALLS: [&str; 2] = ["Perimeter", "External perimeter"];
112
113const OBJECT_LIMIT: usize = 1024;
115
116const AXIS_LIMIT: f64 = 1e4;
119
120const WORD_LIMIT: f64 = 1e7;
123
124const WORD_COUNT: usize = 8;
126
127const TRAVEL_MM: f64 = 1e-6;
129
130const NOT_THE_PART: &str = "Custom";
132
133const FAN_FULL: f64 = 255.0;
135
136const CHORD_MM: f64 = 0.5;
138
139#[derive(Debug, Clone, Copy, PartialEq)]
142struct Head {
143 at: [f64; 3],
145 e: f64,
147 axes: Positioning,
149 extruder: Positioning,
151 current_type: Option<usize>,
153}
154
155#[derive(Debug, Clone, PartialEq)]
157struct Layer {
158 begins: u64,
160 at: u64,
162 head: Head,
164 z_mm: Option<f64>,
166 types: u64,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq)]
173struct Mark<T> {
174 at: u64,
176 value: T,
178}
179
180#[derive(Debug, Clone, Default, PartialEq)]
182struct ObjectDraft {
183 bounds: Option<[f64; 4]>,
185 reach: Reach,
187}
188
189#[derive(Debug, Clone, PartialEq)]
191pub struct GcodeIndex {
192 bytes: u64,
194 lines: u64,
196 layers: Vec<Layer>,
198 type_names: Vec<String>,
200 labelled_types: bool,
202 time_left: Vec<Mark<i64>>,
204 flow: Vec<Mark<f64>>,
206 fan: Vec<Mark<f64>>,
208 objects: Vec<BedArea>,
210 labelled_objects: bool,
212 outlines: Vec<ObjectOutline>,
215 blocks: Vec<(u64, Option<usize>)>,
218 spool: Option<std::path::PathBuf>,
220}
221
222#[derive(Debug, Clone, Copy, PartialEq)]
225pub struct SetInFile {
226 pub value: f64,
228 pub at: u64,
230}
231
232impl GcodeIndex {
233 #[must_use]
235 pub const fn bytes(&self) -> u64 {
236 self.bytes
237 }
238
239 #[must_use]
241 pub const fn lines(&self) -> u64 {
242 self.lines
243 }
244
245 #[must_use]
247 pub const fn layer_count(&self) -> usize {
248 self.layers.len()
249 }
250
251 #[must_use]
254 pub const fn entries(&self) -> usize {
255 self.layers.len()
256 + self.time_left.len()
257 + self.flow.len()
258 + self.fan.len()
259 + self.objects.len()
260 }
261
262 #[must_use]
265 pub fn resident_bytes(&self) -> usize {
266 let names: usize = self.type_names.iter().map(String::capacity).sum();
267 core::mem::size_of::<Self>()
268 + self.layers.capacity() * core::mem::size_of::<Layer>()
269 + self.type_names.capacity() * core::mem::size_of::<String>()
270 + names
271 + self.time_left.capacity() * core::mem::size_of::<Mark<i64>>()
272 + self.flow.capacity() * core::mem::size_of::<Mark<f64>>()
273 + self.fan.capacity() * core::mem::size_of::<Mark<f64>>()
274 + self.objects.capacity() * core::mem::size_of::<BedArea>()
275 + self.outlines.capacity() * core::mem::size_of::<ObjectOutline>()
276 + self
277 .outlines
278 .iter()
279 .map(|outline| outline.hull_mm.capacity() * core::mem::size_of::<[f32; 2]>())
280 .sum::<usize>()
281 + self.blocks.capacity() * core::mem::size_of::<(u64, Option<usize>)>()
282 }
283
284 #[must_use]
288 pub fn object_outlines(&self) -> &[ObjectOutline] {
289 &self.outlines
290 }
291
292 #[must_use]
297 pub fn object_at(&self, file_position_bytes: u64) -> Option<usize> {
298 if !self.labelled_objects {
299 return (!self.outlines.is_empty()).then_some(0);
300 }
301 let started = self
302 .blocks
303 .partition_point(|(start, _)| *start <= file_position_bytes);
304 self.blocks[..started]
305 .iter()
306 .rev()
307 .find_map(|(_, outline)| *outline)
308 }
309
310 #[must_use]
312 pub fn layer_at(&self, file_position_bytes: u64) -> Option<LayerRef> {
313 self.layers
314 .iter()
315 .rposition(|layer| layer.at <= file_position_bytes)
316 .map(LayerRef)
317 }
318
319 #[must_use]
321 pub fn layer_z_mm(&self, layer: LayerRef) -> Option<f64> {
322 self.layers.get(layer.0).and_then(|held| held.z_mm)
323 }
324
325 fn lays_object(&self, layer: &Layer) -> bool {
330 layer.types & !self.type_bits(&SUPPORTS) != 0
331 }
332
333 #[must_use]
336 pub fn object_layer_at_or_below(&self, layer: LayerRef) -> Option<LayerRef> {
337 let held = self.layers.get(..=layer.0)?;
338 held.iter()
339 .rposition(|layer| self.lays_object(layer))
340 .map(LayerRef)
341 }
342
343 #[must_use]
346 pub fn first_object_layer(&self) -> Option<(LayerRef, u64)> {
347 let first = self
348 .layers
349 .iter()
350 .position(|layer| self.lays_object(layer))?;
351 Some((LayerRef(first), self.layer_end(first)))
352 }
353
354 fn layer_end(&self, index: usize) -> u64 {
356 self.layers
357 .get(index + 1)
358 .map_or(self.bytes, |next| next.begins)
359 }
360
361 pub fn layer_toolpath(&self, layer: LayerRef) -> Result<LayerToolpath, SpoolError> {
370 use std::io::{Read as _, Seek as _, SeekFrom};
371
372 let held = self.layers.get(layer.0).ok_or(SpoolError::UnknownLayer)?;
373 let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
374 let io = |error: std::io::Error| SpoolError::Io {
375 detail: error.to_string(),
376 };
377 let length =
378 usize::try_from(self.layer_end(layer.0).saturating_sub(held.at)).map_err(|_| {
379 SpoolError::Io {
380 detail: "a layer too long to hold".to_owned(),
381 }
382 })?;
383 let mut file = std::fs::File::open(path).map_err(io)?;
384 file.seek(SeekFrom::Start(held.at)).map_err(io)?;
385 let mut bytes = vec![0; length];
386 file.read_exact(&mut bytes).map_err(io)?;
387 let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head);
388 let _ = builder.take(&bytes);
389 if !builder.line.is_empty() {
390 builder.end_line();
391 }
392 #[expect(
393 clippy::cast_possible_truncation,
394 reason = "a layer height is a few hundred millimetres at most"
395 )]
396 let z_mm = held.z_mm.unwrap_or(0.0) as f32;
397 Ok(LayerToolpath {
398 z_mm,
399 segments: builder.collected.unwrap_or_default(),
400 })
401 }
402
403 #[must_use]
407 pub fn busiest_layer(&self) -> Option<(usize, i64)> {
408 self.layers
409 .iter()
410 .map(|layer| {
411 (
412 usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
413 i64::try_from(layer.at).unwrap_or(i64::MAX),
414 )
415 })
416 .reduce(|best, next| if next.0 > best.0 { next } else { best })
417 }
418
419 #[must_use]
421 pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
422 last_at(&self.flow, position).map(|mark| SetInFile {
423 value: mark.value,
424 at: mark.at,
425 })
426 }
427
428 #[must_use]
431 pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
432 last_at(&self.fan, position).map(|mark| SetInFile {
433 value: mark.value,
434 at: mark.at,
435 })
436 }
437
438 #[must_use]
441 pub fn plan_at(&self, position: i64) -> SlicerPlan {
442 self.plan_with(position, None, None)
443 }
444
445 #[must_use]
449 pub fn plan_with(
450 &self,
451 position: i64,
452 flow_changed: Option<f64>,
453 fan_changed: Option<f64>,
454 ) -> SlicerPlan {
455 let mut unknown = Vec::new();
456 let layer_index = self
457 .layers
458 .iter()
459 .rposition(|layer| reached(layer.at, position));
460 let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
461 if self.layers.is_empty() {
462 unknown.push(PlanFact::Layer);
463 }
464 if final_z_mm.is_none() {
465 unknown.push(PlanFact::FinalZ);
466 }
467 if !self.labelled_types {
468 unknown.push(PlanFact::Types);
469 }
470 let types = layer_index.map_or_else(Vec::new, |index| {
471 let bits = self.layers[index].types;
472 self.type_names
473 .iter()
474 .enumerate()
475 .filter(|(bit, _)| bits & (1 << bit) != 0)
476 .map(|(_, name)| name.clone())
477 .collect()
478 });
479 let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
480 if minutes_left.is_none() {
481 unknown.push(PlanFact::MinutesLeft);
482 }
483 let flow_factor = set_value(
484 self.flow_at(position).map(|set| set.value),
485 flow_changed,
486 PlanFact::FlowFactor,
487 &mut unknown,
488 );
489 let fan_percent = set_value(
490 self.fan_at(position).map(|set| set.value),
491 fan_changed,
492 PlanFact::FanPercent,
493 &mut unknown,
494 );
495 if !self.labelled_objects {
496 unknown.push(PlanFact::Objects);
497 }
498 unknown.sort_unstable();
499 let in_force =
500 |set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
501 let mut at_odds = Vec::new();
502 if let Some(index) = layer_index {
503 let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
504 .iter()
505 .fold(0, |bits, layer| bits | layer.types);
506 if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
507 && shown & self.type_bits(&OVER_AIR) != 0
508 {
509 at_odds.push(PlanMismatch::FanOffOverBridges);
510 }
511 if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
512 && self.layers[index].types & self.type_bits(&WALLS) != 0
513 {
514 at_odds.push(PlanMismatch::FlowLowOverWalls);
515 }
516 }
517 SlicerPlan {
518 layer: layer_index.map(|index| index + 1),
519 z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
520 final_z_mm,
521 types,
522 minutes_left,
523 flow_factor,
524 fan_percent,
525 object_count: self.labelled_objects.then_some(self.objects.len()),
526 objects: self.objects.clone(),
527 rise: None,
528 at_odds,
529 unknown,
530 }
531 }
532
533 fn type_bits(&self, names: &[&str]) -> u64 {
535 self.type_names
536 .iter()
537 .enumerate()
538 .filter(|(_, name)| names.contains(&name.as_str()))
539 .fold(0, |bits, (bit, _)| bits | (1 << bit))
540 }
541
542 #[must_use]
551 pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
552 self.height_and_rise_since(earlier, now)
553 .map(|[_, risen]| risen)
554 }
555
556 #[must_use]
560 pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
561 let at = |position| {
562 self.layers
563 .iter()
564 .rposition(|layer| reached(layer.at, position))
565 .filter(|index| self.layers[*index].z_mm.is_some())
566 };
567 let (then, now) = (at(earlier)?, at(now)?);
568 let supports = self.type_bits(&SUPPORTS);
569 let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
570 let mut top = self.layers[..=then]
573 .iter()
574 .rev()
575 .filter(lays_the_part)
576 .find_map(|layer| layer.z_mm)
577 .or(self.layers[then].z_mm)?;
578 let height = top;
579 let mut risen = 0.0;
580 for layer in self
581 .layers
582 .iter()
583 .take(now + 1)
584 .skip(then + 1)
585 .filter(lays_the_part)
586 {
587 let Some(z) = layer.z_mm else { continue };
588 risen += (z - top).max(0.0);
589 top = top.max(z);
590 }
591 let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
592 Some([tenth(height), tenth(risen)])
593 }
594}
595
596fn set_value(
599 file: Option<f64>,
600 changed: Option<f64>,
601 fact: PlanFact,
602 unknown: &mut Vec<PlanFact>,
603) -> Option<SetValue> {
604 if file.is_none() {
605 unknown.push(fact);
606 }
607 (file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
608}
609
610fn reached(at: u64, position: i64) -> bool {
612 u64::try_from(position).is_ok_and(|position| at <= position)
613}
614
615fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
617 let Ok(position) = u64::try_from(position) else {
618 return None;
619 };
620 let reached = marks.partition_point(|mark| mark.at <= position);
621 reached.checked_sub(1).map(|index| marks[index])
622}
623
624#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
627#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
628#[schemars(crate = "printobserver_types::schemars")]
629pub struct SetValue {
630 #[serde(default, skip_serializing_if = "Option::is_none")]
632 pub file: Option<f64>,
633 #[serde(default, skip_serializing_if = "Option::is_none")]
636 pub changed: Option<f64>,
637}
638
639pub type BedArea = [i64; 4];
644
645#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
648#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
649#[schemars(crate = "printobserver_types::schemars")]
650pub struct Rise {
651 pub since: Timestamp,
656 pub mm: [f64; 2],
662}
663
664#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
667#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
668#[schemars(crate = "printobserver_types::schemars")]
669pub enum PlanMismatch {
670 FanOffOverBridges,
673 FlowLowOverWalls,
675}
676
677#[derive(
679 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
680)]
681#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
682#[schemars(crate = "printobserver_types::schemars")]
683pub enum PlanFact {
684 Layer,
686 FinalZ,
688 Types,
690 MinutesLeft,
692 FlowFactor,
694 FanPercent,
696 Objects,
698 Rise,
702}
703
704#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
711#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
712#[schemars(crate = "printobserver_types::schemars")]
713pub struct SlicerPlan {
714 #[serde(default, skip_serializing_if = "Option::is_none")]
717 pub layer: Option<usize>,
718 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub z_mm: Option<f64>,
721 #[serde(default, skip_serializing_if = "Option::is_none")]
723 pub final_z_mm: Option<f64>,
724 #[serde(default, skip_serializing_if = "Vec::is_empty")]
727 pub types: Vec<String>,
728 #[serde(default, skip_serializing_if = "Option::is_none")]
730 pub minutes_left: Option<i64>,
731 #[serde(default, skip_serializing_if = "Option::is_none")]
733 pub flow_factor: Option<SetValue>,
734 #[serde(default, skip_serializing_if = "Option::is_none")]
736 pub fan_percent: Option<SetValue>,
737 #[serde(default, skip_serializing_if = "Option::is_none")]
739 pub object_count: Option<usize>,
740 #[serde(default, skip_serializing_if = "Vec::is_empty")]
744 pub objects: Vec<BedArea>,
745 #[serde(default, skip_serializing_if = "Option::is_none")]
748 pub rise: Option<Rise>,
749 #[serde(default, skip_serializing_if = "Vec::is_empty")]
751 pub at_odds: Vec<PlanMismatch>,
752 #[serde(default, skip_serializing_if = "Vec::is_empty")]
755 pub unknown: Vec<PlanFact>,
756}
757
758impl Sample for SlicerPlan {
759 fn sample_full() -> Self {
760 Self {
761 layer: Some(12),
762 z_mm: Some(2.4),
763 types: vec![
764 "Perimeter".to_owned(),
765 "External perimeter".to_owned(),
766 "Support material".to_owned(),
767 ],
768 final_z_mm: Some(30.0),
769 minutes_left: Some(42),
770 flow_factor: Some(SetValue {
771 file: Some(1.0),
772 changed: Some(0.95),
773 }),
774 fan_percent: Some(SetValue {
775 file: Some(100.0),
776 changed: None,
777 }),
778 object_count: Some(1),
779 objects: vec![[100, 99, 150, 117]],
780 rise: Some(Rise {
781 since: Timestamp::sample_full(),
782 mm: [7.2, 4.8],
783 }),
784 at_odds: vec![PlanMismatch::FlowLowOverWalls],
785 unknown: vec![PlanFact::Objects],
786 }
787 }
788
789 fn sample_minimal() -> Self {
790 Self {
791 layer: None,
792 z_mm: None,
793 final_z_mm: None,
794 types: Vec::new(),
795 minutes_left: None,
796 flow_factor: None,
797 fan_percent: None,
798 object_count: None,
799 objects: Vec::new(),
800 rise: None,
801 at_odds: Vec::new(),
802 unknown: Vec::new(),
803 }
804 }
805}
806
807#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
809enum Positioning {
810 #[default]
812 Absolute,
813 Relative,
815}
816
817#[derive(Debug, Default)]
820pub struct IndexBuilder {
821 line: Vec<u8>,
823 overlong: bool,
825 read: u64,
827 lines: u64,
829 layers: Vec<Layer>,
831 type_names: Vec<String>,
833 labelled_types: bool,
835 current_type: Option<usize>,
837 time_left: Vec<Mark<i64>>,
839 flow: Vec<Mark<f64>>,
841 fan: Vec<Mark<f64>>,
843 objects: Vec<ObjectDraft>,
845 object_numbers: BTreeMap<i64, usize>,
847 current_object: Option<usize>,
850 labelled_objects: bool,
852 at: [f64; 3],
854 e: f64,
856 axes: Positioning,
858 extruder: Positioning,
860 line_began: u64,
862 all: Reach,
864 blocks: Vec<(u64, usize)>,
867 spool: Option<Spooling>,
869 collected: Option<Vec<ToolpathSegment>>,
871 reached_last: Option<[f64; 2]>,
873}
874
875#[derive(Debug)]
877struct Spooling {
878 path: std::path::PathBuf,
880 writer: std::io::BufWriter<std::fs::File>,
882 failed: bool,
884}
885
886impl GcodeSink for IndexBuilder {
887 fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
888 if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
898 use std::io::Write as _;
899 spool.failed = spool.writer.write_all(piece).is_err();
900 }
901 let mut start = 0;
902 let mut at = 0;
903 while at < piece.len() {
904 if piece[at] == b'\n' {
905 let head = &piece[start..at];
906 self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
907 if self.line.is_empty() && !self.overlong {
908 self.lines += 1;
910 if head.len() <= LINE_LIMIT {
911 self.read_line(head);
912 }
913 } else {
914 self.hold(head);
915 self.end_line();
916 }
917 self.line_began = self.read;
918 start = at + 1;
919 }
920 at += 1;
921 }
922 let rest = &piece[start..];
923 self.hold(rest);
924 self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
925 ControlFlow::Continue(())
926 }
927}
928
929impl IndexBuilder {
930 #[must_use]
932 pub fn new() -> Self {
933 Self::default()
934 }
935
936 pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
944 let file = std::fs::File::create(&path)?;
945 Ok(Self {
946 spool: Some(Spooling {
947 path,
948 writer: std::io::BufWriter::with_capacity(1 << 16, file),
949 failed: false,
950 }),
951 ..Self::default()
952 })
953 }
954
955 fn reading_layer(type_names: Vec<String>, head: Head) -> Self {
958 Self {
959 type_names,
960 labelled_types: true,
961 current_type: head.current_type,
962 at: head.at,
963 e: head.e,
964 axes: head.axes,
965 extruder: head.extruder,
966 collected: Some(Vec::new()),
967 ..Self::default()
968 }
969 }
970
971 #[must_use]
974 pub fn finish(mut self) -> GcodeIndex {
975 if !self.line.is_empty() || self.overlong {
976 self.end_line();
977 }
978 let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
979 let mut objects = Vec::new();
980 let mut outlines = Vec::new();
981 let mut outline_of = vec![None; drafts.len()];
982 for place in self.object_numbers.into_values() {
983 let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
984 continue;
985 };
986 let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
987 continue;
988 };
989 objects.push([
990 whole(tenth(least_x).floor()),
991 whole(tenth(least_y).floor()),
992 whole(tenth(most_x).ceil()),
993 whole(tenth(most_y).ceil()),
994 ]);
995 outline_of[place] = Some(outlines.len());
996 outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
997 hull_mm: Vec::new(),
998 }));
999 }
1000 if !self.labelled_objects {
1001 outlines.extend(self.all.outline());
1002 }
1003 let blocks = self
1004 .blocks
1005 .into_iter()
1006 .map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
1007 .collect();
1008 let spool = self.spool.and_then(|mut spool| {
1009 use std::io::Write as _;
1010 if spool.failed || spool.writer.flush().is_err() {
1011 drop(spool.writer);
1012 let _ = std::fs::remove_file(&spool.path);
1013 return None;
1014 }
1015 Some(spool.path)
1016 });
1017 GcodeIndex {
1018 bytes: self.read,
1019 lines: self.lines,
1020 layers: self.layers,
1021 type_names: self.type_names,
1022 labelled_types: self.labelled_types,
1023 time_left: self.time_left,
1024 flow: self.flow,
1025 fan: self.fan,
1026 objects,
1027 labelled_objects: self.labelled_objects,
1028 outlines,
1029 blocks,
1030 spool,
1031 }
1032 }
1033
1034 fn hold(&mut self, bytes: &[u8]) {
1036 if self.overlong {
1037 return;
1038 }
1039 if self.line.len() + bytes.len() > LINE_LIMIT {
1040 self.overlong = true;
1041 self.line.clear();
1042 return;
1043 }
1044 self.line.extend_from_slice(bytes);
1045 }
1046
1047 fn end_line(&mut self) {
1049 self.lines += 1;
1050 let line = core::mem::take(&mut self.line);
1051 if !self.overlong {
1052 self.read_line(&line);
1053 }
1054 self.overlong = false;
1055 self.line = line;
1056 self.line.clear();
1057 }
1058
1059 fn read_line(&mut self, raw: &[u8]) {
1061 let raw = raw.trim_ascii();
1062 if let Some(comment) = raw.strip_prefix(b";") {
1063 if let Ok(comment) = core::str::from_utf8(comment) {
1064 self.comment(comment.trim_end());
1065 }
1066 return;
1067 }
1068 if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
1071 self.motion(u32::from(code - b'0'), &move_of(rest));
1072 return;
1073 }
1074 let held = words(raw);
1075 let mut words = held.as_slice();
1076 if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
1078 words = rest;
1079 }
1080 let Some(first) = words.first() else {
1081 return;
1082 };
1083 let code = if held.numbered {
1084 held.second_code
1085 } else {
1086 held.first_code
1087 };
1088 match (char::from(first.letter), code) {
1089 ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
1090 ('G', Some(28)) => self.home(&words[1..]),
1091 ('G', Some(90)) => self.axes = Positioning::Absolute,
1092 ('G', Some(91)) => self.axes = Positioning::Relative,
1093 ('G', Some(92)) => self.declare(&words[1..]),
1094 ('M', Some(82)) => self.extruder = Positioning::Absolute,
1095 ('M', Some(83)) => self.extruder = Positioning::Relative,
1096 ('M', Some(73)) => self.estimate(&words[1..]),
1097 ('M', Some(221)) => self.flow_factor(&words[1..]),
1098 ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
1099 ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
1100 ('M', Some(486)) => self.object(raw, &words[1..]),
1101 _ => {}
1102 }
1103 }
1104
1105 fn comment(&mut self, comment: &str) {
1107 if comment == "LAYER_CHANGE" {
1108 self.layers.push(Layer {
1109 begins: self.line_began,
1110 head: Head {
1111 at: self.at,
1112 e: self.e,
1113 axes: self.axes,
1114 extruder: self.extruder,
1115 current_type: self.current_type,
1116 },
1117 at: self.read,
1118 z_mm: None,
1119 types: 0,
1120 });
1121 } else if let Some(z) = comment.strip_prefix("Z:") {
1122 if let Some(layer) = self.layers.last_mut()
1123 && layer.z_mm.is_none()
1124 {
1125 layer.z_mm = z
1128 .trim()
1129 .parse::<f64>()
1130 .ok()
1131 .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
1132 }
1133 } else if let Some(name) = comment.strip_prefix("TYPE:") {
1134 let name = name.trim();
1135 self.labelled_types = true;
1136 self.current_type = if name == NOT_THE_PART {
1137 None
1138 } else {
1139 self.intern(name)
1140 };
1141 }
1142 }
1143
1144 fn intern(&mut self, name: &str) -> Option<usize> {
1146 if let Some(bit) = self.type_names.iter().position(|held| held == name) {
1147 return Some(bit);
1148 }
1149 if self.type_names.len() >= TYPE_LIMIT {
1150 return None;
1151 }
1152 self.type_names.push(name.to_owned());
1153 Some(self.type_names.len() - 1)
1154 }
1155
1156 fn motion(&mut self, code: u32, words: &Move) {
1158 let start = self.at;
1161 let relative = self.axes == Positioning::Relative;
1162 if let Some(x) = words.x {
1163 self.place(0, x, relative);
1164 }
1165 if let Some(y) = words.y {
1166 self.place(1, y, relative);
1167 }
1168 if let Some(z) = words.z {
1169 self.place(2, z, relative);
1170 }
1171 let mut fed = 0.0;
1172 if let Some(value) = words.e {
1173 if relative || self.extruder == Positioning::Relative {
1174 self.e += value;
1175 fed = value;
1176 } else {
1177 fed = value - self.e;
1178 self.e = value;
1179 }
1180 }
1181 let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
1182 if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
1183 return;
1184 }
1185 if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
1186 layer.types |= 1 << bit;
1187 }
1188 let end = self.at;
1189 let turn = match code {
1190 2 => Some(Turn::Clockwise),
1191 3 => Some(Turn::CounterClockwise),
1192 _ => None,
1193 };
1194 let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
1195 if let Some(collected) = self.collected.as_mut() {
1196 let kind = self
1197 .current_type
1198 .and_then(|bit| self.type_names.get(bit))
1199 .map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
1200 collect_segments(collected, kind, start, end, arc);
1201 return;
1202 }
1203 let part_of_plan = !(self.labelled_types && self.current_type.is_none());
1204 let reach = if let Some(object) = self.current_object {
1205 let draft = &mut self.objects[object];
1206 grow(&mut draft.bounds, start[0], start[1]);
1207 grow(&mut draft.bounds, end[0], end[1]);
1208 if let Some(turn) = turn {
1209 for [x, y] in arc_extremes(words, turn, start, end) {
1210 grow(&mut draft.bounds, x, y);
1211 }
1212 }
1213 &mut draft.reach
1214 } else if !self.labelled_objects && part_of_plan {
1215 &mut self.all
1216 } else {
1217 return;
1218 };
1219 if self.reached_last != Some([start[0], start[1]]) {
1222 reach.point(start[0], start[1]);
1223 }
1224 reach.point(end[0], end[1]);
1225 self.reached_last = Some([end[0], end[1]]);
1226 if let Some(arc) = arc {
1227 reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
1228 }
1229 }
1230
1231 fn place(&mut self, axis: usize, value: f64, relative: bool) {
1235 let landed = if relative {
1236 self.at[axis] + value
1237 } else {
1238 value
1239 };
1240 if landed.abs() <= AXIS_LIMIT {
1241 self.at[axis] = landed;
1242 }
1243 }
1244
1245 fn home(&mut self, words: &[Word]) {
1247 let named: Vec<usize> = ['X', 'Y', 'Z']
1248 .into_iter()
1249 .enumerate()
1250 .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
1251 .map(|(axis, _)| axis)
1252 .collect();
1253 if named.is_empty() {
1254 self.at = [0.0; 3];
1255 } else {
1256 for axis in named {
1257 self.at[axis] = 0.0;
1258 }
1259 }
1260 }
1261
1262 fn declare(&mut self, words: &[Word]) {
1265 if words.is_empty() {
1266 self.at = [0.0; 3];
1267 self.e = 0.0;
1268 return;
1269 }
1270 for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
1271 if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
1272 self.at[axis] = value;
1273 }
1274 }
1275 if let Some(value) = number(words, 'E') {
1276 self.e = value;
1277 }
1278 }
1279
1280 fn estimate(&mut self, words: &[Word]) {
1282 if number(words, 'P').is_none() {
1283 return;
1284 }
1285 if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
1286 self.time_left.push(Mark {
1287 at: self.read,
1288 value: whole(minutes),
1289 });
1290 }
1291 }
1292
1293 fn flow_factor(&mut self, words: &[Word]) {
1295 if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
1296 mark_setting(&mut self.flow, self.read, percent / 100.0);
1297 }
1298 }
1299
1300 fn fan_speed(&mut self, words: &[Word], command: Fan) {
1302 if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1303 return;
1304 }
1305 let speed = match command {
1306 Fan::Off => 0.0,
1307 Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1308 };
1309 let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1310 mark_setting(&mut self.fan, self.read, percent);
1311 }
1312
1313 fn object(&mut self, raw: &[u8], words: &[Word]) {
1315 if raw
1318 .strip_prefix(b"M486")
1319 .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1320 {
1321 self.labelled_objects = true;
1322 return;
1323 }
1324 let Some(number) = number(words, 'S')
1327 .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1328 else {
1329 return;
1330 };
1331 self.labelled_objects = true;
1332 if number < 0.0 {
1333 self.current_object = None;
1334 self.reached_last = None;
1335 return;
1336 }
1337 let id = whole(number);
1338 let place = if let Some(place) = self.object_numbers.get(&id) {
1339 *place
1340 } else if self.objects.len() >= OBJECT_LIMIT {
1341 self.current_object = None;
1342 self.reached_last = None;
1343 return;
1344 } else {
1345 self.objects.push(ObjectDraft::default());
1346 self.object_numbers.insert(id, self.objects.len() - 1);
1347 self.objects.len() - 1
1348 };
1349 self.current_object = Some(place);
1350 self.reached_last = None;
1351 self.blocks.push((self.read, place));
1352 }
1353}
1354
1355fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
1359 marks.push(Mark { at, value });
1360}
1361
1362fn whole(value: f64) -> i64 {
1365 format!("{:.0}", value.round()).parse().unwrap_or_default()
1366}
1367
1368fn tenth(value: f64) -> f64 {
1372 (value * 10.0).round() / 10.0
1373}
1374
1375fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
1377 *bounds = Some(match *bounds {
1378 None => [x, y, x, y],
1379 Some([least_x, least_y, most_x, most_y]) => {
1380 [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
1381 }
1382 });
1383}
1384
1385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1387enum Turn {
1388 Clockwise,
1390 CounterClockwise,
1392}
1393
1394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1397enum Fan {
1398 Set,
1400 Off,
1402}
1403
1404fn arc_extremes(
1413 words: &Move,
1414 turn: Turn,
1415 start: [f64; 3],
1416 end: [f64; 3],
1417) -> impl Iterator<Item = [f64; 2]> {
1418 let reach = arc_of(words, turn, start, end).map(|arc| {
1419 let ArcGeometry {
1420 centre,
1421 radius,
1422 base,
1423 sweep,
1424 ..
1425 } = arc;
1426 let tau = core::f64::consts::TAU;
1427 (0..4).filter_map(move |quarter| {
1428 let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
1429 ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
1430 [
1431 centre[0] + radius * angle.cos(),
1432 centre[1] + radius * angle.sin(),
1433 ]
1434 })
1435 })
1436 });
1437 reach.into_iter().flatten()
1438}
1439
1440#[derive(Debug, Clone, Copy)]
1442struct ArcGeometry {
1443 centre: [f64; 2],
1445 radius: f64,
1447 base: f64,
1450 sweep: f64,
1453 turn: Turn,
1455}
1456
1457fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
1461 let centre = words.r.map_or_else(
1462 || {
1463 Some([
1464 start[0] + words.i.unwrap_or(0.0),
1465 start[1] + words.j.unwrap_or(0.0),
1466 ])
1467 },
1468 |radius| centre_of_radius(radius, turn, start, end),
1469 )?;
1470 let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
1471 let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
1472 let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
1473 let tau = core::f64::consts::TAU;
1474 let (base, sweep) = match turn {
1477 Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
1478 Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
1479 };
1480 let sweep = if sweep < 1e-9 { tau } else { sweep };
1481 Some(ArcGeometry {
1482 centre,
1483 radius,
1484 base,
1485 sweep,
1486 turn,
1487 })
1488}
1489
1490fn collect_segments(
1493 collected: &mut Vec<ToolpathSegment>,
1494 kind: ExtrusionKind,
1495 start: [f64; 3],
1496 end: [f64; 3],
1497 arc: Option<ArcGeometry>,
1498) {
1499 #[expect(
1500 clippy::cast_possible_truncation,
1501 reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
1502 )]
1503 let at = |x: f64, y: f64| [x as f32, y as f32];
1504 let Some(arc) = arc else {
1505 collected.push(ToolpathSegment {
1506 from_mm: at(start[0], start[1]),
1507 to_mm: at(end[0], end[1]),
1508 kind,
1509 });
1510 return;
1511 };
1512 let length = arc.sweep * arc.radius;
1513 let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
1514 let (from, step) = match arc.turn {
1515 Turn::CounterClockwise => (arc.base, arc.sweep / chords),
1516 Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
1517 };
1518 let mut previous = at(start[0], start[1]);
1519 let mut k = 1.0;
1520 while k < chords {
1521 let angle = from + step * k;
1522 let next = at(
1523 arc.centre[0] + arc.radius * angle.cos(),
1524 arc.centre[1] + arc.radius * angle.sin(),
1525 );
1526 collected.push(ToolpathSegment {
1527 from_mm: previous,
1528 to_mm: next,
1529 kind,
1530 });
1531 previous = next;
1532 k += 1.0;
1533 }
1534 collected.push(ToolpathSegment {
1535 from_mm: previous,
1536 to_mm: at(end[0], end[1]),
1537 kind,
1538 });
1539}
1540
1541fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
1546 let chord = [end[0] - start[0], end[1] - start[1]];
1547 let length = chord[0].hypot(chord[1]);
1548 if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
1549 return None;
1550 }
1551 let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
1552 let left = match turn {
1553 Turn::Clockwise => -1.0,
1554 Turn::CounterClockwise => 1.0,
1555 };
1556 let side = left * radius.signum() * rise / length;
1557 Some([
1558 start[0] + chord[0] / 2.0 - chord[1] * side,
1559 start[1] + chord[1] / 2.0 + chord[0] * side,
1560 ])
1561}
1562
1563fn words(command: &[u8]) -> Words {
1569 let mut found = Words {
1570 held: [Word {
1571 letter: 0,
1572 value: f64::NAN,
1573 }; WORD_COUNT],
1574 len: 0,
1575 first_code: None,
1576 second_code: None,
1577 numbered: false,
1578 };
1579 let length = command.len();
1580 let mut at = 0;
1581 while at < length {
1582 let letter = command[at];
1583 if letter == b';' || letter == b'*' {
1584 break;
1585 }
1586 at += 1;
1587 let upper = match letter {
1588 b'a'..=b'z' => letter - (b'a' - b'A'),
1589 b'A'..=b'Z' => letter,
1590 _ => continue,
1591 };
1592 let start = at;
1593 let (value, next) = number_at(command, at);
1594 at = next;
1595 let text = &command[start..at];
1596 if found.len == 0 {
1599 found.first_code = whole_number(text);
1600 found.numbered = upper == b'N';
1601 } else if found.len == 1 {
1602 found.second_code = whole_number(text);
1603 }
1604 if found.len < WORD_COUNT {
1605 found.held[found.len] = Word {
1606 letter: upper,
1607 value,
1608 };
1609 found.len += 1;
1610 }
1611 }
1612 found
1613}
1614
1615fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
1624 let start = at;
1625 while at < line.len()
1626 && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
1627 {
1628 at += 1;
1629 }
1630 (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
1631}
1632
1633#[derive(Debug, Clone, Copy, Default)]
1637struct Move {
1638 x: Option<f64>,
1640 y: Option<f64>,
1642 z: Option<f64>,
1644 e: Option<f64>,
1646 i: Option<f64>,
1648 j: Option<f64>,
1650 r: Option<f64>,
1652}
1653
1654impl Move {
1655 fn of(words: &[Word]) -> Self {
1657 Self {
1658 x: number(words, 'X'),
1659 y: number(words, 'Y'),
1660 z: number(words, 'Z'),
1661 e: number(words, 'E'),
1662 i: number(words, 'I'),
1663 j: number(words, 'J'),
1664 r: number(words, 'R'),
1665 }
1666 }
1667}
1668
1669fn move_of(line: &[u8]) -> Move {
1674 let mut found = Move::default();
1675 let length = line.len();
1676 let mut at = 0;
1677 while at < length {
1678 let letter = line[at];
1679 at += 1;
1680 let slot = match letter {
1681 b';' | b'*' => break,
1682 b'X' | b'x' => &mut found.x,
1683 b'Y' | b'y' => &mut found.y,
1684 b'Z' | b'z' => &mut found.z,
1685 b'E' | b'e' => &mut found.e,
1686 b'I' | b'i' => &mut found.i,
1687 b'J' | b'j' => &mut found.j,
1688 b'R' | b'r' => &mut found.r,
1689 b'A'..=b'Z' | b'a'..=b'z' => {
1690 while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
1691 at += 1;
1692 }
1693 continue;
1694 }
1695 _ => continue,
1696 };
1697 let (value, next) = number_at(line, at);
1698 at = next;
1699 if slot.is_none() {
1700 *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1701 }
1702 }
1703 found
1704}
1705
1706#[derive(Debug, Clone, Copy)]
1709struct Word {
1710 letter: u8,
1712 value: f64,
1714}
1715
1716struct Words {
1718 held: [Word; WORD_COUNT],
1720 len: usize,
1722 first_code: Option<u32>,
1724 second_code: Option<u32>,
1726 numbered: bool,
1728}
1729
1730impl Words {
1731 fn as_slice(&self) -> &[Word] {
1733 &self.held[..self.len]
1734 }
1735}
1736
1737fn whole_number(text: &[u8]) -> Option<u32> {
1739 let mut value: u32 = 0;
1740 let mut at = 0;
1741 while at < text.len() {
1742 let byte = text[at];
1743 if !byte.is_ascii_digit() {
1744 return None;
1745 }
1746 value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
1747 at += 1;
1748 }
1749 (!text.is_empty()).then_some(value)
1750}
1751
1752fn decimal(text: &[u8]) -> Option<f64> {
1754 core::str::from_utf8(text).ok()?.parse::<f64>().ok()
1755}
1756
1757fn number(words: &[Word], letter: char) -> Option<f64> {
1760 let mut at = 0;
1761 while at < words.len() {
1762 let Word {
1763 letter: word,
1764 value,
1765 } = words[at];
1766 if char::from(word) == letter {
1767 return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1768 }
1769 at += 1;
1770 }
1771 None
1772}
1773
1774#[must_use]
1777pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
1778 let mut builder = IndexBuilder::new();
1779 for piece in pieces {
1780 let _ = builder.take(piece);
1781 }
1782 builder.finish()
1783}
1784
1785#[derive(Debug, Default)]
1787enum Slot {
1788 #[default]
1790 Empty,
1791 Building(Vec<Waker>),
1793 Ready(Arc<GcodeIndex>),
1795}
1796
1797#[derive(Debug, Default)]
1799pub struct GcodeIndexes {
1800 slots: Mutex<BTreeMap<PrintId, Slot>>,
1802 looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
1808}
1809
1810#[derive(Debug)]
1812pub enum Claimed<'a> {
1813 Ready(Arc<GcodeIndex>),
1815 Build(BuildClaim<'a>),
1817}
1818
1819#[derive(Debug)]
1822pub struct BuildClaim<'a> {
1823 indexes: &'a GcodeIndexes,
1825 print_id: PrintId,
1827 done: bool,
1829}
1830
1831impl BuildClaim<'_> {
1832 #[must_use]
1834 pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
1835 let index = Arc::new(index);
1836 self.settle(Slot::Ready(Arc::clone(&index)));
1837 self.done = true;
1838 index
1839 }
1840
1841 fn settle(&self, next: Slot) {
1843 let waiting = {
1844 let mut slots = self.indexes.held();
1845 let slot = slots.entry(self.print_id).or_default();
1846 match core::mem::replace(slot, next) {
1847 Slot::Building(waiting) => waiting,
1848 Slot::Empty | Slot::Ready(_) => Vec::new(),
1849 }
1850 };
1851 for waker in waiting {
1852 waker.wake();
1853 }
1854 }
1855}
1856
1857impl Drop for BuildClaim<'_> {
1858 fn drop(&mut self) {
1859 if !self.done {
1860 self.settle(Slot::Empty);
1861 }
1862 }
1863}
1864
1865impl GcodeIndexes {
1866 fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
1868 self.slots.lock().unwrap_or_else(PoisonError::into_inner)
1869 }
1870
1871 pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
1874 Claim {
1875 indexes: self,
1876 print_id,
1877 }
1878 }
1879
1880 #[must_use]
1882 pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
1883 match self.held().get(&print_id) {
1884 Some(Slot::Ready(index)) => Some(Arc::clone(index)),
1885 _ => None,
1886 }
1887 }
1888}
1889
1890#[derive(Debug)]
1892pub struct Claim<'a> {
1893 indexes: &'a GcodeIndexes,
1895 print_id: PrintId,
1897}
1898
1899impl<'a> Future for Claim<'a> {
1900 type Output = Claimed<'a>;
1901
1902 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
1903 let mut slots = self.indexes.held();
1904 let slot = slots.entry(self.print_id).or_default();
1905 match slot {
1906 Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
1907 Slot::Building(waiting) => {
1908 if !waiting.iter().any(|held| held.will_wake(context.waker())) {
1909 waiting.push(context.waker().clone());
1910 }
1911 Poll::Pending
1912 }
1913 Slot::Empty => {
1914 *slot = Slot::Building(Vec::new());
1915 Poll::Ready(Claimed::Build(BuildClaim {
1916 indexes: self.indexes,
1917 print_id: self.print_id,
1918 done: false,
1919 }))
1920 }
1921 }
1922 }
1923}
1924
1925const HELD_INDEXES: usize = 16;
1929
1930impl GcodeIndexes {
1931 pub(crate) fn note_look(
1937 &self,
1938 print_id: PrintId,
1939 captured: Timestamp,
1940 position: i64,
1941 now: Timestamp,
1942 ) {
1943 let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1944 let frames = looked.entry(print_id).or_default();
1945 frames.push((captured, position));
1946 frames.sort_by_key(|(captured, _)| *captured);
1947 if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
1948 let aged = frames.partition_point(|(captured, _)| *captured <= until);
1949 frames.drain(..aged.saturating_sub(1));
1950 }
1951 while looked.len() > HELD_INDEXES {
1952 let Some(oldest) = looked.keys().next().copied() else {
1953 break;
1954 };
1955 let _ = looked.remove(&oldest);
1956 }
1957 }
1958
1959 fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
1962 let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1963 looked
1964 .get(&print_id)?
1965 .iter()
1966 .rev()
1967 .find(|(captured, _)| *captured <= until)
1968 .copied()
1969 }
1970
1971 fn trim(&self, keep: PrintId) {
1973 let mut slots = self.held();
1974 let ready: Vec<PrintId> = slots
1975 .iter()
1976 .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
1977 .map(|(print_id, _)| *print_id)
1978 .collect();
1979 let over = slots.len().saturating_sub(HELD_INDEXES);
1980 for print_id in ready.into_iter().take(over) {
1981 slots.remove(&print_id);
1982 }
1983 }
1984}
1985
1986impl crate::supervisor::Supervisor {
1987 pub(crate) async fn slicer_plan(
1999 &self,
2000 print: &crate::records::PrintRecord,
2001 job: Option<&printobserver_printer_api::JobSnapshot>,
2002 interventions: &[crate::records::Intervention],
2003 ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
2004 let Some((position, file)) = job
2005 .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
2006 .filter(|(_, file)| {
2007 print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
2008 })
2009 else {
2010 return Ok(None);
2011 };
2012 let Some(index) = self.index_of(print.id, file).await else {
2013 return Ok(None);
2014 };
2015 let (flow, fan) = self
2016 .changes_since(print.id, &index, position, interventions)
2017 .await?;
2018 let mut plan = index.plan_with(position, flow, fan);
2019 plan.rise = self.rise_of(print.id, &index, position).await?;
2020 if plan.rise.is_none() {
2021 plan.unknown.push(PlanFact::Rise);
2022 plan.unknown.sort_unstable();
2023 }
2024 Ok(Some(plan))
2025 }
2026
2027 async fn rise_of(
2032 &self,
2033 print_id: PrintId,
2034 index: &GcodeIndex,
2035 position: i64,
2036 ) -> Result<Option<Rise>, crate::error::CoreError> {
2037 use printobserver_types::EventPayload as _;
2038
2039 use crate::kinds::PeriodicObservationPayload;
2040
2041 let now = self.clock().now();
2042 let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
2043 return Ok(None);
2044 };
2045 let events = self
2046 .stores()
2047 .events
2048 .history(crate::store::HistoryQuery {
2049 print_id,
2050 kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
2051 .into_iter()
2052 .collect(),
2053 since: None,
2054 until: Some(until),
2055 limit: Some(1),
2056 })
2057 .await?;
2058 let observed = events.first().and_then(|event| {
2059 let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
2060 let earlier = observed.job?.file_position_bytes?;
2061 Some((
2062 observed.frame_captured_at.unwrap_or(event.received_at),
2063 earlier,
2064 ))
2065 });
2066 let looked = self.gcode_indexes().newest_look_until(print_id, until);
2067 let newest = match (observed, looked) {
2068 (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
2069 looked
2070 } else {
2071 observed
2072 }),
2073 (observed, looked) => observed.or(looked),
2074 };
2075 Ok(newest.and_then(|(since, earlier)| {
2076 Some(Rise {
2077 since,
2078 mm: index.height_and_rise_since(earlier, position)?,
2079 })
2080 }))
2081 }
2082
2083 pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2088 let print = self.stores().prints.print(print_id).await.ok()??;
2095 if print.ended_at.is_some() {
2096 return None;
2097 }
2098 self.index_of(print.id, print.file_name.as_deref()?).await
2099 }
2100
2101 pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
2103 if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
2104 let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
2105 }
2106 }
2107
2108 pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
2115 let Some(directory) = self.config().gcode_spool_dir.clone() else {
2116 return Ok(());
2117 };
2118 let open: Vec<String> = self
2119 .stores()
2120 .prints
2121 .open_prints()
2122 .await?
2123 .iter()
2124 .map(|print| print.id.to_string())
2125 .collect();
2126 let Ok(entries) = std::fs::read_dir(&directory) else {
2134 return Ok(());
2135 };
2136 for entry in entries.flatten() {
2137 let name = entry.file_name();
2138 let Some(print) = name
2140 .to_str()
2141 .and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
2142 .filter(|print| print.parse::<PrintId>().is_ok())
2143 else {
2144 continue;
2145 };
2146 if !open.iter().any(|id| id == print) {
2147 let _ = std::fs::remove_file(entry.path());
2148 }
2149 }
2150 Ok(())
2151 }
2152
2153 async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
2155 let file_name = printobserver_types::FileName::new(file).ok()?;
2157 let claim = match self.gcode_indexes().claim(print_id).await {
2158 Claimed::Ready(index) => return Some(index),
2159 Claimed::Build(claim) => claim,
2160 };
2161 let mut builder = self
2164 .config()
2165 .gcode_spool_dir
2166 .as_deref()
2167 .and_then(|directory| {
2168 IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
2169 })
2170 .unwrap_or_default();
2171 self.read_gcode(file_name.clone(), &mut builder)
2172 .await
2173 .ok()?;
2174 let index = claim.finish(builder.finish());
2175 self.gcode_indexes().trim(print_id);
2176 if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
2177 file_name,
2178 bytes: index.bytes(),
2179 layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
2180 }) {
2181 let _ = self.append_system_event(print_id, body).await;
2184 }
2185 Some(index)
2186 }
2187
2188 async fn changes_since(
2197 &self,
2198 print_id: PrintId,
2199 index: &GcodeIndex,
2200 position: i64,
2201 interventions: &[crate::records::Intervention],
2202 ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
2203 use printobserver_types::EventPayload as _;
2204
2205 use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
2206 use crate::records::PrintAction;
2207
2208 let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
2209 .iter()
2210 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
2211 .collect();
2212 let events = self
2213 .stores()
2214 .events
2215 .history(crate::store::HistoryQuery {
2216 print_id,
2217 kinds,
2218 since: None,
2219 until: None,
2220 limit: Some(crate::store::MAX_HISTORY_LIMIT),
2221 })
2222 .await?;
2223 let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
2224 .iter()
2225 .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
2226 .filter_map(Result::ok)
2227 .map(|payload| (payload.action_id, payload.action))
2228 .collect();
2229 let mut flow = None;
2230 let mut fan = None;
2231 for executed in events
2233 .iter()
2234 .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
2235 .filter_map(Result::ok)
2236 {
2237 let standing = executed
2238 .intervention_id
2239 .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
2240 let made = executed
2243 .file_position_bytes
2244 .and_then(|made| u64::try_from(made).ok())
2245 .unwrap_or(0);
2246 let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
2247 match requested.get(&executed.action_id) {
2248 Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
2249 flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
2250 }
2251 Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
2252 fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
2253 }
2254 _ => {}
2255 }
2256 }
2257 Ok((flow.flatten(), fan.flatten()))
2258 }
2259}
2260
2261#[cfg(test)]
2262mod tests {
2263 use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
2264 use crate::toolpath::ExtrusionKind;
2265
2266 #[test]
2270 fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
2271 for name in WALLS {
2272 assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
2273 }
2274 for name in SUPPORTS {
2275 assert_eq!(
2276 ExtrusionKind::of_type(name),
2277 ExtrusionKind::Support,
2278 "{name}"
2279 );
2280 }
2281 for name in OVER_AIR {
2282 assert!(
2283 matches!(
2284 ExtrusionKind::of_type(name),
2285 ExtrusionKind::Bridge | ExtrusionKind::Overhang
2286 ),
2287 "{name}"
2288 );
2289 }
2290 }
2291 use printobserver_types::{PrintId, Timestamp};
2292
2293 fn after(start: Timestamp, seconds: i64) -> Timestamp {
2295 start.plus_seconds(seconds).expect("an instant")
2296 }
2297
2298 fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
2300 indexes
2301 .looked
2302 .lock()
2303 .expect("the looks are held")
2304 .get(&print_id)
2305 .cloned()
2306 .unwrap_or_default()
2307 }
2308
2309 #[test]
2312 fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
2313 let indexes = GcodeIndexes::default();
2314 let print = PrintId::new();
2315 let start = Timestamp::now();
2316 indexes.note_look(print, start, 10, start);
2317 indexes.note_look(print, after(start, 60), 20, after(start, 60));
2318 let now = after(start, 60 + RISE_WINDOW_S + 30);
2319 indexes.note_look(print, now, 30, now);
2320
2321 assert_eq!(
2322 held(&indexes, print),
2323 vec![(after(start, 60), 20), (now, 30)]
2324 );
2325 assert_eq!(
2326 indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
2327 Some((after(start, 60), 20))
2328 );
2329 assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
2330 }
2331
2332 #[test]
2335 fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
2336 let indexes = GcodeIndexes::default();
2337 let now = Timestamp::now();
2338 let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
2339 prints.sort_unstable();
2340 for print in &prints {
2341 indexes.note_look(*print, now, 1, now);
2342 }
2343
2344 assert!(held(&indexes, prints[0]).is_empty());
2345 for print in &prints[1..] {
2346 assert_eq!(held(&indexes, *print), vec![(now, 1)]);
2347 }
2348 }
2349}