printobserver-panels 0.20.0

Camera calibration, drift and alignment checks, and the check image's panels, for printobserver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
//! Whether the camera is still aligned with its calibration, judged on one
//! frame of the empty build sheet, before anything is printed.
//!
//! Two gates answer it, and `aligned` needs both.
//!
//! - **The landmarks** say whether the camera moved: the calibration's own
//!   landmarks, found as every check finds them ([`crate::found_landmarks`]).
//!   Two or more visible beyond the calibration's `drift_tolerance_px` mean the
//!   camera moved, whatever the sheet says; fewer than two visible cannot say.
//! - **The sheet** says whether the projection and the bed height the caller
//!   read back still put the sheet where it is. Every sample of the sheet's
//!   outline ([`SheetOutline`]) is projected at that height and searched for
//!   only within [`SHEET_TOLERANCE_PX`] of where it lands, along its outward
//!   normal, for an edge light inside and dark outside; the sheet's hole is
//!   searched for as a dark blob just as near. A translation is fitted to what
//!   is found, with Huber weights.
//!
//! The band is deliberately no wider than the tolerance, so the sheet alone
//! cannot see a camera moved further than it: it finds nothing, or a nearby
//! edge. Measured on the 2026-11-28 empty-sheet frames, the sheet alone passed
//! 9 of 14 copies shifted 20 px and all 14 rotated 0.5°, and the two gates
//! together passed none of them while passing every frame as captured, at bed
//! heights 2 to 150 mm. A camera that has clearly moved is therefore answered
//! as moved before the sheet is asked, so a frame on which the sheet cannot be
//! found is still sent to a calibration when its landmarks show the move.
//!
//! The fit cannot find the bed's height: the outline moves only 1.9 to 3.6 px
//! per millimetre of it, so a sheet reseated 1–2 mm is worth several
//! millimetres, and a height is caught wrong only when it is about 10 mm off.
//! It is the caller's, read back from the printer while idle.

use std::sync::OnceLock;

use image::{GrayImage, Rgb, RgbImage};
use imageproc::drawing::{draw_cross_mut, draw_hollow_rect_mut};
use imageproc::rect::Rect;
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};

use crate::calibration::{CameraCalibration, Projector};
use crate::compose::decode;
use crate::drift::check_frame;
use crate::error::ComposeError;
use crate::view::{FoundLandmark, ReferenceLandmark, ViewCorrection, found_landmarks};

/// How far from the calibration's projection the sheet is searched for, and
/// the largest translation an aligned camera may need, in pixels.
pub const SHEET_TOLERANCE_PX: f64 = 10.0;

/// The largest RMS distance, in pixels, of the found edges from the
/// translated outline at which the fit is trusted. The worst frame measured
/// as captured, the smooth sheet at bed Z 150, leaves 4.68 px of the
/// calibration's own error above the heights it was fitted over.
pub const MAX_RESIDUAL_PX: f64 = 5.0;

/// The least share of the outline samples in view that must be found.
pub const MIN_SUPPORT: f64 = 0.6;

/// Below this share found, no sheet is in view at all.
pub const NO_SHEET_BELOW: f64 = 0.25;

/// How many edges must each show [`MIN_SAMPLES_PER_EDGE`] samples.
pub const MIN_EDGES_SEEN: usize = 3;

/// How many samples an edge needs, in view or found, to count.
pub const MIN_SAMPLES_PER_EDGE: usize = 6;

/// The least edge strength, in grey levels per pixel, that counts as an edge.
const EDGE_MIN_STRENGTH: f64 = 2.0;

/// How far inside the frame's border a sample must project to be in view.
const IN_VIEW_MARGIN_PX: f64 = 20.0;

/// The blur the frame's grey is read through before its gradient.
const BLUR_SIGMA: f64 = 2.0;

/// The spacing of the offsets an edge is searched at, in pixels.
const SEARCH_STEP_PX: f64 = 0.5;

/// How far either side along the edge each sample is averaged over.
const ALONG_EDGE_PX: f64 = 3.0;

/// A residual beyond which a Huber weight starts to fall, in pixels.
const HUBER_PX: f64 = 1.5;

/// How much darker than its neighbourhood the hole must be, in grey levels.
const HOLE_DARKER_BY: f64 = 25.0;

/// The fewest pixels the hole's blob may hold.
const HOLE_MIN_AREA: usize = 20;

/// One edge of a sheet: a straight line in bed millimetres at the sheet's
/// surface, its outward normal, and where along it the real edge lies.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct SheetEdge {
    /// Which edge, as the camera's bed frame names it.
    pub name: String,
    /// Where the line starts.
    pub from_mm: [f64; 2],
    /// Where it ends.
    pub to_mm: [f64; 2],
    /// The unit normal pointing off the sheet.
    pub outward: [f64; 2],
    /// `[t, across]`: at `t` mm along the line, how far outward of it the
    /// real edge lies. Rounded corners, notches, pin cut-outs and the
    /// label's edge are left out.
    pub profile_t_across_mm: Vec<[f64; 2]>,
}

