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,
655 pub mm: [f64; 2],
661}
662
663#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
666#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
667#[schemars(crate = "printobserver_types::schemars")]
668pub enum PlanMismatch {
669 FanOffOverBridges,
672 FlowLowOverWalls,
674}
675
676#[derive(
678 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
679)]
680#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
681#[schemars(crate = "printobserver_types::schemars")]
682pub enum PlanFact {
683 Layer,
685 FinalZ,
687 Types,
689 MinutesLeft,
691 FlowFactor,
693 FanPercent,
695 Objects,
697 Rise,
701}
702
703#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
710#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
711#[schemars(crate = "printobserver_types::schemars")]
712pub struct SlicerPlan {
713 #[serde(default, skip_serializing_if = "Option::is_none")]
716 pub layer: Option<usize>,
717 #[serde(default, skip_serializing_if = "Option::is_none")]
719 pub z_mm: Option<f64>,
720 #[serde(default, skip_serializing_if = "Option::is_none")]
722 pub final_z_mm: Option<f64>,
723 #[serde(default, skip_serializing_if = "Vec::is_empty")]
726 pub types: Vec<String>,
727 #[serde(default, skip_serializing_if = "Option::is_none")]
729 pub minutes_left: Option<i64>,
730 #[serde(default, skip_serializing_if = "Option::is_none")]
732 pub flow_factor: Option<SetValue>,
733 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub fan_percent: Option<SetValue>,
736 #[serde(default, skip_serializing_if = "Option::is_none")]
738 pub object_count: Option<usize>,
739 #[serde(default, skip_serializing_if = "Vec::is_empty")]
743 pub objects: Vec<BedArea>,
744 #[serde(default, skip_serializing_if = "Option::is_none")]
747 pub rise: Option<Rise>,
748 #[serde(default, skip_serializing_if = "Vec::is_empty")]
750 pub at_odds: Vec<PlanMismatch>,
751 #[serde(default, skip_serializing_if = "Vec::is_empty")]
754 pub unknown: Vec<PlanFact>,
755}
756
757impl Sample for SlicerPlan {
758 fn sample_full() -> Self {
759 Self {
760 layer: Some(12),
761 z_mm: Some(2.4),
762 types: vec![
763 "Perimeter".to_owned(),
764 "External perimeter".to_owned(),
765 "Support material".to_owned(),
766 ],
767 final_z_mm: Some(30.0),
768 minutes_left: Some(42),
769 flow_factor: Some(SetValue {
770 file: Some(1.0),
771 changed: Some(0.95),
772 }),
773 fan_percent: Some(SetValue {
774 file: Some(100.0),
775 changed: None,
776 }),
777 object_count: Some(1),
778 objects: vec![[100, 99, 150, 117]],
779 rise: Some(Rise {
780 since: Timestamp::sample_full(),
781 mm: [7.2, 4.8],
782 }),
783 at_odds: vec![PlanMismatch::FlowLowOverWalls],
784 unknown: vec![PlanFact::Objects],
785 }
786 }
787
788 fn sample_minimal() -> Self {
789 Self {
790 layer: None,
791 z_mm: None,
792 final_z_mm: None,
793 types: Vec::new(),
794 minutes_left: None,
795 flow_factor: None,
796 fan_percent: None,
797 object_count: None,
798 objects: Vec::new(),
799 rise: None,
800 at_odds: Vec::new(),
801 unknown: Vec::new(),
802 }
803 }
804}
805
806#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
808enum Positioning {
809 #[default]
811 Absolute,
812 Relative,
814}
815
816#[derive(Debug, Default)]
819pub struct IndexBuilder {
820 line: Vec<u8>,
822 overlong: bool,
824 read: u64,
826 lines: u64,
828 layers: Vec<Layer>,
830 type_names: Vec<String>,
832 labelled_types: bool,
834 current_type: Option<usize>,
836 time_left: Vec<Mark<i64>>,
838 flow: Vec<Mark<f64>>,
840 fan: Vec<Mark<f64>>,
842 objects: Vec<ObjectDraft>,
844 object_numbers: BTreeMap<i64, usize>,
846 current_object: Option<usize>,
849 labelled_objects: bool,
851 at: [f64; 3],
853 e: f64,
855 axes: Positioning,
857 extruder: Positioning,
859 line_began: u64,
861 all: Reach,
863 blocks: Vec<(u64, usize)>,
866 spool: Option<Spooling>,
868 collected: Option<Vec<ToolpathSegment>>,
870 reached_last: Option<[f64; 2]>,
872}
873
874#[derive(Debug)]
876struct Spooling {
877 path: std::path::PathBuf,
879 writer: std::io::BufWriter<std::fs::File>,
881 failed: bool,
883}
884
885impl GcodeSink for IndexBuilder {
886 fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
887 if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
897 use std::io::Write as _;
898 spool.failed = spool.writer.write_all(piece).is_err();
899 }
900 let mut start = 0;
901 let mut at = 0;
902 while at < piece.len() {
903 if piece[at] == b'\n' {
904 let head = &piece[start..at];
905 self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
906 if self.line.is_empty() && !self.overlong {
907 self.lines += 1;
909 if head.len() <= LINE_LIMIT {
910 self.read_line(head);
911 }
912 } else {
913 self.hold(head);
914 self.end_line();
915 }
916 self.line_began = self.read;
917 start = at + 1;
918 }
919 at += 1;
920 }
921 let rest = &piece[start..];
922 self.hold(rest);
923 self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
924 ControlFlow::Continue(())
925 }
926}
927
928impl IndexBuilder {
929 #[must_use]
931 pub fn new() -> Self {
932 Self::default()
933 }
934
935 pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
943 let file = std::fs::File::create(&path)?;
944 Ok(Self {
945 spool: Some(Spooling {
946 path,
947 writer: std::io::BufWriter::with_capacity(1 << 16, file),
948 failed: false,
949 }),
950 ..Self::default()
951 })
952 }
953
954 fn reading_layer(type_names: Vec<String>, head: Head) -> Self {
957 Self {
958 type_names,
959 labelled_types: true,
960 current_type: head.current_type,
961 at: head.at,
962 e: head.e,
963 axes: head.axes,
964 extruder: head.extruder,
965 collected: Some(Vec::new()),
966 ..Self::default()
967 }
968 }
969
970 #[must_use]
973 pub fn finish(mut self) -> GcodeIndex {
974 if !self.line.is_empty() || self.overlong {
975 self.end_line();
976 }
977 let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
978 let mut objects = Vec::new();
979 let mut outlines = Vec::new();
980 let mut outline_of = vec![None; drafts.len()];
981 for place in self.object_numbers.into_values() {
982 let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
983 continue;
984 };
985 let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
986 continue;
987 };
988 objects.push([
989 whole(tenth(least_x).floor()),
990 whole(tenth(least_y).floor()),
991 whole(tenth(most_x).ceil()),
992 whole(tenth(most_y).ceil()),
993 ]);
994 outline_of[place] = Some(outlines.len());
995 outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
996 hull_mm: Vec::new(),
997 }));
998 }
999 if !self.labelled_objects {
1000 outlines.extend(self.all.outline());
1001 }
1002 let blocks = self
1003 .blocks
1004 .into_iter()
1005 .map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
1006 .collect();
1007 let spool = self.spool.and_then(|mut spool| {
1008 use std::io::Write as _;
1009 if spool.failed || spool.writer.flush().is_err() {
1010 drop(spool.writer);
1011 let _ = std::fs::remove_file(&spool.path);
1012 return None;
1013 }
1014 Some(spool.path)
1015 });
1016 GcodeIndex {
1017 bytes: self.read,
1018 lines: self.lines,
1019 layers: self.layers,
1020 type_names: self.type_names,
1021 labelled_types: self.labelled_types,
1022 time_left: self.time_left,
1023 flow: self.flow,
1024 fan: self.fan,
1025 objects,
1026 labelled_objects: self.labelled_objects,
1027 outlines,
1028 blocks,
1029 spool,
1030 }
1031 }
1032
1033 fn hold(&mut self, bytes: &[u8]) {
1035 if self.overlong {
1036 return;
1037 }
1038 if self.line.len() + bytes.len() > LINE_LIMIT {
1039 self.overlong = true;
1040 self.line.clear();
1041 return;
1042 }
1043 self.line.extend_from_slice(bytes);
1044 }
1045
1046 fn end_line(&mut self) {
1048 self.lines += 1;
1049 let line = core::mem::take(&mut self.line);
1050 if !self.overlong {
1051 self.read_line(&line);
1052 }
1053 self.overlong = false;
1054 self.line = line;
1055 self.line.clear();
1056 }
1057
1058 fn read_line(&mut self, raw: &[u8]) {
1060 let raw = raw.trim_ascii();
1061 if let Some(comment) = raw.strip_prefix(b";") {
1062 if let Ok(comment) = core::str::from_utf8(comment) {
1063 self.comment(comment.trim_end());
1064 }
1065 return;
1066 }
1067 if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
1070 self.motion(u32::from(code - b'0'), &move_of(rest));
1071 return;
1072 }
1073 let held = words(raw);
1074 let mut words = held.as_slice();
1075 if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
1077 words = rest;
1078 }
1079 let Some(first) = words.first() else {
1080 return;
1081 };
1082 let code = if held.numbered {
1083 held.second_code
1084 } else {
1085 held.first_code
1086 };
1087 match (char::from(first.letter), code) {
1088 ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
1089 ('G', Some(28)) => self.home(&words[1..]),
1090 ('G', Some(90)) => self.axes = Positioning::Absolute,
1091 ('G', Some(91)) => self.axes = Positioning::Relative,
1092 ('G', Some(92)) => self.declare(&words[1..]),
1093 ('M', Some(82)) => self.extruder = Positioning::Absolute,
1094 ('M', Some(83)) => self.extruder = Positioning::Relative,
1095 ('M', Some(73)) => self.estimate(&words[1..]),
1096 ('M', Some(221)) => self.flow_factor(&words[1..]),
1097 ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
1098 ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
1099 ('M', Some(486)) => self.object(raw, &words[1..]),
1100 _ => {}
1101 }
1102 }
1103
1104 fn comment(&mut self, comment: &str) {
1106 if comment == "LAYER_CHANGE" {
1107 self.layers.push(Layer {
1108 begins: self.line_began,
1109 head: Head {
1110 at: self.at,
1111 e: self.e,
1112 axes: self.axes,
1113 extruder: self.extruder,
1114 current_type: self.current_type,
1115 },
1116 at: self.read,
1117 z_mm: None,
1118 types: 0,
1119 });
1120 } else if let Some(z) = comment.strip_prefix("Z:") {
1121 if let Some(layer) = self.layers.last_mut()
1122 && layer.z_mm.is_none()
1123 {
1124 layer.z_mm = z
1127 .trim()
1128 .parse::<f64>()
1129 .ok()
1130 .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
1131 }
1132 } else if let Some(name) = comment.strip_prefix("TYPE:") {
1133 let name = name.trim();
1134 self.labelled_types = true;
1135 self.current_type = if name == NOT_THE_PART {
1136 None
1137 } else {
1138 self.intern(name)
1139 };
1140 }
1141 }
1142
1143 fn intern(&mut self, name: &str) -> Option<usize> {
1145 if let Some(bit) = self.type_names.iter().position(|held| held == name) {
1146 return Some(bit);
1147 }
1148 if self.type_names.len() >= TYPE_LIMIT {
1149 return None;
1150 }
1151 self.type_names.push(name.to_owned());
1152 Some(self.type_names.len() - 1)
1153 }
1154
1155 fn motion(&mut self, code: u32, words: &Move) {
1157 let start = self.at;
1160 let relative = self.axes == Positioning::Relative;
1161 if let Some(x) = words.x {
1162 self.place(0, x, relative);
1163 }
1164 if let Some(y) = words.y {
1165 self.place(1, y, relative);
1166 }
1167 if let Some(z) = words.z {
1168 self.place(2, z, relative);
1169 }
1170 let mut fed = 0.0;
1171 if let Some(value) = words.e {
1172 if relative || self.extruder == Positioning::Relative {
1173 self.e += value;
1174 fed = value;
1175 } else {
1176 fed = value - self.e;
1177 self.e = value;
1178 }
1179 }
1180 let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
1181 if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
1182 return;
1183 }
1184 if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
1185 layer.types |= 1 << bit;
1186 }
1187 let end = self.at;
1188 let turn = match code {
1189 2 => Some(Turn::Clockwise),
1190 3 => Some(Turn::CounterClockwise),
1191 _ => None,
1192 };
1193 let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
1194 if let Some(collected) = self.collected.as_mut() {
1195 let kind = self
1196 .current_type
1197 .and_then(|bit| self.type_names.get(bit))
1198 .map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
1199 collect_segments(collected, kind, start, end, arc);
1200 return;
1201 }
1202 let part_of_plan = !(self.labelled_types && self.current_type.is_none());
1203 let reach = if let Some(object) = self.current_object {
1204 let draft = &mut self.objects[object];
1205 grow(&mut draft.bounds, start[0], start[1]);
1206 grow(&mut draft.bounds, end[0], end[1]);
1207 if let Some(turn) = turn {
1208 for [x, y] in arc_extremes(words, turn, start, end) {
1209 grow(&mut draft.bounds, x, y);
1210 }
1211 }
1212 &mut draft.reach
1213 } else if !self.labelled_objects && part_of_plan {
1214 &mut self.all
1215 } else {
1216 return;
1217 };
1218 if self.reached_last != Some([start[0], start[1]]) {
1221 reach.point(start[0], start[1]);
1222 }
1223 reach.point(end[0], end[1]);
1224 self.reached_last = Some([end[0], end[1]]);
1225 if let Some(arc) = arc {
1226 reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
1227 }
1228 }
1229
1230 fn place(&mut self, axis: usize, value: f64, relative: bool) {
1234 let landed = if relative {
1235 self.at[axis] + value
1236 } else {
1237 value
1238 };
1239 if landed.abs() <= AXIS_LIMIT {
1240 self.at[axis] = landed;
1241 }
1242 }
1243
1244 fn home(&mut self, words: &[Word]) {
1246 let named: Vec<usize> = ['X', 'Y', 'Z']
1247 .into_iter()
1248 .enumerate()
1249 .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
1250 .map(|(axis, _)| axis)
1251 .collect();
1252 if named.is_empty() {
1253 self.at = [0.0; 3];
1254 } else {
1255 for axis in named {
1256 self.at[axis] = 0.0;
1257 }
1258 }
1259 }
1260
1261 fn declare(&mut self, words: &[Word]) {
1264 if words.is_empty() {
1265 self.at = [0.0; 3];
1266 self.e = 0.0;
1267 return;
1268 }
1269 for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
1270 if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
1271 self.at[axis] = value;
1272 }
1273 }
1274 if let Some(value) = number(words, 'E') {
1275 self.e = value;
1276 }
1277 }
1278
1279 fn estimate(&mut self, words: &[Word]) {
1281 if number(words, 'P').is_none() {
1282 return;
1283 }
1284 if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
1285 self.time_left.push(Mark {
1286 at: self.read,
1287 value: whole(minutes),
1288 });
1289 }
1290 }
1291
1292 fn flow_factor(&mut self, words: &[Word]) {
1294 if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
1295 mark_setting(&mut self.flow, self.read, percent / 100.0);
1296 }
1297 }
1298
1299 fn fan_speed(&mut self, words: &[Word], command: Fan) {
1301 if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1302 return;
1303 }
1304 let speed = match command {
1305 Fan::Off => 0.0,
1306 Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1307 };
1308 let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1309 mark_setting(&mut self.fan, self.read, percent);
1310 }
1311
1312 fn object(&mut self, raw: &[u8], words: &[Word]) {
1314 if raw
1317 .strip_prefix(b"M486")
1318 .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1319 {
1320 self.labelled_objects = true;
1321 return;
1322 }
1323 let Some(number) = number(words, 'S')
1326 .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1327 else {
1328 return;
1329 };
1330 self.labelled_objects = true;
1331 if number < 0.0 {
1332 self.current_object = None;
1333 self.reached_last = None;
1334 return;
1335 }
1336 let id = whole(number);
1337 let place = if let Some(place) = self.object_numbers.get(&id) {
1338 *place
1339 } else if self.objects.len() >= OBJECT_LIMIT {
1340 self.current_object = None;
1341 self.reached_last = None;
1342 return;
1343 } else {
1344 self.objects.push(ObjectDraft::default());
1345 self.object_numbers.insert(id, self.objects.len() - 1);
1346 self.objects.len() - 1
1347 };
1348 self.current_object = Some(place);
1349 self.reached_last = None;
1350 self.blocks.push((self.read, place));
1351 }
1352}
1353
1354fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
1358 marks.push(Mark { at, value });
1359}
1360
1361fn whole(value: f64) -> i64 {
1364 format!("{:.0}", value.round()).parse().unwrap_or_default()
1365}
1366
1367fn tenth(value: f64) -> f64 {
1371 (value * 10.0).round() / 10.0
1372}
1373
1374fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
1376 *bounds = Some(match *bounds {
1377 None => [x, y, x, y],
1378 Some([least_x, least_y, most_x, most_y]) => {
1379 [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
1380 }
1381 });
1382}
1383
1384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1386enum Turn {
1387 Clockwise,
1389 CounterClockwise,
1391}
1392
1393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1396enum Fan {
1397 Set,
1399 Off,
1401}
1402
1403fn arc_extremes(
1412 words: &Move,
1413 turn: Turn,
1414 start: [f64; 3],
1415 end: [f64; 3],
1416) -> impl Iterator<Item = [f64; 2]> {
1417 let reach = arc_of(words, turn, start, end).map(|arc| {
1418 let ArcGeometry {
1419 centre,
1420 radius,
1421 base,
1422 sweep,
1423 ..
1424 } = arc;
1425 let tau = core::f64::consts::TAU;
1426 (0..4).filter_map(move |quarter| {
1427 let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
1428 ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
1429 [
1430 centre[0] + radius * angle.cos(),
1431 centre[1] + radius * angle.sin(),
1432 ]
1433 })
1434 })
1435 });
1436 reach.into_iter().flatten()
1437}
1438
1439#[derive(Debug, Clone, Copy)]
1441struct ArcGeometry {
1442 centre: [f64; 2],
1444 radius: f64,
1446 base: f64,
1449 sweep: f64,
1452 turn: Turn,
1454}
1455
1456fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
1460 let centre = words.r.map_or_else(
1461 || {
1462 Some([
1463 start[0] + words.i.unwrap_or(0.0),
1464 start[1] + words.j.unwrap_or(0.0),
1465 ])
1466 },
1467 |radius| centre_of_radius(radius, turn, start, end),
1468 )?;
1469 let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
1470 let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
1471 let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
1472 let tau = core::f64::consts::TAU;
1473 let (base, sweep) = match turn {
1476 Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
1477 Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
1478 };
1479 let sweep = if sweep < 1e-9 { tau } else { sweep };
1480 Some(ArcGeometry {
1481 centre,
1482 radius,
1483 base,
1484 sweep,
1485 turn,
1486 })
1487}
1488
1489fn collect_segments(
1492 collected: &mut Vec<ToolpathSegment>,
1493 kind: ExtrusionKind,
1494 start: [f64; 3],
1495 end: [f64; 3],
1496 arc: Option<ArcGeometry>,
1497) {
1498 #[expect(
1499 clippy::cast_possible_truncation,
1500 reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
1501 )]
1502 let at = |x: f64, y: f64| [x as f32, y as f32];
1503 let Some(arc) = arc else {
1504 collected.push(ToolpathSegment {
1505 from_mm: at(start[0], start[1]),
1506 to_mm: at(end[0], end[1]),
1507 kind,
1508 });
1509 return;
1510 };
1511 let length = arc.sweep * arc.radius;
1512 let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
1513 let (from, step) = match arc.turn {
1514 Turn::CounterClockwise => (arc.base, arc.sweep / chords),
1515 Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
1516 };
1517 let mut previous = at(start[0], start[1]);
1518 let mut k = 1.0;
1519 while k < chords {
1520 let angle = from + step * k;
1521 let next = at(
1522 arc.centre[0] + arc.radius * angle.cos(),
1523 arc.centre[1] + arc.radius * angle.sin(),
1524 );
1525 collected.push(ToolpathSegment {
1526 from_mm: previous,
1527 to_mm: next,
1528 kind,
1529 });
1530 previous = next;
1531 k += 1.0;
1532 }
1533 collected.push(ToolpathSegment {
1534 from_mm: previous,
1535 to_mm: at(end[0], end[1]),
1536 kind,
1537 });
1538}
1539
1540fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
1545 let chord = [end[0] - start[0], end[1] - start[1]];
1546 let length = chord[0].hypot(chord[1]);
1547 if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
1548 return None;
1549 }
1550 let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
1551 let left = match turn {
1552 Turn::Clockwise => -1.0,
1553 Turn::CounterClockwise => 1.0,
1554 };
1555 let side = left * radius.signum() * rise / length;
1556 Some([
1557 start[0] + chord[0] / 2.0 - chord[1] * side,
1558 start[1] + chord[1] / 2.0 + chord[0] * side,
1559 ])
1560}
1561
1562fn words(command: &[u8]) -> Words {
1568 let mut found = Words {
1569 held: [Word {
1570 letter: 0,
1571 value: f64::NAN,
1572 }; WORD_COUNT],
1573 len: 0,
1574 first_code: None,
1575 second_code: None,
1576 numbered: false,
1577 };
1578 let length = command.len();
1579 let mut at = 0;
1580 while at < length {
1581 let letter = command[at];
1582 if letter == b';' || letter == b'*' {
1583 break;
1584 }
1585 at += 1;
1586 let upper = match letter {
1587 b'a'..=b'z' => letter - (b'a' - b'A'),
1588 b'A'..=b'Z' => letter,
1589 _ => continue,
1590 };
1591 let start = at;
1592 let (value, next) = number_at(command, at);
1593 at = next;
1594 let text = &command[start..at];
1595 if found.len == 0 {
1598 found.first_code = whole_number(text);
1599 found.numbered = upper == b'N';
1600 } else if found.len == 1 {
1601 found.second_code = whole_number(text);
1602 }
1603 if found.len < WORD_COUNT {
1604 found.held[found.len] = Word {
1605 letter: upper,
1606 value,
1607 };
1608 found.len += 1;
1609 }
1610 }
1611 found
1612}
1613
1614fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
1623 let start = at;
1624 while at < line.len()
1625 && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
1626 {
1627 at += 1;
1628 }
1629 (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
1630}
1631
1632#[derive(Debug, Clone, Copy, Default)]
1636struct Move {
1637 x: Option<f64>,
1639 y: Option<f64>,
1641 z: Option<f64>,
1643 e: Option<f64>,
1645 i: Option<f64>,
1647 j: Option<f64>,
1649 r: Option<f64>,
1651}
1652
1653impl Move {
1654 fn of(words: &[Word]) -> Self {
1656 Self {
1657 x: number(words, 'X'),
1658 y: number(words, 'Y'),
1659 z: number(words, 'Z'),
1660 e: number(words, 'E'),
1661 i: number(words, 'I'),
1662 j: number(words, 'J'),
1663 r: number(words, 'R'),
1664 }
1665 }
1666}
1667
1668fn move_of(line: &[u8]) -> Move {
1673 let mut found = Move::default();
1674 let length = line.len();
1675 let mut at = 0;
1676 while at < length {
1677 let letter = line[at];
1678 at += 1;
1679 let slot = match letter {
1680 b';' | b'*' => break,
1681 b'X' | b'x' => &mut found.x,
1682 b'Y' | b'y' => &mut found.y,
1683 b'Z' | b'z' => &mut found.z,
1684 b'E' | b'e' => &mut found.e,
1685 b'I' | b'i' => &mut found.i,
1686 b'J' | b'j' => &mut found.j,
1687 b'R' | b'r' => &mut found.r,
1688 b'A'..=b'Z' | b'a'..=b'z' => {
1689 while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
1690 at += 1;
1691 }
1692 continue;
1693 }
1694 _ => continue,
1695 };
1696 let (value, next) = number_at(line, at);
1697 at = next;
1698 if slot.is_none() {
1699 *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1700 }
1701 }
1702 found
1703}
1704
1705#[derive(Debug, Clone, Copy)]
1708struct Word {
1709 letter: u8,
1711 value: f64,
1713}
1714
1715struct Words {
1717 held: [Word; WORD_COUNT],
1719 len: usize,
1721 first_code: Option<u32>,
1723 second_code: Option<u32>,
1725 numbered: bool,
1727}
1728
1729impl Words {
1730 fn as_slice(&self) -> &[Word] {
1732 &self.held[..self.len]
1733 }
1734}
1735
1736fn whole_number(text: &[u8]) -> Option<u32> {
1738 let mut value: u32 = 0;
1739 let mut at = 0;
1740 while at < text.len() {
1741 let byte = text[at];
1742 if !byte.is_ascii_digit() {
1743 return None;
1744 }
1745 value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
1746 at += 1;
1747 }
1748 (!text.is_empty()).then_some(value)
1749}
1750
1751fn decimal(text: &[u8]) -> Option<f64> {
1753 core::str::from_utf8(text).ok()?.parse::<f64>().ok()
1754}
1755
1756fn number(words: &[Word], letter: char) -> Option<f64> {
1759 let mut at = 0;
1760 while at < words.len() {
1761 let Word {
1762 letter: word,
1763 value,
1764 } = words[at];
1765 if char::from(word) == letter {
1766 return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1767 }
1768 at += 1;
1769 }
1770 None
1771}
1772
1773#[must_use]
1776pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
1777 let mut builder = IndexBuilder::new();
1778 for piece in pieces {
1779 let _ = builder.take(piece);
1780 }
1781 builder.finish()
1782}
1783
1784#[derive(Debug, Default)]
1786enum Slot {
1787 #[default]
1789 Empty,
1790 Building(Vec<Waker>),
1792 Ready(Arc<GcodeIndex>),
1794}
1795
1796#[derive(Debug, Default)]
1798pub struct GcodeIndexes {
1799 slots: Mutex<BTreeMap<PrintId, Slot>>,
1801 looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
1807}
1808
1809#[derive(Debug)]
1811pub enum Claimed<'a> {
1812 Ready(Arc<GcodeIndex>),
1814 Build(BuildClaim<'a>),
1816}
1817
1818#[derive(Debug)]
1821pub struct BuildClaim<'a> {
1822 indexes: &'a GcodeIndexes,
1824 print_id: PrintId,
1826 done: bool,
1828}
1829
1830impl BuildClaim<'_> {
1831 #[must_use]
1833 pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
1834 let index = Arc::new(index);
1835 self.settle(Slot::Ready(Arc::clone(&index)));
1836 self.done = true;
1837 index
1838 }
1839
1840 fn settle(&self, next: Slot) {
1842 let waiting = {
1843 let mut slots = self.indexes.held();
1844 let slot = slots.entry(self.print_id).or_default();
1845 match core::mem::replace(slot, next) {
1846 Slot::Building(waiting) => waiting,
1847 Slot::Empty | Slot::Ready(_) => Vec::new(),
1848 }
1849 };
1850 for waker in waiting {
1851 waker.wake();
1852 }
1853 }
1854}
1855
1856impl Drop for BuildClaim<'_> {
1857 fn drop(&mut self) {
1858 if !self.done {
1859 self.settle(Slot::Empty);
1860 }
1861 }
1862}
1863
1864impl GcodeIndexes {
1865 fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
1867 self.slots.lock().unwrap_or_else(PoisonError::into_inner)
1868 }
1869
1870 pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
1873 Claim {
1874 indexes: self,
1875 print_id,
1876 }
1877 }
1878
1879 #[must_use]
1881 pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
1882 match self.held().get(&print_id) {
1883 Some(Slot::Ready(index)) => Some(Arc::clone(index)),
1884 _ => None,
1885 }
1886 }
1887}
1888
1889#[derive(Debug)]
1891pub struct Claim<'a> {
1892 indexes: &'a GcodeIndexes,
1894 print_id: PrintId,
1896}
1897
1898impl<'a> Future for Claim<'a> {
1899 type Output = Claimed<'a>;
1900
1901 fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
1902 let mut slots = self.indexes.held();
1903 let slot = slots.entry(self.print_id).or_default();
1904 match slot {
1905 Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
1906 Slot::Building(waiting) => {
1907 if !waiting.iter().any(|held| held.will_wake(context.waker())) {
1908 waiting.push(context.waker().clone());
1909 }
1910 Poll::Pending
1911 }
1912 Slot::Empty => {
1913 *slot = Slot::Building(Vec::new());
1914 Poll::Ready(Claimed::Build(BuildClaim {
1915 indexes: self.indexes,
1916 print_id: self.print_id,
1917 done: false,
1918 }))
1919 }
1920 }
1921 }
1922}
1923
1924const HELD_INDEXES: usize = 16;
1928
1929impl GcodeIndexes {
1930 pub(crate) fn note_look(
1936 &self,
1937 print_id: PrintId,
1938 captured: Timestamp,
1939 position: i64,
1940 now: Timestamp,
1941 ) {
1942 let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1943 let frames = looked.entry(print_id).or_default();
1944 frames.push((captured, position));
1945 frames.sort_by_key(|(captured, _)| *captured);
1946 if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
1947 let aged = frames.partition_point(|(captured, _)| *captured <= until);
1948 frames.drain(..aged.saturating_sub(1));
1949 }
1950 while looked.len() > HELD_INDEXES {
1951 let Some(oldest) = looked.keys().next().copied() else {
1952 break;
1953 };
1954 let _ = looked.remove(&oldest);
1955 }
1956 }
1957
1958 fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
1961 let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1962 looked
1963 .get(&print_id)?
1964 .iter()
1965 .rev()
1966 .find(|(captured, _)| *captured <= until)
1967 .copied()
1968 }
1969
1970 fn trim(&self, keep: PrintId) {
1972 let mut slots = self.held();
1973 let ready: Vec<PrintId> = slots
1974 .iter()
1975 .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
1976 .map(|(print_id, _)| *print_id)
1977 .collect();
1978 let over = slots.len().saturating_sub(HELD_INDEXES);
1979 for print_id in ready.into_iter().take(over) {
1980 slots.remove(&print_id);
1981 }
1982 }
1983}
1984
1985impl crate::supervisor::Supervisor {
1986 pub(crate) async fn slicer_plan(
1998 &self,
1999 print: &crate::records::PrintRecord,
2000 job: Option<&printobserver_printer_api::JobSnapshot>,
2001 interventions: &[crate::records::Intervention],
2002 ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
2003 let Some((position, file)) = job
2004 .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
2005 .filter(|(_, file)| {
2006 print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
2007 })
2008 else {
2009 return Ok(None);
2010 };
2011 let Some(index) = self.index_of(print.id, file).await else {
2012 return Ok(None);
2013 };
2014 let (flow, fan) = self
2015 .changes_since(print.id, &index, position, interventions)
2016 .await?;
2017 let mut plan = index.plan_with(position, flow, fan);
2018 plan.rise = self.rise_of(print.id, &index, position).await?;
2019 if plan.rise.is_none() {
2020 plan.unknown.push(PlanFact::Rise);
2021 plan.unknown.sort_unstable();
2022 }
2023 Ok(Some(plan))
2024 }
2025
2026 async fn rise_of(
2030 &self,
2031 print_id: PrintId,
2032 index: &GcodeIndex,
2033 position: i64,
2034 ) -> Result<Option<Rise>, crate::error::CoreError> {
2035 use printobserver_types::EventPayload as _;
2036
2037 use crate::kinds::PeriodicObservationPayload;
2038
2039 let now = self.clock().now();
2040 let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
2041 return Ok(None);
2042 };
2043 let events = self
2044 .stores()
2045 .events
2046 .history(crate::store::HistoryQuery {
2047 print_id,
2048 kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
2049 .into_iter()
2050 .collect(),
2051 since: None,
2052 until: Some(until),
2053 limit: Some(1),
2054 })
2055 .await?;
2056 let observed = events.first().and_then(|event| {
2057 let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
2058 let earlier = observed.job?.file_position_bytes?;
2059 Some((
2060 observed.frame_captured_at.unwrap_or(event.received_at),
2061 earlier,
2062 ))
2063 });
2064 let looked = self.gcode_indexes().newest_look_until(print_id, until);
2065 let newest = match (observed, looked) {
2066 (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
2067 looked
2068 } else {
2069 observed
2070 }),
2071 (observed, looked) => observed.or(looked),
2072 };
2073 Ok(newest.and_then(|(since, earlier)| {
2074 Some(Rise {
2075 since,
2076 mm: index.height_and_rise_since(earlier, position)?,
2077 })
2078 }))
2079 }
2080
2081 pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2086 let print = self.stores().prints.print(print_id).await.ok()??;
2093 if print.ended_at.is_some() {
2094 return None;
2095 }
2096 self.index_of(print.id, print.file_name.as_deref()?).await
2097 }
2098
2099 pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
2101 if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
2102 let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
2103 }
2104 }
2105
2106 pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
2113 let Some(directory) = self.config().gcode_spool_dir.clone() else {
2114 return Ok(());
2115 };
2116 let open: Vec<String> = self
2117 .stores()
2118 .prints
2119 .open_prints()
2120 .await?
2121 .iter()
2122 .map(|print| print.id.to_string())
2123 .collect();
2124 let Ok(entries) = std::fs::read_dir(&directory) else {
2132 return Ok(());
2133 };
2134 for entry in entries.flatten() {
2135 let name = entry.file_name();
2136 let Some(print) = name
2138 .to_str()
2139 .and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
2140 .filter(|print| print.parse::<PrintId>().is_ok())
2141 else {
2142 continue;
2143 };
2144 if !open.iter().any(|id| id == print) {
2145 let _ = std::fs::remove_file(entry.path());
2146 }
2147 }
2148 Ok(())
2149 }
2150
2151 async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
2153 let file_name = printobserver_types::FileName::new(file).ok()?;
2155 let claim = match self.gcode_indexes().claim(print_id).await {
2156 Claimed::Ready(index) => return Some(index),
2157 Claimed::Build(claim) => claim,
2158 };
2159 let mut builder = self
2162 .config()
2163 .gcode_spool_dir
2164 .as_deref()
2165 .and_then(|directory| {
2166 IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
2167 })
2168 .unwrap_or_default();
2169 self.read_gcode(file_name.clone(), &mut builder)
2170 .await
2171 .ok()?;
2172 let index = claim.finish(builder.finish());
2173 self.gcode_indexes().trim(print_id);
2174 if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
2175 file_name,
2176 bytes: index.bytes(),
2177 layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
2178 }) {
2179 let _ = self.append_system_event(print_id, body).await;
2182 }
2183 Some(index)
2184 }
2185
2186 async fn changes_since(
2195 &self,
2196 print_id: PrintId,
2197 index: &GcodeIndex,
2198 position: i64,
2199 interventions: &[crate::records::Intervention],
2200 ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
2201 use printobserver_types::EventPayload as _;
2202
2203 use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
2204 use crate::records::PrintAction;
2205
2206 let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
2207 .iter()
2208 .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
2209 .collect();
2210 let events = self
2211 .stores()
2212 .events
2213 .history(crate::store::HistoryQuery {
2214 print_id,
2215 kinds,
2216 since: None,
2217 until: None,
2218 limit: Some(crate::store::MAX_HISTORY_LIMIT),
2219 })
2220 .await?;
2221 let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
2222 .iter()
2223 .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
2224 .filter_map(Result::ok)
2225 .map(|payload| (payload.action_id, payload.action))
2226 .collect();
2227 let mut flow = None;
2228 let mut fan = None;
2229 for executed in events
2231 .iter()
2232 .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
2233 .filter_map(Result::ok)
2234 {
2235 let standing = executed
2236 .intervention_id
2237 .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
2238 let made = executed
2241 .file_position_bytes
2242 .and_then(|made| u64::try_from(made).ok())
2243 .unwrap_or(0);
2244 let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
2245 match requested.get(&executed.action_id) {
2246 Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
2247 flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
2248 }
2249 Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
2250 fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
2251 }
2252 _ => {}
2253 }
2254 }
2255 Ok((flow.flatten(), fan.flatten()))
2256 }
2257}
2258
2259#[cfg(test)]
2260mod tests {
2261 use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
2262 use crate::toolpath::ExtrusionKind;
2263
2264 #[test]
2268 fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
2269 for name in WALLS {
2270 assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
2271 }
2272 for name in SUPPORTS {
2273 assert_eq!(
2274 ExtrusionKind::of_type(name),
2275 ExtrusionKind::Support,
2276 "{name}"
2277 );
2278 }
2279 for name in OVER_AIR {
2280 assert!(
2281 matches!(
2282 ExtrusionKind::of_type(name),
2283 ExtrusionKind::Bridge | ExtrusionKind::Overhang
2284 ),
2285 "{name}"
2286 );
2287 }
2288 }
2289 use printobserver_types::{PrintId, Timestamp};
2290
2291 fn after(start: Timestamp, seconds: i64) -> Timestamp {
2293 start.plus_seconds(seconds).expect("an instant")
2294 }
2295
2296 fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
2298 indexes
2299 .looked
2300 .lock()
2301 .expect("the looks are held")
2302 .get(&print_id)
2303 .cloned()
2304 .unwrap_or_default()
2305 }
2306
2307 #[test]
2310 fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
2311 let indexes = GcodeIndexes::default();
2312 let print = PrintId::new();
2313 let start = Timestamp::now();
2314 indexes.note_look(print, start, 10, start);
2315 indexes.note_look(print, after(start, 60), 20, after(start, 60));
2316 let now = after(start, 60 + RISE_WINDOW_S + 30);
2317 indexes.note_look(print, now, 30, now);
2318
2319 assert_eq!(
2320 held(&indexes, print),
2321 vec![(after(start, 60), 20), (now, 30)]
2322 );
2323 assert_eq!(
2324 indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
2325 Some((after(start, 60), 20))
2326 );
2327 assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
2328 }
2329
2330 #[test]
2333 fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
2334 let indexes = GcodeIndexes::default();
2335 let now = Timestamp::now();
2336 let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
2337 prints.sort_unstable();
2338 for print in &prints {
2339 indexes.note_look(*print, now, 1, now);
2340 }
2341
2342 assert!(held(&indexes, prints[0]).is_empty());
2343 for print in &prints[1..] {
2344 assert_eq!(held(&indexes, *print), vec![(now, 1)]);
2345 }
2346 }
2347}