Skip to main content

printobserver_core/
gcode_index.rs

1//! What the slicer planned to print at each height, indexed once per print
2//! from the print's own G-code.
3//!
4//! A supervising agent judging a frame needs to know what *should* be there:
5//! a support tower, a bridge or an overhang the slicer planned looks, to a
6//! camera, much like a defect. The slicer wrote that plan into the file, and
7//! this module reads it: one streamed pass over the whole file builds a
8//! [`GcodeIndex`], and every check after that reads the plan at the print's
9//! current file position from the index rather than from the file. The agent
10//! is handed only what is derived — a [`SlicerPlan`] — and never a line of
11//! G-code.
12//!
13//! # What is read
14//!
15//! * `;LAYER_CHANGE` starts a layer and the `;Z:` after it is its height: the
16//!   markers `PrusaSlicer` writes. The last layer's height is the final one.
17//! * `;TYPE:<name>` names what the moves after it extrude — `Perimeter`,
18//!   `Support material`, `Bridge infill` — and a layer's types are those under
19//!   which any move of that layer laid material. `Custom` is left out: it
20//!   labels the slicer's own start and end G-code rather than the part.
21//! * `M73 P<percent> R<minutes>` is the slicer's own estimate of the time
22//!   left, in the normal mode. The silent mode's `M73 Q<percent> S<minutes>`
23//!   is ignored.
24//! * `M221 S<percent>` sets the flow factor and `M106 S<0–255>` the part
25//!   cooling fan, which `M107` turns off; a fan named by a `P` other than `0`
26//!   is not the part-cooling fan.
27//! * `M486 S<n>` starts laying down object `n` and `M486 S-1` stops; an
28//!   `M486 A<name>` labels the file's objects too, though no name is kept. An
29//!   object's bed area is the rectangle every move laying material for it
30//!   reached — an arc's the extremes of the part of its circle it sweeps, so a
31//!   footprint is never smaller than what was laid and a nearly straight arc
32//!   about a far centre is no larger than the line it nearly is — read to the
33//!   nearest tenth of a millimetre and then widened to whole millimetres.
34//!
35//! Everything else is a move or nothing to this reader: `G0`–`G3` with
36//! `G90`/`G91`, `M82`/`M83`, `G92` and `G28` are followed so that what laid
37//! material, and where, is known; a comment is not a command, a leading
38//! `N<line number>` is not a word, and `*<checksum>` ends the line.
39//!
40//! # Where a position falls
41//!
42//! A line counts when every byte of it, its newline included, lies before the
43//! position — `OctoPrint`'s file position is the offset after the last line it
44//! read. So a marker the printer has read is in force, and one it is part-way
45//! through is not yet.
46//!
47//! # Once per print
48//!
49//! [`GcodeIndexes`] holds each print's index in memory for as long as this
50//! process runs. The first check or context read after a print starts builds
51//! it; a read arriving while it is being built waits for that build rather
52//! than starting a second, and no read after it touches the file. A read that
53//! failed builds nothing, so the next one tries again; a file whose markers
54//! are missing builds an index that says so ([`PlanFact`]), which is not a
55//! failure.
56
57use core::future::Future;
58use core::ops::ControlFlow;
59use core::pin::Pin;
60use core::task::{Context, Poll, Waker};
61use std::collections::BTreeMap;
62use std::sync::{Arc, Mutex, PoisonError};
63
64use printobserver_printer_api::GcodeSink;
65use printobserver_types::contract::Sample;
66use printobserver_types::schemars::JsonSchema;
67use printobserver_types::serde::{Deserialize, Serialize};
68use printobserver_types::{PrintId, Timestamp};
69
70/// The longest line this reader holds; anything longer is no line it reads.
71///
72/// G-code lines are tens of bytes. A bound keeps a file that is not G-code
73/// from being held in memory a line at a time.
74const LINE_LIMIT: usize = 4096;
75
76/// The most distinct extrusion types one index names; a file naming more is
77/// no slicer's output, and its further types are not recorded.
78const TYPE_LIMIT: usize = 64;
79
80/// How long before a check an earlier frame is, at the least, for the height
81/// laid since it to be one a camera shows: half an hour.
82const RISE_WINDOW_S: i64 = 30 * 60;
83
84/// How many layers below the current one a frame shows, and so how far down a
85/// bridge or an overhang the fan should still be cooling is looked for.
86const LAYERS_SHOWN_BELOW: usize = 5;
87
88/// The flow factor under which a wall is laid starved of material.
89const FLOW_WELL_UNDER_ONE: f64 = 0.9;
90
91/// The types a part-cooling fan holds up: what is laid over air.
92const OVER_AIR: [&str; 2] = ["Bridge infill", "Overhang perimeter"];
93
94/// The types that hold a part up rather than make it.
95const SUPPORTS: [&str; 2] = ["Support material", "Support material interface"];
96
97/// The types a wall is laid as.
98const WALLS: [&str; 2] = ["Perimeter", "External perimeter"];
99
100/// The most objects one index names, for the same reason.
101const OBJECT_LIMIT: usize = 1024;
102
103/// The largest axis word read as a place, in millimetres: ten metres, far
104/// past any machine's travel. A word beyond it is no place a head can be.
105const AXIS_LIMIT: f64 = 1e4;
106
107/// The largest number any word is read as: ten kilometres of filament as an
108/// absolute `E`, far past any spool. A word beyond it is no figure a file sets.
109const WORD_LIMIT: f64 = 1e7;
110
111/// The most words one command is read as; G-code commands carry a handful.
112const WORD_COUNT: usize = 8;
113
114/// The XY travel below which a move counts as no travel at all.
115const TRAVEL_MM: f64 = 1e-6;
116
117/// The type label naming the slicer's own start and end G-code.
118const NOT_THE_PART: &str = "Custom";
119
120/// What `M106` sets the fan to with no `S` word, and what full speed is.
121const FAN_FULL: f64 = 255.0;
122
123/// One layer, from its `;LAYER_CHANGE` to the next.
124#[derive(Debug, Clone, PartialEq)]
125struct Layer {
126    /// The offset just past its `;LAYER_CHANGE` line.
127    at: u64,
128    /// Its height, from the `;Z:` after it.
129    z_mm: Option<f64>,
130    /// The types any of its moves laid material under, as bits of the index's
131    /// type table.
132    types: u64,
133}
134
135/// A value a file set, and the offset just past the line that set it.
136#[derive(Debug, Clone, Copy, PartialEq)]
137struct Mark<T> {
138    /// The offset just past the line.
139    at: u64,
140    /// What it set.
141    value: T,
142}
143
144/// An object as the reader has seen it so far.
145#[derive(Debug, Clone, Default, PartialEq)]
146struct ObjectDraft {
147    /// The rectangle its material reached: least X, least Y, most X, most Y.
148    bounds: Option<[f64; 4]>,
149}
150
151/// One file's slicer plan, by file position.
152#[derive(Debug, Clone, PartialEq)]
153pub struct GcodeIndex {
154    /// How many bytes were read.
155    bytes: u64,
156    /// How many lines were read.
157    lines: u64,
158    /// Every layer, in file order.
159    layers: Vec<Layer>,
160    /// The extrusion types, in the order the file first names them.
161    type_names: Vec<String>,
162    /// Whether the file names any extrusion type.
163    labelled_types: bool,
164    /// The slicer's normal-mode estimates of the minutes left.
165    time_left: Vec<Mark<i64>>,
166    /// The flow factors the file sets, one meaning one hundred percent.
167    flow: Vec<Mark<f64>>,
168    /// The part-cooling fan speeds the file sets, in percent.
169    fan: Vec<Mark<f64>>,
170    /// Every object the file labels and lays material for, by its number.
171    objects: Vec<BedArea>,
172    /// Whether the file labels any object.
173    labelled_objects: bool,
174}
175
176/// What a file set one adjustable to, as of a file position: the value, and
177/// the offset just past the line that set it.
178#[derive(Debug, Clone, Copy, PartialEq)]
179pub struct SetInFile {
180    /// What it set.
181    pub value: f64,
182    /// The offset just past the line that set it.
183    pub at: u64,
184}
185
186impl GcodeIndex {
187    /// How many bytes the index was built from.
188    #[must_use]
189    pub const fn bytes(&self) -> u64 {
190        self.bytes
191    }
192
193    /// How many lines the index was built from.
194    #[must_use]
195    pub const fn lines(&self) -> u64 {
196        self.lines
197    }
198
199    /// How many layers the file plans.
200    #[must_use]
201    pub const fn layer_count(&self) -> usize {
202        self.layers.len()
203    }
204
205    /// How many entries the index holds: layers, time marks, flow and fan
206    /// settings, and objects.
207    #[must_use]
208    pub const fn entries(&self) -> usize {
209        self.layers.len()
210            + self.time_left.len()
211            + self.flow.len()
212            + self.fan.len()
213            + self.objects.len()
214    }
215
216    /// How many bytes the index itself holds on the heap and inline, which is
217    /// what keeping it in memory for a print costs.
218    #[must_use]
219    pub fn resident_bytes(&self) -> usize {
220        let names: usize = self.type_names.iter().map(String::capacity).sum();
221        core::mem::size_of::<Self>()
222            + self.layers.capacity() * core::mem::size_of::<Layer>()
223            + self.type_names.capacity() * core::mem::size_of::<String>()
224            + names
225            + self.time_left.capacity() * core::mem::size_of::<Mark<i64>>()
226            + self.flow.capacity() * core::mem::size_of::<Mark<f64>>()
227            + self.fan.capacity() * core::mem::size_of::<Mark<f64>>()
228            + self.objects.capacity() * core::mem::size_of::<BedArea>()
229    }
230
231    /// The most extrusion types any one layer lays material under, and the
232    /// file position just past that layer's `;LAYER_CHANGE`: where the plan
233    /// names the most.
234    #[must_use]
235    pub fn busiest_layer(&self) -> Option<(usize, i64)> {
236        self.layers
237            .iter()
238            .map(|layer| {
239                (
240                    usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
241                    i64::try_from(layer.at).unwrap_or(i64::MAX),
242                )
243            })
244            .reduce(|best, next| if next.0 > best.0 { next } else { best })
245    }
246
247    /// The flow factor the file had set by a position, when it had set one.
248    #[must_use]
249    pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
250        last_at(&self.flow, position).map(|mark| SetInFile {
251            value: mark.value,
252            at: mark.at,
253        })
254    }
255
256    /// The part-cooling fan speed the file had set by a position, in percent,
257    /// when it had set one.
258    #[must_use]
259    pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
260        last_at(&self.fan, position).map(|mark| SetInFile {
261            value: mark.value,
262            at: mark.at,
263        })
264    }
265
266    /// The slicer's plan at one file position, with no change made through
267    /// this program beside what the file set.
268    #[must_use]
269    pub fn plan_at(&self, position: i64) -> SlicerPlan {
270        self.plan_with(position, None, None)
271    }
272
273    /// The slicer's plan at one file position, with the flow factor and fan
274    /// speed changed through this program since the file last set each, when
275    /// there was such a change.
276    #[must_use]
277    pub fn plan_with(
278        &self,
279        position: i64,
280        flow_changed: Option<f64>,
281        fan_changed: Option<f64>,
282    ) -> SlicerPlan {
283        let mut unknown = Vec::new();
284        let layer_index = self
285            .layers
286            .iter()
287            .rposition(|layer| reached(layer.at, position));
288        let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
289        if self.layers.is_empty() {
290            unknown.push(PlanFact::Layer);
291        }
292        if final_z_mm.is_none() {
293            unknown.push(PlanFact::FinalZ);
294        }
295        if !self.labelled_types {
296            unknown.push(PlanFact::Types);
297        }
298        let types = layer_index.map_or_else(Vec::new, |index| {
299            let bits = self.layers[index].types;
300            self.type_names
301                .iter()
302                .enumerate()
303                .filter(|(bit, _)| bits & (1 << bit) != 0)
304                .map(|(_, name)| name.clone())
305                .collect()
306        });
307        let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
308        if minutes_left.is_none() {
309            unknown.push(PlanFact::MinutesLeft);
310        }
311        let flow_factor = set_value(
312            self.flow_at(position).map(|set| set.value),
313            flow_changed,
314            PlanFact::FlowFactor,
315            &mut unknown,
316        );
317        let fan_percent = set_value(
318            self.fan_at(position).map(|set| set.value),
319            fan_changed,
320            PlanFact::FanPercent,
321            &mut unknown,
322        );
323        if !self.labelled_objects {
324            unknown.push(PlanFact::Objects);
325        }
326        unknown.sort_unstable();
327        let in_force =
328            |set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
329        let mut at_odds = Vec::new();
330        if let Some(index) = layer_index {
331            let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
332                .iter()
333                .fold(0, |bits, layer| bits | layer.types);
334            if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
335                && shown & self.type_bits(&OVER_AIR) != 0
336            {
337                at_odds.push(PlanMismatch::FanOffOverBridges);
338            }
339            if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
340                && self.layers[index].types & self.type_bits(&WALLS) != 0
341            {
342                at_odds.push(PlanMismatch::FlowLowOverWalls);
343            }
344        }
345        SlicerPlan {
346            layer: layer_index.map(|index| index + 1),
347            z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
348            final_z_mm,
349            types,
350            minutes_left,
351            flow_factor,
352            fan_percent,
353            object_count: self.labelled_objects.then_some(self.objects.len()),
354            objects: self.objects.clone(),
355            rise: None,
356            at_odds,
357            unknown,
358        }
359    }
360
361    /// The bits of the type table the named types hold, those the file names.
362    fn type_bits(&self, names: &[&str]) -> u64 {
363        self.type_names
364            .iter()
365            .enumerate()
366            .filter(|(_, name)| names.contains(&name.as_str()))
367            .fold(0, |bits, (bit, _)| bits | (1 << bit))
368    }
369
370    /// The height the parts themselves have gained between two positions, in
371    /// millimetres to a tenth: each layer after the earlier one's, up to the
372    /// later one's, that lays anything but supports adds its rise over the
373    /// part's top so far, and a layer laying supports alone adds nothing,
374    /// because nothing a camera watches grows there — so a support layer
375    /// slicer-interleaved between two of the part's is not the floor the next
376    /// one rises from. Nothing where a position has no
377    /// layer with a height.
378    #[must_use]
379    pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
380        self.height_and_rise_since(earlier, now)
381            .map(|[_, risen]| risen)
382    }
383
384    /// The part's own top at an earlier position and the height it gains from
385    /// there to a later one, each in millimetres to a tenth, as
386    /// [`risen_since`](Self::risen_since) counts the gain.
387    #[must_use]
388    pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
389        let at = |position| {
390            self.layers
391                .iter()
392                .rposition(|layer| reached(layer.at, position))
393                .filter(|index| self.layers[*index].z_mm.is_some())
394        };
395        let (then, now) = (at(earlier)?, at(now)?);
396        let supports = self.type_bits(&SUPPORTS);
397        let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
398        // The part's own top as of the earlier position: the last layer up to
399        // it that laid the part, or that position's own layer before any did.
400        let mut top = self.layers[..=then]
401            .iter()
402            .rev()
403            .filter(lays_the_part)
404            .find_map(|layer| layer.z_mm)
405            .or(self.layers[then].z_mm)?;
406        let height = top;
407        let mut risen = 0.0;
408        for layer in self
409            .layers
410            .iter()
411            .take(now + 1)
412            .skip(then + 1)
413            .filter(lays_the_part)
414        {
415            let Some(z) = layer.z_mm else { continue };
416            risen += (z - top).max(0.0);
417            top = top.max(z);
418        }
419        let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
420        Some([tenth(height), tenth(risen)])
421    }
422}
423
424/// One adjustable as the file set it and as this program changed it since,
425/// recording the fact as unknown when the file had set nothing.
426fn set_value(
427    file: Option<f64>,
428    changed: Option<f64>,
429    fact: PlanFact,
430    unknown: &mut Vec<PlanFact>,
431) -> Option<SetValue> {
432    if file.is_none() {
433        unknown.push(fact);
434    }
435    (file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
436}
437
438/// Whether a line ending at `at` lies wholly before `position`.
439fn reached(at: u64, position: i64) -> bool {
440    u64::try_from(position).is_ok_and(|position| at <= position)
441}
442
443/// The last mark a position has reached.
444fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
445    let Ok(position) = u64::try_from(position) else {
446        return None;
447    };
448    let reached = marks.partition_point(|mark| mark.at <= position);
449    reached.checked_sub(1).map(|index| marks[index])
450}
451
452/// One adjustable as the print's file set it at the current position, and as
453/// a change made through this program since then left it.
454#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
455#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
456#[schemars(crate = "printobserver_types::schemars")]
457pub struct SetValue {
458    /// What the file's own commands set it to, by the current position.
459    #[serde(default, skip_serializing_if = "Option::is_none")]
460    pub file: Option<f64>,
461    /// What the latest change made through this program set it to, when one
462    /// was made after the file last set it.
463    #[serde(default, skip_serializing_if = "Option::is_none")]
464    pub changed: Option<f64>,
465}
466
467/// The bed area one object of the print covers: the rectangle
468/// `[x_min, y_min, x_max, y_max]` its material reaches, in whole millimetres —
469/// each edge read to the nearest tenth, then each least edge rounded down and
470/// each most edge up, so that it holds every move laying that object down.
471pub type BedArea = [i64; 4];
472
473/// How far the plan has risen since one earlier frame of this print that was
474/// seen: the height a camera should show the parts to have gained since then.
475#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
476#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
477#[schemars(crate = "printobserver_types::schemars")]
478pub struct Rise {
479    /// When that earlier frame was captured: the newest frame at least half
480    /// an hour old that a periodic observation or a look at this print was
481    /// given, as that observation or look states its capture time.
482    pub since: Timestamp,
483    /// Two heights of the print's highest point, in millimetres: the first
484    /// is where the plan had it when that frame was captured, the second how
485    /// far it should have risen since — the rise of every layer since that
486    /// lays anything but supports. They are the plate's, not every part's: a
487    /// part the plan has finished does not grow with it.
488    pub mm: [f64; 2],
489}
490
491/// A setting in force that the plan at this height says is wrong for what is
492/// being laid.
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
495#[schemars(crate = "printobserver_types::schemars")]
496pub enum PlanMismatch {
497    /// The part-cooling fan is off while the current layer or the few below
498    /// it, which a frame shows, bridge or overhang.
499    FanOffOverBridges,
500    /// The flow factor is well under one while the current layer lays walls.
501    FlowLowOverWalls,
502}
503
504/// A fact of the plan the print's file does not state.
505#[derive(
506    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
507)]
508#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
509#[schemars(crate = "printobserver_types::schemars")]
510pub enum PlanFact {
511    /// The file marks no layers.
512    Layer,
513    /// The file states no final height.
514    FinalZ,
515    /// The file labels no extrusion types.
516    Types,
517    /// The file carries no estimate of the time left, by the current position.
518    MinutesLeft,
519    /// The file sets no flow factor, by the current position.
520    FlowFactor,
521    /// The file sets no part-cooling fan speed, by the current position.
522    FanPercent,
523    /// The file labels no objects.
524    Objects,
525    /// No frame of this print is half an hour old with a position to rise
526    /// from, so how far the parts should have grown is not known, and no
527    /// growth can be judged from frames closer together.
528    Rise,
529}
530
531/// What the slicer planned at the print's current file position: the shape
532/// and place of what should be printing, read from the print's own G-code.
533///
534/// These are the slicer's plan rather than an observation: a feature named
535/// here is part of the design at this height, and nothing here says how well
536/// it printed.
537#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
538#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
539#[schemars(crate = "printobserver_types::schemars")]
540pub struct SlicerPlan {
541    /// The layer the print is in, counting the first as 1; absent before the
542    /// first.
543    #[serde(default, skip_serializing_if = "Option::is_none")]
544    pub layer: Option<usize>,
545    /// The current layer's height, in millimetres.
546    #[serde(default, skip_serializing_if = "Option::is_none")]
547    pub z_mm: Option<f64>,
548    /// The final layer's height, in millimetres.
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub final_z_mm: Option<f64>,
551    /// What the current layer lays material as, in the order the file first
552    /// names each: `Perimeter`, `Support material`, `Bridge infill`.
553    #[serde(default, skip_serializing_if = "Vec::is_empty")]
554    pub types: Vec<String>,
555    /// The slicer's own estimate of the minutes left, at the current position.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub minutes_left: Option<i64>,
558    /// The flow factor, one meaning one hundred percent.
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    pub flow_factor: Option<SetValue>,
561    /// The part-cooling fan speed, in percent.
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    pub fan_percent: Option<SetValue>,
564    /// How many objects the file lays down; absent when it labels none.
565    #[serde(default, skip_serializing_if = "Option::is_none")]
566    pub object_count: Option<usize>,
567    /// The bed area each object the file lays down covers, unnamed, as
568    /// `[x_min, y_min, x_max, y_max]` in whole millimetres, in the order of
569    /// the file's object numbers.
570    #[serde(default, skip_serializing_if = "Vec::is_empty")]
571    pub objects: Vec<BedArea>,
572    /// How far the plan has risen since an earlier frame; absent before any
573    /// frame is half an hour old.
574    #[serde(default, skip_serializing_if = "Option::is_none")]
575    pub rise: Option<Rise>,
576    /// Each setting in force the plan at this height says is wrong.
577    #[serde(default, skip_serializing_if = "Vec::is_empty")]
578    pub at_odds: Vec<PlanMismatch>,
579    /// The facts the file does not state, which are therefore unknown rather
580    /// than absent.
581    #[serde(default, skip_serializing_if = "Vec::is_empty")]
582    pub unknown: Vec<PlanFact>,
583}
584
585impl Sample for SlicerPlan {
586    fn sample_full() -> Self {
587        Self {
588            layer: Some(12),
589            z_mm: Some(2.4),
590            types: vec![
591                "Perimeter".to_owned(),
592                "External perimeter".to_owned(),
593                "Support material".to_owned(),
594            ],
595            final_z_mm: Some(30.0),
596            minutes_left: Some(42),
597            flow_factor: Some(SetValue {
598                file: Some(1.0),
599                changed: Some(0.95),
600            }),
601            fan_percent: Some(SetValue {
602                file: Some(100.0),
603                changed: None,
604            }),
605            object_count: Some(1),
606            objects: vec![[100, 99, 150, 117]],
607            rise: Some(Rise {
608                since: Timestamp::sample_full(),
609                mm: [7.2, 4.8],
610            }),
611            at_odds: vec![PlanMismatch::FlowLowOverWalls],
612            unknown: vec![PlanFact::Objects],
613        }
614    }
615
616    fn sample_minimal() -> Self {
617        Self {
618            layer: None,
619            z_mm: None,
620            final_z_mm: None,
621            types: Vec::new(),
622            minutes_left: None,
623            flow_factor: None,
624            fan_percent: None,
625            object_count: None,
626            objects: Vec::new(),
627            rise: None,
628            at_odds: Vec::new(),
629            unknown: Vec::new(),
630        }
631    }
632}
633
634/// How a coordinate is read: as a place, or as a distance from the last one.
635#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
636enum Positioning {
637    /// A place: `M82` for `E`, `G90` for the axes. What a firmware starts in.
638    #[default]
639    Absolute,
640    /// A distance: `M83` for `E`, `G91` for the axes.
641    Relative,
642}
643
644/// Builds a [`GcodeIndex`] from a file streamed into it, a piece at a time,
645/// in one pass: the [`GcodeSink`] the printer port's whole-file read feeds.
646#[derive(Debug, Default)]
647pub struct IndexBuilder {
648    /// The line being read, up to [`LINE_LIMIT`].
649    line: Vec<u8>,
650    /// Whether the line being read has run past [`LINE_LIMIT`].
651    overlong: bool,
652    /// How many bytes have been read.
653    read: u64,
654    /// How many lines have been read.
655    lines: u64,
656    /// Every layer so far.
657    layers: Vec<Layer>,
658    /// The extrusion types so far.
659    type_names: Vec<String>,
660    /// Whether any type was named.
661    labelled_types: bool,
662    /// The type the moves being read extrude, as a bit of the type table.
663    current_type: Option<usize>,
664    /// The time estimates so far.
665    time_left: Vec<Mark<i64>>,
666    /// The flow factors so far.
667    flow: Vec<Mark<f64>>,
668    /// The fan speeds so far.
669    fan: Vec<Mark<f64>>,
670    /// Every object labelled so far, in the order first labelled.
671    objects: Vec<ObjectDraft>,
672    /// Where each object's number is in `objects`.
673    object_numbers: BTreeMap<i64, usize>,
674    /// The object the moves being read lay material for, by its place in
675    /// `objects`.
676    current_object: Option<usize>,
677    /// Whether any object was labelled.
678    labelled_objects: bool,
679    /// Where the head is in X, Y and Z.
680    at: [f64; 3],
681    /// The extruder's position.
682    e: f64,
683    /// What `G90`/`G91` last said.
684    axes: Positioning,
685    /// What `M82`/`M83` last said.
686    extruder: Positioning,
687}
688
689impl GcodeSink for IndexBuilder {
690    fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
691        // Plain index loops rather than iterator adaptors throughout this
692        // reader: it runs over every byte of a print, and is as fast in a
693        // build without optimisation as in one with it only written so.
694        let mut start = 0;
695        let mut at = 0;
696        while at < piece.len() {
697            if piece[at] == b'\n' {
698                let head = &piece[start..at];
699                self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
700                if self.line.is_empty() && !self.overlong {
701                    // The whole line is in this piece: read it where it lies.
702                    self.lines += 1;
703                    if head.len() <= LINE_LIMIT {
704                        self.read_line(head);
705                    }
706                } else {
707                    self.hold(head);
708                    self.end_line();
709                }
710                start = at + 1;
711            }
712            at += 1;
713        }
714        let rest = &piece[start..];
715        self.hold(rest);
716        self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
717        ControlFlow::Continue(())
718    }
719}
720
721impl IndexBuilder {
722    /// A builder that has read nothing.
723    #[must_use]
724    pub fn new() -> Self {
725        Self::default()
726    }
727
728    /// The index of everything read, the file's last line counting whether or
729    /// not it ended in a newline.
730    #[must_use]
731    pub fn finish(mut self) -> GcodeIndex {
732        if !self.line.is_empty() || self.overlong {
733            self.end_line();
734        }
735        let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
736        let objects = self
737            .object_numbers
738            .into_values()
739            .filter_map(|place| drafts.get_mut(place).and_then(Option::take))
740            .filter_map(|draft| {
741                draft.bounds.map(|[least_x, least_y, most_x, most_y]| {
742                    [
743                        whole(tenth(least_x).floor()),
744                        whole(tenth(least_y).floor()),
745                        whole(tenth(most_x).ceil()),
746                        whole(tenth(most_y).ceil()),
747                    ]
748                })
749            })
750            .collect();
751        GcodeIndex {
752            bytes: self.read,
753            lines: self.lines,
754            layers: self.layers,
755            type_names: self.type_names,
756            labelled_types: self.labelled_types,
757            time_left: self.time_left,
758            flow: self.flow,
759            fan: self.fan,
760            objects,
761            labelled_objects: self.labelled_objects,
762        }
763    }
764
765    /// Hold more of the line being read, up to its bound.
766    fn hold(&mut self, bytes: &[u8]) {
767        if self.overlong {
768            return;
769        }
770        if self.line.len() + bytes.len() > LINE_LIMIT {
771            self.overlong = true;
772            self.line.clear();
773            return;
774        }
775        self.line.extend_from_slice(bytes);
776    }
777
778    /// Read the line held, which ended at the offset read so far.
779    fn end_line(&mut self) {
780        self.lines += 1;
781        let line = core::mem::take(&mut self.line);
782        if !self.overlong {
783            self.read_line(&line);
784        }
785        self.overlong = false;
786        self.line = line;
787        self.line.clear();
788    }
789
790    /// Read one whole line, without its newline.
791    fn read_line(&mut self, raw: &[u8]) {
792        let raw = raw.trim_ascii();
793        if let Some(comment) = raw.strip_prefix(b";") {
794            if let Ok(comment) = core::str::from_utf8(comment) {
795                self.comment(comment.trim_end());
796            }
797            return;
798        }
799        // A move is nearly every line of a print, so `G0`–`G3` written as a
800        // slicer writes them are read by their own one pass.
801        if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
802            self.motion(u32::from(code - b'0'), &move_of(rest));
803            return;
804        }
805        let held = words(raw);
806        let mut words = held.as_slice();
807        // A leading `N<line number>` numbers the line and is no word of it.
808        if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
809            words = rest;
810        }
811        let Some(first) = words.first() else {
812            return;
813        };
814        let code = if held.numbered {
815            held.second_code
816        } else {
817            held.first_code
818        };
819        match (char::from(first.letter), code) {
820            ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
821            ('G', Some(28)) => self.home(&words[1..]),
822            ('G', Some(90)) => self.axes = Positioning::Absolute,
823            ('G', Some(91)) => self.axes = Positioning::Relative,
824            ('G', Some(92)) => self.declare(&words[1..]),
825            ('M', Some(82)) => self.extruder = Positioning::Absolute,
826            ('M', Some(83)) => self.extruder = Positioning::Relative,
827            ('M', Some(73)) => self.estimate(&words[1..]),
828            ('M', Some(221)) => self.flow_factor(&words[1..]),
829            ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
830            ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
831            ('M', Some(486)) => self.object(raw, &words[1..]),
832            _ => {}
833        }
834    }
835
836    /// A comment line: a layer change, a height, or an extrusion type.
837    fn comment(&mut self, comment: &str) {
838        if comment == "LAYER_CHANGE" {
839            self.layers.push(Layer {
840                at: self.read,
841                z_mm: None,
842                types: 0,
843            });
844        } else if let Some(z) = comment.strip_prefix("Z:") {
845            if let Some(layer) = self.layers.last_mut()
846                && layer.z_mm.is_none()
847            {
848                // A height is a place on the Z axis: no lower than the bed and
849                // no further than any machine reaches.
850                layer.z_mm = z
851                    .trim()
852                    .parse::<f64>()
853                    .ok()
854                    .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
855            }
856        } else if let Some(name) = comment.strip_prefix("TYPE:") {
857            let name = name.trim();
858            self.labelled_types = true;
859            self.current_type = if name == NOT_THE_PART {
860                None
861            } else {
862                self.intern(name)
863            };
864        }
865    }
866
867    /// The bit of the type table one name is, adding it when there is room.
868    fn intern(&mut self, name: &str) -> Option<usize> {
869        if let Some(bit) = self.type_names.iter().position(|held| held == name) {
870            return Some(bit);
871        }
872        if self.type_names.len() >= TYPE_LIMIT {
873            return None;
874        }
875        self.type_names.push(name.to_owned());
876        Some(self.type_names.len() - 1)
877    }
878
879    /// A move: where the head goes, and whether it laid material on the way.
880    fn motion(&mut self, code: u32, words: &Move) {
881        // Plain statements rather than iterators and closures: this runs for
882        // every move of a print.
883        let start = self.at;
884        let relative = self.axes == Positioning::Relative;
885        if let Some(x) = words.x {
886            self.place(0, x, relative);
887        }
888        if let Some(y) = words.y {
889            self.place(1, y, relative);
890        }
891        if let Some(z) = words.z {
892            self.place(2, z, relative);
893        }
894        let mut fed = 0.0;
895        if let Some(value) = words.e {
896            if relative || self.extruder == Positioning::Relative {
897                self.e += value;
898                fed = value;
899            } else {
900                fed = value - self.e;
901                self.e = value;
902            }
903        }
904        let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
905        if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
906            return;
907        }
908        if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
909            layer.types |= 1 << bit;
910        }
911        let Some(object) = self.current_object else {
912            return;
913        };
914        let end = self.at;
915        let draft = &mut self.objects[object];
916        grow(&mut draft.bounds, start[0], start[1]);
917        grow(&mut draft.bounds, end[0], end[1]);
918        if code >= 2 {
919            let turn = if code == 2 {
920                Turn::Clockwise
921            } else {
922                Turn::CounterClockwise
923            };
924            for [x, y] in arc_extremes(words, turn, start, end) {
925                grow(&mut draft.bounds, x, y);
926            }
927        }
928    }
929
930    /// Move one axis to a place, or by a distance, when where it lands is
931    /// within reach: a run of distances each within reach can carry the head
932    /// past it, and a place beyond it is no place a head can be.
933    fn place(&mut self, axis: usize, value: f64, relative: bool) {
934        let landed = if relative {
935            self.at[axis] + value
936        } else {
937            value
938        };
939        if landed.abs() <= AXIS_LIMIT {
940            self.at[axis] = landed;
941        }
942    }
943
944    /// `G28`: the axes it names, or every axis when it names none, go home.
945    fn home(&mut self, words: &[Word]) {
946        let named: Vec<usize> = ['X', 'Y', 'Z']
947            .into_iter()
948            .enumerate()
949            .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
950            .map(|(axis, _)| axis)
951            .collect();
952        if named.is_empty() {
953            self.at = [0.0; 3];
954        } else {
955            for axis in named {
956                self.at[axis] = 0.0;
957            }
958        }
959    }
960
961    /// `G92`: where the named axes are, without moving them; bare, every axis
962    /// and the extruder are at zero.
963    fn declare(&mut self, words: &[Word]) {
964        if words.is_empty() {
965            self.at = [0.0; 3];
966            self.e = 0.0;
967            return;
968        }
969        for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
970            if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
971                self.at[axis] = value;
972            }
973        }
974        if let Some(value) = number(words, 'E') {
975            self.e = value;
976        }
977    }
978
979    /// `M73`: the normal mode's estimate of the minutes left, `P` and `R`.
980    fn estimate(&mut self, words: &[Word]) {
981        if number(words, 'P').is_none() {
982            return;
983        }
984        if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
985            self.time_left.push(Mark {
986                at: self.read,
987                value: whole(minutes),
988            });
989        }
990    }
991
992    /// `M221 S<percent>`: the flow factor.
993    fn flow_factor(&mut self, words: &[Word]) {
994        if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
995            mark_setting(&mut self.flow, self.read, percent / 100.0);
996        }
997    }
998
999    /// `M106 S<speed>` or `M107`: the part-cooling fan, in percent.
1000    fn fan_speed(&mut self, words: &[Word], command: Fan) {
1001        if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1002            return;
1003        }
1004        let speed = match command {
1005            Fan::Off => 0.0,
1006            Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1007        };
1008        let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1009        mark_setting(&mut self.fan, self.read, percent);
1010    }
1011
1012    /// `M486`: an object starting, stopping, or being named.
1013    fn object(&mut self, raw: &[u8], words: &[Word]) {
1014        // A name labels the file's objects, though none is kept: an object is
1015        // its place on the bed.
1016        if raw
1017            .strip_prefix(b"M486")
1018            .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1019        {
1020            self.labelled_objects = true;
1021            return;
1022        }
1023        // An object is a whole number, and `-1` alone stops laying one down;
1024        // any other number names no object and changes nothing.
1025        let Some(number) = number(words, 'S')
1026            .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1027        else {
1028            return;
1029        };
1030        self.labelled_objects = true;
1031        if number < 0.0 {
1032            self.current_object = None;
1033            return;
1034        }
1035        let id = whole(number);
1036        let place = if let Some(place) = self.object_numbers.get(&id) {
1037            *place
1038        } else if self.objects.len() >= OBJECT_LIMIT {
1039            self.current_object = None;
1040            return;
1041        } else {
1042            self.objects.push(ObjectDraft::default());
1043            self.object_numbers.insert(id, self.objects.len() - 1);
1044            self.objects.len() - 1
1045        };
1046        self.current_object = Some(place);
1047    }
1048}
1049
1050/// Record a value a file set, where it set it — every time, the same value
1051/// included, because a command repeating a value still puts it back over a
1052/// change made since.
1053fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
1054    marks.push(Mark { at, value });
1055}
1056
1057/// The whole number nearest a value a file wrote, which every word is
1058/// bounded well inside [`i64`] by.
1059fn whole(value: f64) -> i64 {
1060    format!("{:.0}", value.round()).parse().unwrap_or_default()
1061}
1062
1063/// A length rounded to a tenth of a millimetre before a bed area is widened
1064/// to whole millimetres, so that an arc's extreme computed a hair past a whole
1065/// number does not widen it by a millimetre more.
1066fn tenth(value: f64) -> f64 {
1067    (value * 10.0).round() / 10.0
1068}
1069
1070/// Grow a rectangle to reach a point.
1071fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
1072    *bounds = Some(match *bounds {
1073        None => [x, y, x, y],
1074        Some([least_x, least_y, most_x, most_y]) => {
1075            [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
1076        }
1077    });
1078}
1079
1080/// Which way an arc turns: `G2` clockwise, `G3` counter-clockwise.
1081#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1082enum Turn {
1083    /// `G2`.
1084    Clockwise,
1085    /// `G3`.
1086    CounterClockwise,
1087}
1088
1089/// What a part-cooling fan command does: `M106` sets a speed, `M107` turns
1090/// the fan off.
1091#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1092enum Fan {
1093    /// `M106`, at its `S` speed or full.
1094    Set,
1095    /// `M107`.
1096    Off,
1097}
1098
1099/// The points of an arc's circle at which it reaches furthest along X or Y,
1100/// of the part of the circle the arc sweeps: what an arc lays beyond its two
1101/// ends.
1102///
1103/// The centre is the one `I` and `J` name, or for the `R` form the one on the
1104/// side of the chord the direction and the radius's sign choose. `G2` sweeps
1105/// clockwise and `G3` counter-clockwise; an arc ending where it began is the
1106/// whole circle.
1107fn arc_extremes(
1108    words: &Move,
1109    turn: Turn,
1110    start: [f64; 3],
1111    end: [f64; 3],
1112) -> impl Iterator<Item = [f64; 2]> {
1113    let centre = words.r.map_or_else(
1114        || {
1115            Some([
1116                start[0] + words.i.unwrap_or(0.0),
1117                start[1] + words.j.unwrap_or(0.0),
1118            ])
1119        },
1120        |radius| centre_of_radius(radius, turn, start, end),
1121    );
1122    let reach = centre.map(|centre| {
1123        let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
1124        let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
1125        let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
1126        let tau = core::f64::consts::TAU;
1127        // How far the arc turns, counter-clockwise from `from`, as a positive
1128        // sweep: a clockwise arc is the same sweep taken from its end.
1129        let (base, sweep) = match turn {
1130            Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
1131            Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
1132        };
1133        let sweep = if sweep < 1e-9 { tau } else { sweep };
1134        (0..4).filter_map(move |quarter| {
1135            let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
1136            ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
1137                [
1138                    centre[0] + radius * angle.cos(),
1139                    centre[1] + radius * angle.sin(),
1140                ]
1141            })
1142        })
1143    });
1144    reach.into_iter().flatten()
1145}
1146
1147/// The centre of an `R`-form arc: on the chord's perpendicular, on the side a
1148/// clockwise or counter-clockwise turn of a short arc puts it, and on the other
1149/// side for a negative radius, which asks for the long way round. Nothing when
1150/// the chord is longer than the circle allows, or the arc ends where it began.
1151fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
1152    let chord = [end[0] - start[0], end[1] - start[1]];
1153    let length = chord[0].hypot(chord[1]);
1154    if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
1155        return None;
1156    }
1157    let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
1158    let left = match turn {
1159        Turn::Clockwise => -1.0,
1160        Turn::CounterClockwise => 1.0,
1161    };
1162    let side = left * radius.signum() * rise / length;
1163    Some([
1164        start[0] + chord[0] / 2.0 - chord[1] * side,
1165        start[1] + chord[1] / 2.0 + chord[0] * side,
1166    ])
1167}
1168
1169/// The words of a command, each a letter, the text after it and the number
1170/// that text is when it is one, up to [`WORD_COUNT`] of them: up to the `;`
1171/// a comment starts at or the `*` a checksum does.
1172///
1173/// Each number is read by [`number_at`].
1174fn words(command: &[u8]) -> Words {
1175    let mut found = Words {
1176        held: [Word {
1177            letter: 0,
1178            value: f64::NAN,
1179        }; WORD_COUNT],
1180        len: 0,
1181        first_code: None,
1182        second_code: None,
1183        numbered: false,
1184    };
1185    let length = command.len();
1186    let mut at = 0;
1187    while at < length {
1188        let letter = command[at];
1189        if letter == b';' || letter == b'*' {
1190            break;
1191        }
1192        at += 1;
1193        let upper = match letter {
1194            b'a'..=b'z' => letter - (b'a' - b'A'),
1195            b'A'..=b'Z' => letter,
1196            _ => continue,
1197        };
1198        let start = at;
1199        let (value, next) = number_at(command, at);
1200        at = next;
1201        let text = &command[start..at];
1202        // A command's code is the first word's, or the second's after a
1203        // line number, read as the whole number it is written as.
1204        if found.len == 0 {
1205            found.first_code = whole_number(text);
1206            found.numbered = upper == b'N';
1207        } else if found.len == 1 {
1208            found.second_code = whole_number(text);
1209        }
1210        if found.len < WORD_COUNT {
1211            found.held[found.len] = Word {
1212                letter: upper,
1213                value,
1214            };
1215            found.len += 1;
1216        }
1217    }
1218    found
1219}
1220
1221/// The number a word carries, read from `at` to the next space, letter, `;`
1222/// or `*`, and the offset just past it; a word that is no number is not a
1223/// number.
1224///
1225/// The end is found with a plain loop rather than an iterator adaptor, and the
1226/// number is read by the standard library's own parse, which is compiled
1227/// optimised whatever this crate is built as: this runs for every number of
1228/// every move of a print.
1229fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
1230    let start = at;
1231    while at < line.len()
1232        && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
1233    {
1234        at += 1;
1235    }
1236    (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
1237}
1238
1239/// The words of a move this reader uses, each a number within reach when the
1240/// move carries it: where it goes, what it feeds, and an arc's centre or
1241/// radius.
1242#[derive(Debug, Clone, Copy, Default)]
1243struct Move {
1244    /// `X`.
1245    x: Option<f64>,
1246    /// `Y`.
1247    y: Option<f64>,
1248    /// `Z`.
1249    z: Option<f64>,
1250    /// `E`.
1251    e: Option<f64>,
1252    /// `I`.
1253    i: Option<f64>,
1254    /// `J`.
1255    j: Option<f64>,
1256    /// `R`.
1257    r: Option<f64>,
1258}
1259
1260impl Move {
1261    /// A move's words, from a command read word by word.
1262    fn of(words: &[Word]) -> Self {
1263        Self {
1264            x: number(words, 'X'),
1265            y: number(words, 'Y'),
1266            z: number(words, 'Z'),
1267            e: number(words, 'E'),
1268            i: number(words, 'I'),
1269            j: number(words, 'J'),
1270            r: number(words, 'R'),
1271        }
1272    }
1273}
1274
1275/// A move's words, read in one pass from what follows its `G0`–`G3`: the
1276/// first of each letter it uses, up to the `;` a comment starts at or the `*`
1277/// a checksum does. Every other word — the feedrate above all — is passed
1278/// over unread, which is what keeps this the cheap path through a print.
1279fn move_of(line: &[u8]) -> Move {
1280    let mut found = Move::default();
1281    let length = line.len();
1282    let mut at = 0;
1283    while at < length {
1284        let letter = line[at];
1285        at += 1;
1286        let slot = match letter {
1287            b';' | b'*' => break,
1288            b'X' | b'x' => &mut found.x,
1289            b'Y' | b'y' => &mut found.y,
1290            b'Z' | b'z' => &mut found.z,
1291            b'E' | b'e' => &mut found.e,
1292            b'I' | b'i' => &mut found.i,
1293            b'J' | b'j' => &mut found.j,
1294            b'R' | b'r' => &mut found.r,
1295            b'A'..=b'Z' | b'a'..=b'z' => {
1296                while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
1297                    at += 1;
1298                }
1299                continue;
1300            }
1301            _ => continue,
1302        };
1303        let (value, next) = number_at(line, at);
1304        at = next;
1305        if slot.is_none() {
1306            *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1307        }
1308    }
1309    found
1310}
1311
1312/// One word of a command: its letter, upper-cased, and the number it carries,
1313/// not a number when it carries none.
1314#[derive(Debug, Clone, Copy)]
1315struct Word {
1316    /// The letter.
1317    letter: u8,
1318    /// The number, `NaN` when the word's text is none.
1319    value: f64,
1320}
1321
1322/// One command's words, held without allocating.
1323struct Words {
1324    /// The words, the first `len` of them read.
1325    held: [Word; WORD_COUNT],
1326    /// How many were read.
1327    len: usize,
1328    /// The first word's text, as a whole number when it is one.
1329    first_code: Option<u32>,
1330    /// The second word's text, as a whole number when it is one.
1331    second_code: Option<u32>,
1332    /// Whether the first word is a line number.
1333    numbered: bool,
1334}
1335
1336impl Words {
1337    /// The words read.
1338    fn as_slice(&self) -> &[Word] {
1339        &self.held[..self.len]
1340    }
1341}
1342
1343/// The whole number a command's code is, when it is digits alone.
1344fn whole_number(text: &[u8]) -> Option<u32> {
1345    let mut value: u32 = 0;
1346    let mut at = 0;
1347    while at < text.len() {
1348        let byte = text[at];
1349        if !byte.is_ascii_digit() {
1350            return None;
1351        }
1352        value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
1353        at += 1;
1354    }
1355    (!text.is_empty()).then_some(value)
1356}
1357
1358/// The number a word's text is, by the standard library's own parse.
1359fn decimal(text: &[u8]) -> Option<f64> {
1360    core::str::from_utf8(text).ok()?.parse::<f64>().ok()
1361}
1362
1363/// The number one word carries, when the command has that word and it is a
1364/// number within reach.
1365fn number(words: &[Word], letter: char) -> Option<f64> {
1366    let mut at = 0;
1367    while at < words.len() {
1368        let Word {
1369            letter: word,
1370            value,
1371        } = words[at];
1372        if char::from(word) == letter {
1373            return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1374        }
1375        at += 1;
1376    }
1377    None
1378}
1379
1380/// Build one file's index from its pieces, in order — what the whole-file
1381/// read does with the pieces it is handed.
1382#[must_use]
1383pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
1384    let mut builder = IndexBuilder::new();
1385    for piece in pieces {
1386        let _ = builder.take(piece);
1387    }
1388    builder.finish()
1389}
1390
1391/// One print's index, as the cache holds it.
1392#[derive(Debug, Default)]
1393enum Slot {
1394    /// Nothing is built and nothing is building.
1395    #[default]
1396    Empty,
1397    /// A build is under way, and these are waiting for it.
1398    Building(Vec<Waker>),
1399    /// Built.
1400    Ready(Arc<GcodeIndex>),
1401}
1402
1403/// Every print's index, held for as long as this process runs.
1404#[derive(Debug, Default)]
1405pub struct GcodeIndexes {
1406    /// One slot per print that has been asked for.
1407    slots: Mutex<BTreeMap<PrintId, Slot>>,
1408    /// The frames each print's looks were given, by their capture time, with
1409    /// the file position the job had reached as each was taken: a look's
1410    /// record keeps no job, so a rise since one is measured from this. It is
1411    /// this process's alone, as the indexes are: a restarted one measures
1412    /// from periodic observations until its own looks are old enough.
1413    looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
1414}
1415
1416/// What asking for one print's index answered.
1417#[derive(Debug)]
1418pub enum Claimed<'a> {
1419    /// It is built.
1420    Ready(Arc<GcodeIndex>),
1421    /// Nothing is building it, and this caller is to: it holds the claim.
1422    Build(BuildClaim<'a>),
1423}
1424
1425/// The one caller building a print's index. Dropping it unfinished hands the
1426/// build to whoever asks next, and wakes everyone waiting.
1427#[derive(Debug)]
1428pub struct BuildClaim<'a> {
1429    /// The cache it was claimed from.
1430    indexes: &'a GcodeIndexes,
1431    /// The print it is building for.
1432    print_id: PrintId,
1433    /// Whether it has finished.
1434    done: bool,
1435}
1436
1437impl BuildClaim<'_> {
1438    /// Hand the built index over, waking every caller waiting for it.
1439    #[must_use]
1440    pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
1441        let index = Arc::new(index);
1442        self.settle(Slot::Ready(Arc::clone(&index)));
1443        self.done = true;
1444        index
1445    }
1446
1447    /// Put the slot into its next state and wake whoever waited.
1448    fn settle(&self, next: Slot) {
1449        let waiting = {
1450            let mut slots = self.indexes.held();
1451            let slot = slots.entry(self.print_id).or_default();
1452            match core::mem::replace(slot, next) {
1453                Slot::Building(waiting) => waiting,
1454                Slot::Empty | Slot::Ready(_) => Vec::new(),
1455            }
1456        };
1457        for waker in waiting {
1458            waker.wake();
1459        }
1460    }
1461}
1462
1463impl Drop for BuildClaim<'_> {
1464    fn drop(&mut self) {
1465        if !self.done {
1466            self.settle(Slot::Empty);
1467        }
1468    }
1469}
1470
1471impl GcodeIndexes {
1472    /// The slots, held for one read or write.
1473    fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
1474        self.slots.lock().unwrap_or_else(PoisonError::into_inner)
1475    }
1476
1477    /// One print's index when it is built, or the claim to build it, waiting
1478    /// while another caller is building it.
1479    pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
1480        Claim {
1481            indexes: self,
1482            print_id,
1483        }
1484    }
1485
1486    /// One print's index, when it is built.
1487    #[must_use]
1488    pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
1489        match self.held().get(&print_id) {
1490            Some(Slot::Ready(index)) => Some(Arc::clone(index)),
1491            _ => None,
1492        }
1493    }
1494}
1495
1496/// The future [`GcodeIndexes::claim`] answers.
1497#[derive(Debug)]
1498pub struct Claim<'a> {
1499    /// The cache.
1500    indexes: &'a GcodeIndexes,
1501    /// The print.
1502    print_id: PrintId,
1503}
1504
1505impl<'a> Future for Claim<'a> {
1506    type Output = Claimed<'a>;
1507
1508    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
1509        let mut slots = self.indexes.held();
1510        let slot = slots.entry(self.print_id).or_default();
1511        match slot {
1512            Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
1513            Slot::Building(waiting) => {
1514                if !waiting.iter().any(|held| held.will_wake(context.waker())) {
1515                    waiting.push(context.waker().clone());
1516                }
1517                Poll::Pending
1518            }
1519            Slot::Empty => {
1520                *slot = Slot::Building(Vec::new());
1521                Poll::Ready(Claimed::Build(BuildClaim {
1522                    indexes: self.indexes,
1523                    print_id: self.print_id,
1524                    done: false,
1525                }))
1526            }
1527        }
1528    }
1529}
1530
1531/// The most indexes held at once. A print's index is a few tens of kilobytes,
1532/// and a supervisor watches one print at a time; this bounds what a server
1533/// running for months holds of prints long finished.
1534const HELD_INDEXES: usize = 16;
1535
1536impl GcodeIndexes {
1537    /// Remember that a look at one print was given a frame captured at
1538    /// `captured`, with the job at `position`, and forget what no rise can be
1539    /// measured from any more: every look older than the newest one already
1540    /// half an hour old before `now`, and the looks of prints beyond
1541    /// [`HELD_INDEXES`], oldest print first.
1542    pub(crate) fn note_look(
1543        &self,
1544        print_id: PrintId,
1545        captured: Timestamp,
1546        position: i64,
1547        now: Timestamp,
1548    ) {
1549        let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1550        let frames = looked.entry(print_id).or_default();
1551        frames.push((captured, position));
1552        frames.sort_by_key(|(captured, _)| *captured);
1553        if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
1554            let aged = frames.partition_point(|(captured, _)| *captured <= until);
1555            frames.drain(..aged.saturating_sub(1));
1556        }
1557        while looked.len() > HELD_INDEXES {
1558            let Some(oldest) = looked.keys().next().copied() else {
1559                break;
1560            };
1561            let _ = looked.remove(&oldest);
1562        }
1563    }
1564
1565    /// The newest look at one print whose frame was captured no later than
1566    /// `until`: its capture time and the job's position then.
1567    fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
1568        let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1569        looked
1570            .get(&print_id)?
1571            .iter()
1572            .rev()
1573            .find(|(captured, _)| *captured <= until)
1574            .copied()
1575    }
1576
1577    /// Let go of finished indexes beyond [`HELD_INDEXES`], keeping `keep`.
1578    fn trim(&self, keep: PrintId) {
1579        let mut slots = self.held();
1580        let ready: Vec<PrintId> = slots
1581            .iter()
1582            .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
1583            .map(|(print_id, _)| *print_id)
1584            .collect();
1585        let over = slots.len().saturating_sub(HELD_INDEXES);
1586        for print_id in ready.into_iter().take(over) {
1587            slots.remove(&print_id);
1588        }
1589    }
1590}
1591
1592impl crate::supervisor::Supervisor {
1593    /// What the slicer planned at the job's current file position, building
1594    /// the print's index first when this supervisor has none for it.
1595    ///
1596    /// Nothing when the print is over, the job is not this print's file, the
1597    /// job reports no position, or the file could not be read — a read that
1598    /// failed builds nothing, so the next one tries again.
1599    ///
1600    /// # Errors
1601    ///
1602    /// The store's own error when the print's actions could not be read, as
1603    /// every other store read of the context answers it.
1604    pub(crate) async fn slicer_plan(
1605        &self,
1606        print: &crate::records::PrintRecord,
1607        job: Option<&printobserver_printer_api::JobSnapshot>,
1608        interventions: &[crate::records::Intervention],
1609    ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
1610        let Some((position, file)) = job
1611            .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
1612            .filter(|(_, file)| {
1613                print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
1614            })
1615        else {
1616            return Ok(None);
1617        };
1618        let Some(index) = self.index_of(print.id, file).await else {
1619            return Ok(None);
1620        };
1621        let (flow, fan) = self
1622            .changes_since(print.id, &index, position, interventions)
1623            .await?;
1624        let mut plan = index.plan_with(position, flow, fan);
1625        plan.rise = self.rise_of(print.id, &index, position).await?;
1626        if plan.rise.is_none() {
1627            plan.unknown.push(PlanFact::Rise);
1628            plan.unknown.sort_unstable();
1629        }
1630        Ok(Some(plan))
1631    }
1632
1633    /// How far the plan has risen since the newest frame at least
1634    /// [`RISE_WINDOW_S`] old that was seen — a periodic observation's, when it
1635    /// carries a position, or a look's — and where the plan had the top then.
1636    async fn rise_of(
1637        &self,
1638        print_id: PrintId,
1639        index: &GcodeIndex,
1640        position: i64,
1641    ) -> Result<Option<Rise>, crate::error::CoreError> {
1642        use printobserver_types::EventPayload as _;
1643
1644        use crate::kinds::PeriodicObservationPayload;
1645
1646        let now = self.clock().now();
1647        let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
1648            return Ok(None);
1649        };
1650        let events = self
1651            .stores()
1652            .events
1653            .history(crate::store::HistoryQuery {
1654                print_id,
1655                kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
1656                    .into_iter()
1657                    .collect(),
1658                since: None,
1659                until: Some(until),
1660                limit: Some(1),
1661            })
1662            .await?;
1663        let observed = events.first().and_then(|event| {
1664            let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
1665            let earlier = observed.job?.file_position_bytes?;
1666            Some((
1667                observed.frame_captured_at.unwrap_or(event.received_at),
1668                earlier,
1669            ))
1670        });
1671        let looked = self.gcode_indexes().newest_look_until(print_id, until);
1672        let newest = match (observed, looked) {
1673            (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
1674                looked
1675            } else {
1676                observed
1677            }),
1678            (observed, looked) => observed.or(looked),
1679        };
1680        Ok(newest.and_then(|(since, earlier)| {
1681            Some(Rise {
1682                since,
1683                mm: index.height_and_rise_since(earlier, position)?,
1684            })
1685        }))
1686    }
1687
1688    /// One print's index, built from its file when there is none yet.
1689    async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
1690        // A name no file could carry is no file to read.
1691        let file_name = printobserver_types::FileName::new(file).ok()?;
1692        let claim = match self.gcode_indexes().claim(print_id).await {
1693            Claimed::Ready(index) => return Some(index),
1694            Claimed::Build(claim) => claim,
1695        };
1696        let mut builder = IndexBuilder::new();
1697        self.read_gcode(file_name.clone(), &mut builder)
1698            .await
1699            .ok()?;
1700        let index = claim.finish(builder.finish());
1701        self.gcode_indexes().trim(print_id);
1702        if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
1703            file_name,
1704            bytes: index.bytes(),
1705            layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
1706        }) {
1707            // The index is built whether or not the store takes the record of
1708            // it, and a check goes on without it.
1709            let _ = self.append_system_event(print_id, body).await;
1710        }
1711        Some(index)
1712    }
1713
1714    /// The flow factor and the fan speed the latest change made through this
1715    /// program set, each when it was made after the file last set the same
1716    /// thing and still stands.
1717    ///
1718    /// A change is placed against the file by the position the print had last
1719    /// been read to have reached when it was made, at the file's start when no
1720    /// position had been read yet; a change whose bounded intervention has
1721    /// since expired stands no more.
1722    async fn changes_since(
1723        &self,
1724        print_id: PrintId,
1725        index: &GcodeIndex,
1726        position: i64,
1727        interventions: &[crate::records::Intervention],
1728    ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
1729        use printobserver_types::EventPayload as _;
1730
1731        use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
1732        use crate::records::PrintAction;
1733
1734        let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
1735            .iter()
1736            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
1737            .collect();
1738        let events = self
1739            .stores()
1740            .events
1741            .history(crate::store::HistoryQuery {
1742                print_id,
1743                kinds,
1744                since: None,
1745                until: None,
1746                limit: Some(crate::store::MAX_HISTORY_LIMIT),
1747            })
1748            .await?;
1749        let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
1750            .iter()
1751            .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
1752            .filter_map(Result::ok)
1753            .map(|payload| (payload.action_id, payload.action))
1754            .collect();
1755        let mut flow = None;
1756        let mut fan = None;
1757        // Newest first, so the first change of each kind is the latest.
1758        for executed in events
1759            .iter()
1760            .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
1761            .filter_map(Result::ok)
1762        {
1763            let standing = executed
1764                .intervention_id
1765                .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
1766            // Where in the file the change was made; one made before any
1767            // position was known is placed at the file's start.
1768            let made = executed
1769                .file_position_bytes
1770                .and_then(|made| u64::try_from(made).ok())
1771                .unwrap_or(0);
1772            let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
1773            match requested.get(&executed.action_id) {
1774                Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
1775                    flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
1776                }
1777                Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
1778                    fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
1779                }
1780                _ => {}
1781            }
1782        }
1783        Ok((flow.flatten(), fan.flatten()))
1784    }
1785}
1786
1787#[cfg(test)]
1788mod tests {
1789    use super::{GcodeIndexes, HELD_INDEXES, RISE_WINDOW_S};
1790    use printobserver_types::{PrintId, Timestamp};
1791
1792    /// An instant some seconds after another.
1793    fn after(start: Timestamp, seconds: i64) -> Timestamp {
1794        start.plus_seconds(seconds).expect("an instant")
1795    }
1796
1797    /// What is remembered of one print's looks, oldest first.
1798    fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
1799        indexes
1800            .looked
1801            .lock()
1802            .expect("the looks are held")
1803            .get(&print_id)
1804            .cloned()
1805            .unwrap_or_default()
1806    }
1807
1808    /// Of the looks already half an hour old, only the newest is kept: it is
1809    /// the one a rise is measured from until a newer look ages.
1810    #[test]
1811    fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
1812        let indexes = GcodeIndexes::default();
1813        let print = PrintId::new();
1814        let start = Timestamp::now();
1815        indexes.note_look(print, start, 10, start);
1816        indexes.note_look(print, after(start, 60), 20, after(start, 60));
1817        let now = after(start, 60 + RISE_WINDOW_S + 30);
1818        indexes.note_look(print, now, 30, now);
1819
1820        assert_eq!(
1821            held(&indexes, print),
1822            vec![(after(start, 60), 20), (now, 30)]
1823        );
1824        assert_eq!(
1825            indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
1826            Some((after(start, 60), 20))
1827        );
1828        assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
1829    }
1830
1831    /// Past as many prints as indexes are held, the looks of the oldest print
1832    /// are let go first.
1833    #[test]
1834    fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
1835        let indexes = GcodeIndexes::default();
1836        let now = Timestamp::now();
1837        let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
1838        prints.sort_unstable();
1839        for print in &prints {
1840            indexes.note_look(*print, now, 1, now);
1841        }
1842
1843        assert!(held(&indexes, prints[0]).is_empty());
1844        for print in &prints[1..] {
1845            assert_eq!(held(&indexes, *print), vec![(now, 1)]);
1846        }
1847    }
1848}