/// One build sheet's outline and its hole, in bed millimetres at its surface.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
pub struct SheetOutline {
    /// The sheet id, as the server's sheet table names it.
    pub sheet: String,
    /// Where the geometry came from.
    pub source: String,
    /// The plane it lies in.
    pub plane: String,
    /// Its four edges.
    pub edges: Vec<SheetEdge>,
    /// The centre of its round hole, when it has one.
    pub hole_mm: Option<[f64; 2]>,
}

/// The sheets this crate carries an outline of: the two PEI sheets of the
/// CORE One, back-projected through its 2026-11-27 calibration, since no
/// dimensioned drawing of them is published.
const COMMITTED: [&str; 2] = [
    include_str!("../sheets/core-one-smooth-pei.json"),
    include_str!("../sheets/core-one-textured-pei.json"),
];

impl SheetOutline {
    /// The committed outline of one sheet, by its id; nothing for a sheet this
    /// crate carries no outline of.
    #[must_use]
    pub fn committed(sheet: &str) -> Option<&'static Self> {
        static PARSED: OnceLock<Vec<SheetOutline>> = OnceLock::new();
        PARSED
            .get_or_init(|| {
                COMMITTED
                    .iter()
                    .filter_map(|text| printobserver_types::serde_json::from_str(text).ok())
                    .collect()
            })
            .iter()
            .find(|outline| outline.sheet == sheet)
    }

    /// Every sheet id this crate carries an outline of.
    #[must_use]
    pub fn committed_sheets() -> Vec<&'static str> {
        ["smooth-pei", "textured-pei"]
            .into_iter()
            .filter(|sheet| Self::committed(sheet).is_some())
            .collect()
    }
}

/// Why a frame could not show whether the camera is aligned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum UnjudgeableCause {
    /// Too few of the outline's samples project into the frame.
    TooLittleSheetInView,
    /// Almost none of the outline is found: no sheet, or no picture.
    NoSheetFound,
    /// Too little of the outline is found, or on too few edges.
    SheetOccluded,
    /// Fewer than two of the calibration's landmarks are found.
    LandmarksHidden,
    /// The found edges disagree with any one translation of the outline.
    FitInconsistent,
}

impl UnjudgeableCause {
    /// The cause as a sentence's clause.
    #[must_use]
    pub const fn said(self) -> &'static str {
        match self {
            Self::TooLittleSheetInView => "too little of the sheet is in the camera's view",
            Self::NoSheetFound => "no sheet was found in the frame",
            Self::SheetOccluded => "too much of the sheet's outline is hidden",
            Self::LandmarksHidden => {
                "fewer than two of the calibration's landmarks are found, so whether the camera moved cannot be told"
            }
            Self::FitInconsistent => "the sheet's edges fit no one shift of its outline",
        }
    }
}

/// What the two gates found of one frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SheetVerdict {
    /// Both gates pass.
    Aligned,
    /// The landmarks show the camera moved, or the sheet is shifted beyond
    /// the tolerance.
    NotAligned,
    /// The frame cannot show it.
    Unjudgeable(UnjudgeableCause),
}

/// One judgement of the camera on an empty sheet.
#[derive(Debug, Clone, PartialEq)]
pub struct SheetFit {
    /// What it came to.
    pub verdict: SheetVerdict,
    /// The fitted translation, `[dx, dy]` pixels; nothing when the sheet could
    /// not be fitted.
    pub shift_px: Option<[f64; 2]>,
    /// The RMS distance of the found edges from the translated outline;
    /// nothing when the sheet could not be fitted.
    pub residual_px: Option<f64>,
    /// The share of the in-view samples found.
    pub support: f64,
    /// How many edges showed enough found samples.
    pub edges_seen: usize,
    /// How many visible landmarks lie beyond the drift tolerance.
    pub landmarks_moved: usize,
    /// How many landmarks are visible.
    pub landmarks_visible: usize,
    /// Whether the sheet's hole was found.
    pub hole_found: bool,
    /// The correction an aligned frame puts in force: its translation, with
    /// the landmarks found on this frame as its reference.
    pub correction: Option<ViewCorrection>,
    /// The frame with the projected outline, the fitted one and the found
    /// landmarks drawn, as a JPEG.
    pub drawn_jpeg: Vec<u8>,
}

impl SheetFit {
    /// The fitted translation's length.
    #[must_use]
    pub fn offset_px(&self) -> Option<f64> {
        self.shift_px.map(|[dx, dy]| dx.hypot(dy))
    }
}

/// What the camera check is given.
#[derive(Debug, Clone, Copy)]
pub struct SheetInputs<'a> {
    /// The frame.
    pub frame_jpeg: &'a [u8],
    /// The snapshot URL it came from.
    pub camera_snapshot_url: &'a str,
    /// The printer's calibration.
    pub calibration: &'a CameraCalibration,
    /// The sheet on the bed.
    pub sheet: &'a SheetOutline,
    /// The bed's height as the printer read it back, in millimetres.
    pub bed_z_mm: f64,
}

/// Judge whether the camera is still aligned with its calibration on one frame
/// of the empty sheet.
///
/// # Errors
///
/// [`ComposeError::Undecodable`] for a frame that is no JPEG,
/// [`ComposeError::FrameMismatch`] for one of another size or stream than the
/// calibration's, and [`ComposeError::Encode`] when the drawn frame cannot be
/// encoded.
pub fn fit_sheet(inputs: &SheetInputs<'_>) -> Result<SheetFit, ComposeError> {
    let frame = decode(inputs.frame_jpeg)?;
    check_frame(
        inputs.calibration,
        [frame.width(), frame.height()],
        inputs.camera_snapshot_url,
    )?;
    let grey = image::imageops::grayscale(&frame);
    let landmarks = found_landmarks(inputs.calibration, &grey);
    let gradients = Gradients::of(&grey);
    let samples = Samples::projected(
        &inputs.calibration.projector(),
        inputs.sheet,
        inputs.bed_z_mm,
        [frame.width(), frame.height()],
    );
    let measured = measure(&gradients, &samples);
    let visible = landmarks.iter().filter(|found| found.visible()).count();
    let moved = landmarks
        .iter()
        .filter(|found| {
            found.visible() && found.distance_px() > inputs.calibration.drift_tolerance_px
        })
        .count();
    let verdict = ruled(&measured, visible, moved);
    let correction = (verdict == SheetVerdict::Aligned)
        .then_some(measured.shift)
        .flatten()
        .map(|shift| ViewCorrection::translation(shift, reference(&landmarks)));
    let drawn_jpeg = drawn(frame, &samples, &measured, &landmarks, inputs.calibration)?;
    Ok(SheetFit {
        verdict,
        shift_px: measured.shift,
        residual_px: measured.residual,
        support: measured.support,
        edges_seen: measured.edges_seen,
        landmarks_moved: moved,
        landmarks_visible: visible,
        hole_found: measured.hole.is_some(),
        correction,
        drawn_jpeg,
    })
}

/// The highest bed height, in millimetres, [`calibrated_outline`] looks for
/// the sheet at: no printer this crate carries a sheet for lowers it further.
const OUTLINE_SEARCH_TOP_MM: u32 = 220;

/// The step between the bed heights [`calibrated_outline`] tries, in
/// millimetres: at most 3.6 px of the outline's move per millimetre, so every
/// height lies within [`SHEET_TOLERANCE_PX`] of one tried.
const OUTLINE_SEARCH_STEP_MM: u32 = 2;

/// Where the sheet's outline lies on a frame of a calibration's own size and
/// stream, in frame pixels, when the frame shows it: the committed sheet and
/// bed height whose projection the frame's edges support best, shifted by the
/// translation fitted to them. Nothing when the frame is not the
/// calibration's, when its landmarks show the camera moved, or when no sheet
/// and height is fitted by [`MIN_SUPPORT`] of its samples within
/// [`MAX_RESIDUAL_PX`].
///
/// A look at the printer names neither the sheet nor the bed's height, so
/// both are searched for; the height is found only roughly, which is all a
/// close-up cut around the outline needs.
pub(crate) fn calibrated_outline(
    frame: &RgbImage,
    camera_snapshot_url: &str,
    calibration: &CameraCalibration,
) -> Option<Vec<[f64; 2]>> {
    let size = [frame.width(), frame.height()];
    check_frame(calibration, size, camera_snapshot_url).ok()?;
    let grey = image::imageops::grayscale(frame);
    let moved = found_landmarks(calibration, &grey)
        .iter()
        .filter(|found| found.visible() && found.distance_px() > calibration.drift_tolerance_px)
        .count();
    if moved >= 2 {
        return None;
    }
    let gradients = Gradients::of(&grey);
    let projector = calibration.projector();
    let mut best: Option<(f64, f64, &SheetOutline, f64, [f64; 2])> = None;
    for sheet in SheetOutline::committed_sheets() {
        let Some(outline) = SheetOutline::committed(sheet) else {
            continue;
        };
        for step in 0..=OUTLINE_SEARCH_TOP_MM / OUTLINE_SEARCH_STEP_MM {
            let bed_z_mm = f64::from(step * OUTLINE_SEARCH_STEP_MM);
            let samples = Samples::projected(&projector, outline, bed_z_mm, size);
            let measured = measure(&gradients, &samples);
            let (Some(shift), Some(residual)) = (measured.shift, measured.residual) else {
                continue;
            };
            if measured.unfitted.is_some() || residual > MAX_RESIDUAL_PX {
                continue;
            }
            if best.is_none_or(|(support, least, ..)| {
                measured
                    .support
                    .total_cmp(&support)
                    .then(least.total_cmp(&residual))
                    .is_gt()
            }) {
                best = Some((measured.support, residual, outline, bed_z_mm, shift));
            }
        }
    }
    let (_, _, outline, bed_z_mm, [dx, dy]) = best?;
    Some(
        outline_points_mm(outline)
            .into_iter()
            .filter_map(|[x, y]| projector.pixel([x, y, -bed_z_mm]))
            .map(|[u, v]| [u + dx, v + dy])
            .collect(),
    )
}

/// Every point of a sheet's outline the committed geometry places, in bed
/// millimetres: each edge's two ends and each point of its profile.
fn outline_points_mm(sheet: &SheetOutline) -> Vec<[f64; 2]> {
    let mut points = Vec::new();
    for edge in &sheet.edges {
        let (dx, dy) = (
            edge.to_mm[0] - edge.from_mm[0],
            edge.to_mm[1] - edge.from_mm[1],
        );
        let length = dx.hypot(dy);
        if length <= 0.0 {
            continue;
        }
        let direction = [dx / length, dy / length];
        points.push(edge.from_mm);
        points.extend(edge.profile_t_across_mm.iter().map(|[t, across]| {
            [
                edge.from_mm[0] + t * direction[0] + across * edge.outward[0],
                edge.from_mm[1] + t * direction[1] + across * edge.outward[1],
            ]
        }));
        points.push(edge.to_mm);
    }
    points
}

/// Which verdict the two gates come to, the camera's own evidence first: two
/// or more moved landmarks are a moved camera whatever the sheet found.
fn ruled(measured: &Measured, visible: usize, moved: usize) -> SheetVerdict {
    if moved >= 2 {
        return SheetVerdict::NotAligned;
    }
    if let Some(cause) = measured.unfitted {
        return SheetVerdict::Unjudgeable(cause);
    }
    if visible < 2 {
        return SheetVerdict::Unjudgeable(UnjudgeableCause::LandmarksHidden);
    }
    if measured
        .residual
        .is_some_and(|residual| residual > MAX_RESIDUAL_PX)
    {
        return SheetVerdict::Unjudgeable(UnjudgeableCause::FitInconsistent);
    }
    if measured
        .shift
        .is_some_and(|[dx, dy]| dx.hypot(dy) > SHEET_TOLERANCE_PX)
    {
        return SheetVerdict::NotAligned;
    }
    SheetVerdict::Aligned
}

/// The visible landmarks of a frame, as a correction's reference.
fn reference(landmarks: &[FoundLandmark]) -> Vec<ReferenceLandmark> {
    landmarks
        .iter()
        .filter(|found| found.visible())
        .map(|found| ReferenceLandmark {
            name: found.name.clone(),
            offset_px: found.located.offset_px,
            score: f64::from(found.located.score),
        })
        .collect()
}

/// A frame's blurred grey and its gradient, in grey levels per pixel.
struct Gradients {
    /// Its width.
    width: usize,
    /// Its height.
    height: usize,
    /// The blurred grey, row by row.
    grey: Vec<f64>,
    /// The gradient along X.
    gx: Vec<f64>,
    /// The gradient along Y.
    gy: Vec<f64>,
}

impl Gradients {
    /// A grey frame's, blurred by [`BLUR_SIGMA`], with the 3×3 Sobel
    /// gradient scaled to grey levels per pixel.
    fn of(frame: &GrayImage) -> Self {
        let (width, height) = (frame.width() as usize, frame.height() as usize);
        let raw: Vec<f64> = frame
            .as_raw()
            .iter()
            .map(|value| f64::from(*value))
            .collect();
        let grey = blurred(&raw, width, height, BLUR_SIGMA);
        let mut gx = vec![0.0; width * height];
        let mut gy = vec![0.0; width * height];
        let at = |x: usize, y: usize| grey[y * width + x];
        for y in 0..height {
            let (up, down) = (y.saturating_sub(1), (y + 1).min(height - 1));
            for x in 0..width {
                let (left, right) = (x.saturating_sub(1), (x + 1).min(width - 1));
                gx[y * width + x] = ((at(right, up) - at(left, up))
                    + 2.0 * (at(right, y) - at(left, y))
                    + (at(right, down) - at(left, down)))
                    / 8.0;
                gy[y * width + x] = ((at(left, down) - at(left, up))
                    + 2.0 * (at(x, down) - at(x, up))
                    + (at(right, down) - at(right, up)))
                    / 8.0;
            }
        }
        Self {
            width,
            height,
            grey,
            gx,
            gy,
        }
    }

    /// One plane's value at a point, bilinearly, its nearest edge pixel
    /// outside the frame.
    fn sample(&self, plane: &[f64], [x, y]: [f64; 2]) -> f64 {
        let most = |size: usize| f64::from(u32::try_from(size - 1).unwrap_or(0));
        let (x, y) = (
            x.clamp(0.0, most(self.width)),
            y.clamp(0.0, most(self.height)),
        );
        let (x0, y0) = (x.floor(), y.floor());
        let (fx, fy) = (x - x0, y - y0);
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "clamped into the frame above"
        )]
        let (x0, y0) = (x0 as usize, y0 as usize);
        let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1));
        let value = |x: usize, y: usize| plane[y * self.width + x];
        (value(x0, y0) * (1.0 - fx) + value(x1, y0) * fx) * (1.0 - fy)
            + (value(x0, y1) * (1.0 - fx) + value(x1, y1) * fx) * fy
    }

    /// The grey's derivative along `normal` at a point.
    fn along(&self, point: [f64; 2], normal: [f64; 2]) -> f64 {
        self.sample(&self.gx, point) * normal[0] + self.sample(&self.gy, point) * normal[1]
    }
}

/// A separable Gaussian blur of a grey plane, its border replicated.
pub(crate) fn blurred(plane: &[f64], width: usize, height: usize, sigma: f64) -> Vec<f64> {
    let radius = (sigma * 4.0).ceil();
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "a few times a small sigma"
    )]
    let reach = radius as usize;
    let weights: Vec<f64> = (0..=2 * reach)
        .map(|k| {
            let d = f64::from(u32::try_from(k).unwrap_or(0)) - radius;
            (-(d * d) / (2.0 * sigma * sigma)).exp()
        })
        .collect();
    let total: f64 = weights.iter().sum();
    let weights: Vec<f64> = weights.iter().map(|weight| weight / total).collect();
    let mut across = vec![0.0; plane.len()];
    for y in 0..height {
        let row = &plane[y * width..(y + 1) * width];
        for x in 0..width {
            across[y * width + x] = weights
                .iter()
                .enumerate()
                .map(|(k, weight)| {
                    let at = (x + k).saturating_sub(reach).min(width - 1);
                    row[at] * weight
                })
                .sum();
        }
    }
    let mut out = vec![0.0; plane.len()];
    for y in 0..height {
        for (k, weight) in weights.iter().enumerate() {
            let from = (y + k).saturating_sub(reach).min(height - 1);
            let source = &across[from * width..(from + 1) * width];
            let target = &mut out[y * width..(y + 1) * width];
            for (value, add) in target.iter_mut().zip(source) {
                *value += add * weight;
            }
        }
    }
    out
}

/// The outline's samples in view at one bed height: each point, its outward
/// normal in the image, and the edge it is of.
struct Samples {
    /// The projected points.
    points: Vec<[f64; 2]>,
    /// Their outward normals, unit length.
    normals: Vec<[f64; 2]>,
    /// Which edge each is of.
    edge: Vec<usize>,
    /// How many edges the outline has.
    edges: usize,
    /// The hole's projection, when it has one in view.
    hole: Option<[f64; 2]>,
}

impl Samples {
    /// The samples of `sheet` projected with the bed at `bed_z_mm`, those
    /// within [`IN_VIEW_MARGIN_PX`] of the frame's border left out.
    fn projected(
        projector: &Projector,
        sheet: &SheetOutline,
        bed_z_mm: f64,
        size: [u32; 2],
    ) -> Self {
        let [w, h] = size.map(f64::from);
        let in_view = |[u, v]: [f64; 2]| {
            u > IN_VIEW_MARGIN_PX
                && u < w - IN_VIEW_MARGIN_PX
                && v > IN_VIEW_MARGIN_PX
                && v < h - IN_VIEW_MARGIN_PX
        };
        let mut samples = Self {
            points: Vec::new(),
            normals: Vec::new(),
            edge: Vec::new(),
            edges: sheet.edges.len(),
            hole: sheet
                .hole_mm
                .and_then(|[x, y]| projector.pixel([x, y, -bed_z_mm])),
        };
        for (index, edge) in sheet.edges.iter().enumerate() {
            let (dx, dy) = (
                edge.to_mm[0] - edge.from_mm[0],
                edge.to_mm[1] - edge.from_mm[1],
            );
            let length = dx.hypot(dy);
            if length <= 0.0 {
                continue;
            }
            let direction = [dx / length, dy / length];
            for [t, across] in &edge.profile_t_across_mm {
                let bed = [
                    edge.from_mm[0] + t * direction[0] + across * edge.outward[0],
                    edge.from_mm[1] + t * direction[1] + across * edge.outward[1],
                ];
                let (Some(point), Some(outer)) = (
                    projector.pixel([bed[0], bed[1], -bed_z_mm]),
                    projector.pixel([
                        bed[0] + edge.outward[0],
                        bed[1] + edge.outward[1],
                        -bed_z_mm,
                    ]),
                ) else {
                    continue;
                };
                let normal = [outer[0] - point[0], outer[1] - point[1]];
                let norm = normal[0].hypot(normal[1]);
                if !in_view(point) || norm <= 1e-9 {
                    continue;
                }
                samples.points.push(point);
                samples.normals.push([normal[0] / norm, normal[1] / norm]);
                samples.edge.push(index);
            }
        }
        samples
    }

    /// How many edges have at least [`MIN_SAMPLES_PER_EDGE`] of the samples
    /// `kept` marks.
    fn edges_with(&self, kept: &[bool]) -> usize {
        (0..self.edges)
            .filter(|edge| {
                self.edge
                    .iter()
                    .zip(kept)
                    .filter(|(of, kept)| **of == *edge && **kept)
                    .count()
                    >= MIN_SAMPLES_PER_EDGE
            })
            .count()
    }
}

/// What the sheet gate measured.
struct Measured {
    /// Why the sheet could not be fitted at all.
    unfitted: Option<UnjudgeableCause>,
    /// The share of in-view samples found.
    support: f64,
    /// How many edges showed enough found samples.
    edges_seen: usize,
    /// Each in-view sample's found offset along its normal.
    offsets: Vec<Option<f64>>,
    /// Where the hole was found.
    hole: Option<[f64; 2]>,
    /// The fitted translation.
    shift: Option<[f64; 2]>,
    /// Its residual.
    residual: Option<f64>,
}

/// Search the band, then fit the translation to what it found.
fn measure(gradients: &Gradients, samples: &Samples) -> Measured {
    let mut measured = Measured {
        unfitted: None,
        support: 0.0,
        edges_seen: 0,
        offsets: Vec::new(),
        hole: None,
        shift: None,
        residual: None,
    };
    let all = vec![true; samples.points.len()];
    if samples.points.len() < MIN_EDGES_SEEN * MIN_SAMPLES_PER_EDGE
        || samples.edges_with(&all) < MIN_EDGES_SEEN
    {
        measured.unfitted = Some(UnjudgeableCause::TooLittleSheetInView);
        measured.edges_seen = samples.edges_with(&all);
        return measured;
    }
    measured.offsets = samples
        .points
        .iter()
        .zip(&samples.normals)
        .map(|(point, normal)| edge_offset(gradients, *point, *normal, SHEET_TOLERANCE_PX))
        .collect();
    let found: Vec<bool> = measured.offsets.iter().map(Option::is_some).collect();
    let count = found.iter().filter(|found| **found).count();
    measured.support = ratio(count, found.len());
    measured.edges_seen = samples.edges_with(&found);
    if measured.support < NO_SHEET_BELOW {
        measured.unfitted = Some(UnjudgeableCause::NoSheetFound);
        return measured;
    }
    if measured.support < MIN_SUPPORT || measured.edges_seen < MIN_EDGES_SEEN {
        measured.unfitted = Some(UnjudgeableCause::SheetOccluded);
        return measured;
    }
    let mut rows: Vec<([f64; 2], f64)> = samples
        .normals
        .iter()
        .zip(&measured.offsets)
        .filter_map(|(normal, offset)| offset.map(|offset| (*normal, offset)))
        .collect();
    let outline_rows = rows.len();
    measured.hole = samples
        .hole
        .and_then(|hole| dark_blob(gradients, hole, SHEET_TOLERANCE_PX).map(|at| (hole, at)))
        .map(|(hole, at)| {
            rows.push(([1.0, 0.0], at[0] - hole[0]));
            rows.push(([0.0, 1.0], at[1] - hole[1]));
            at
        });
    let (shift, residuals) = huber_translation(&rows);
    measured.shift = Some(shift);
    measured.residual = Some(rms_inliers(&residuals[..outline_rows]));
    measured
}

/// A count's share of a total.
fn ratio(count: usize, total: usize) -> f64 {
    let as_f64 = |n: usize| f64::from(u32::try_from(n).unwrap_or(u32::MAX));
    if total == 0 {
        0.0
    } else {
        as_f64(count) / as_f64(total)
    }
}

/// Along one sample's outward normal, within `window`, where the strongest
/// edge light inside and dark outside lies, averaged over
/// [`ALONG_EDGE_PX`] either side along the edge; nothing when none reaches
/// [`EDGE_MIN_STRENGTH`] or the strongest lies on the window's border.
fn edge_offset(
    gradients: &Gradients,
    point: [f64; 2],
    normal: [f64; 2],
    window: f64,
) -> Option<f64> {
    let tangent = [-normal[1], normal[0]];
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "a window of a few pixels"
    )]
    let steps = (2.0 * window / SEARCH_STEP_PX).round() as usize + 1;
    let profile: Vec<f64> = (0..steps)
        .map(|step| {
            let d = -window + SEARCH_STEP_PX * f64::from(u32::try_from(step).unwrap_or(0));
            let total: f64 = [-ALONG_EDGE_PX, 0.0, ALONG_EDGE_PX]
                .iter()
                .map(|t| {
                    gradients.along(
                        [
                            point[0] + d * normal[0] + t * tangent[0],
                            point[1] + d * normal[1] + t * tangent[1],
                        ],
                        normal,
                    )
                })
                .sum();
            -total / 3.0
        })
        .collect();
    let (best, strength) = profile
        .iter()
        .copied()
        .enumerate()
        .reduce(|best, next| if next.1 > best.1 { next } else { best })?;
    if best == 0 || best + 1 == steps || strength < EDGE_MIN_STRENGTH {
        return None;
    }
    let (left, right) = (profile[best - 1], profile[best + 1]);
    let curve = left - 2.0 * strength + right;
    let refined = if curve.abs() > 1e-9 {
        0.5 * SEARCH_STEP_PX * (left - right) / curve
    } else {
        0.0
    };
    Some(-window + SEARCH_STEP_PX * f64::from(u32::try_from(best).unwrap_or(0)) + refined)
}

/// The centroid of the largest dark blob within `window` of `guess`: pixels
/// [`HOLE_DARKER_BY`] below the neighbourhood's median grey, connected.
fn dark_blob(gradients: &Gradients, guess: [f64; 2], window: f64) -> Option<[f64; 2]> {
    #[expect(
        clippy::cast_possible_truncation,
        reason = "a projected point of a frame of a few thousand pixels"
    )]
    let (x, y) = (guess[0].round() as i64, guess[1].round() as i64);
    #[expect(
        clippy::cast_possible_truncation,
        reason = "a tolerance of a few pixels"
    )]
    let reach = window as i64 + 12;
    let (width, height) = (
        i64::try_from(gradients.width).ok()?,
        i64::try_from(gradients.height).ok()?,
    );
    if x - reach < 0 || y - reach < 0 || x + reach >= width || y + reach >= height {
        return None;
    }
    let side = usize::try_from(2 * reach + 1).ok()?;
    let value = |dx: usize, dy: usize| {
        let at = usize::try_from((y - reach) * width + x - reach).unwrap_or(0)
            + dy * gradients.width
            + dx;
        gradients.grey[at]
    };
    let mut values: Vec<f64> = (0..side * side)
        .map(|k| value(k % side, k / side))
        .collect();
    let mut sorted = values.clone();
    sorted.sort_by(f64::total_cmp);
    let median = sorted[sorted.len() / 2];
    for value in &mut values {
        *value = if *value < median - HOLE_DARKER_BY {
            1.0
        } else {
            0.0
        };
    }
    let mut seen = vec![false; side * side];
    let mut best: Option<(usize, [f64; 2])> = None;
    let reach_f = f64::from(u32::try_from(reach).unwrap_or(0));
    for start in 0..side * side {
        if values[start] < 0.5 || seen[start] {
            continue;
        }
        let mut stack = vec![start];
        seen[start] = true;
        let (mut area, mut sum) = (0_usize, [0.0, 0.0]);
        while let Some(at) = stack.pop() {
            area += 1;
            let (cx, cy) = (at % side, at / side);
            sum[0] += f64::from(u32::try_from(cx).unwrap_or(0));
            sum[1] += f64::from(u32::try_from(cy).unwrap_or(0));
            for (nx, ny) in [
                (cx.wrapping_sub(1), cy),
                (cx + 1, cy),
                (cx, cy.wrapping_sub(1)),
                (cx, cy + 1),
            ] {
                if nx < side && ny < side && values[ny * side + nx] > 0.5 && !seen[ny * side + nx] {
                    seen[ny * side + nx] = true;
                    stack.push(ny * side + nx);
                }
            }
        }
        let count = f64::from(u32::try_from(area).unwrap_or(u32::MAX));
        let centre = [sum[0] / count - reach_f, sum[1] / count - reach_f];
        if centre[0].hypot(centre[1]) <= window
            && area >= HOLE_MIN_AREA
            && best.is_none_or(|(most, _)| area > most)
        {
            best = Some((area, centre));
        }
    }
    let x_f = f64::from(i32::try_from(x).ok()?);
    let y_f = f64::from(i32::try_from(y).ok()?);
    best.map(|(_, centre)| [x_f + centre[0], y_f + centre[1]])
}

/// The translation `s` minimising `Σ ρ(n·s − d)` over rows `(n, d)` with a
/// Huber `ρ`, by reweighted least squares, and each row's residual.
fn huber_translation(rows: &[([f64; 2], f64)]) -> ([f64; 2], Vec<f64>) {
    let mut weights = vec![1.0; rows.len()];
    let mut shift = [0.0, 0.0];
    for _ in 0..10 {
        // The normal equations' matrix `[[xx, xy], [xy, yy]]` and right side.
        let (mut xx, mut xy, mut yy) = (0.0, 0.0, 0.0);
        let mut right = [0.0, 0.0];
        for ((normal, target), weight) in rows.iter().zip(&weights) {
            let squared = weight * weight;
            xx += squared * normal[0] * normal[0];
            xy += squared * normal[0] * normal[1];
            yy += squared * normal[1] * normal[1];
            right[0] += squared * normal[0] * target;
            right[1] += squared * normal[1] * target;
        }
        let determinant = xx * yy - xy * xy;
        if determinant.abs() < 1e-12 {
            break;
        }
        shift = [
            (yy * right[0] - xy * right[1]) / determinant,
            (xx * right[1] - xy * right[0]) / determinant,
        ];
        for ((normal, target), weight) in rows.iter().zip(weights.iter_mut()) {
            let residual = (target - (normal[0] * shift[0] + normal[1] * shift[1])).abs();
            *weight = if residual <= HUBER_PX {
                1.0
            } else {
                (HUBER_PX / residual.max(1e-9)).sqrt()
            };
        }
    }
    let residuals = rows
        .iter()
        .map(|(normal, target)| target - (normal[0] * shift[0] + normal[1] * shift[1]))
        .collect();
    (shift, residuals)
}

/// The RMS of the residuals within three robust deviations, and a pixel, of
/// zero: a few edges found on a fibre or a scratch do not count against it.
fn rms_inliers(residuals: &[f64]) -> f64 {
    if residuals.is_empty() {
        return 0.0;
    }
    let mut sizes: Vec<f64> = residuals.iter().map(|r| r.abs()).collect();
    sizes.sort_by(f64::total_cmp);
    let median = sizes[sizes.len() / 2];
    let bound = 3.0 * 1.4826 * median + 1.0;
    let inliers: Vec<f64> = residuals
        .iter()
        .copied()
        .filter(|r| r.abs() < bound)
        .collect();
    if inliers.is_empty() {
        return 0.0;
    }
    let count = f64::from(u32::try_from(inliers.len()).unwrap_or(u32::MAX));
    (inliers.iter().map(|r| r * r).sum::<f64>() / count).sqrt()
}

/// The frame with the outline where the calibration projects it in red, where
/// the fit puts it in green, the hole found in yellow, and each landmark
/// found in cyan, or in red when it lies beyond the drift tolerance.
fn drawn(
    mut frame: RgbImage,
    samples: &Samples,
    measured: &Measured,
    landmarks: &[FoundLandmark],
    calibration: &CameraCalibration,
) -> Result<Vec<u8>, ComposeError> {
    const RED: Rgb<u8> = Rgb([255, 40, 40]);
    const GREEN: Rgb<u8> = Rgb([40, 255, 40]);
    const YELLOW: Rgb<u8> = Rgb([255, 230, 0]);
    const CYAN: Rgb<u8> = Rgb([0, 230, 255]);
    #[expect(
        clippy::cast_possible_truncation,
        reason = "a pixel of a frame of a few thousand pixels"
    )]
    let pixel = |[x, y]: [f64; 2]| (x.round() as i32, y.round() as i32);
    for point in &samples.points {
        let (x, y) = pixel(*point);
        draw_cross_mut(&mut frame, RED, x, y);
    }
    if let Some(shift) = measured.shift {
        for point in &samples.points {
            let (x, y) = pixel([point[0] + shift[0], point[1] + shift[1]]);
            draw_cross_mut(&mut frame, GREEN, x, y);
        }
    }
    if let Some(hole) = measured.hole {
        let (x, y) = pixel(hole);
        draw_hollow_rect_mut(&mut frame, Rect::at(x - 6, y - 6).of_size(13, 13), YELLOW);
    }
    for (found, landmark) in landmarks.iter().zip(&calibration.landmarks) {
        if !found.visible() {
            continue;
        }
        let (x, y) = pixel([
            landmark.center_px[0] + found.located.offset_px[0],
            landmark.center_px[1] + found.located.offset_px[1],
        ]);
        let colour = if found.distance_px() > calibration.drift_tolerance_px {
            RED
        } else {
            CYAN
        };
        draw_hollow_rect_mut(&mut frame, Rect::at(x - 24, y - 24).of_size(49, 49), colour);
    }
    let mut jpeg = Vec::new();
    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
        .encode_image(&frame)
        .map_err(|error| ComposeError::Encode {
            detail: error.to_string(),
        })?;
    Ok(jpeg)
}

#[cfg(test)]
mod tests {
    use super::{SheetOutline, huber_translation, rms_inliers};

    #[test]
    fn both_committed_sheets_are_read_and_no_other_is_named() {
        assert_eq!(
            SheetOutline::committed_sheets(),
            ["smooth-pei", "textured-pei"]
        );
        for sheet in ["smooth-pei", "textured-pei"] {
            let outline = SheetOutline::committed(sheet).expect("committed");
            assert_eq!(outline.edges.len(), 4);
            assert!(outline.hole_mm.is_some());
            assert!(
                outline
                    .edges
                    .iter()
                    .all(|edge| edge.profile_t_across_mm.len() >= 6)
            );
        }
        assert!(SheetOutline::committed("satin-pei").is_none());
    }

    #[test]
    fn the_huber_fit_finds_a_known_shift_through_an_outlier() {
        let shift = [3.0, -2.0];
        let mut rows: Vec<([f64; 2], f64)> = [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.0, -1.0]]
            .iter()
            .cycle()
            .take(40)
            .map(|normal: &[f64; 2]| (*normal, normal[0] * shift[0] + normal[1] * shift[1]))
            .collect();
        rows.push(([1.0, 0.0], 40.0));
        let (found, residuals) = huber_translation(&rows);
        assert!(
            (found[0] - 3.0).abs() < 0.2 && (found[1] + 2.0).abs() < 0.2,
            "{found:?}"
        );
        assert!(rms_inliers(&residuals) < 0.5);
    }
}