BREP_kernel 0.16.0

A boundary representation (BREP) geometry kernel for building CAD applications.
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
use super::*;
use super::mass_profile;
use web_time::Instant;

/// The static facts a `mass.face` line carries beside the route: the
/// recognized carrier kind, the patch degrees and closed directions, and the
/// trim's size. Read only when `BREP_PROFILE_MASS_FACES` armed the lines.
fn face_line_meta(face: &FaceRecord) -> (&'static str, usize, usize, bool, bool, usize, usize) {
    // `kind_label` spells the general carrier with spaces; the profile line is
    // whitespace-tokenized, so collapse it to one word.
    let kind = match face.surface.analytic().map(|analytic| analytic.kind_label()) {
        Some("Surface of revolution") => "Revolution",
        Some(label) => label,
        None => "Fitted",
    };
    let (closed_u, closed_v) = face.surface.closed_directions().unwrap_or((false, false));
    let coedges = face
        .loops
        .iter()
        .map(|loop_record| loop_record.coedges.len())
        .sum();
    (
        kind,
        face.surface.degree_u,
        face.surface.degree_v,
        closed_u,
        closed_v,
        face.loops.len(),
        coedges,
    )
}

/// Emit one `mass.face` line for the face just integrated. `before` is the
/// counter snapshot taken ahead of its work and `started` the wall clock at
/// the same point; both are `None` unless the lines are armed.
fn emit_face_line(
    call: &str,
    shell: usize,
    face_index: usize,
    face: &FaceRecord,
    before: Option<super::profile::MassProfile>,
    started: Option<Instant>,
) {
    let (Some(before), Some(started)) = (before, started) else {
        return;
    };
    let wall_ms = started.elapsed().as_secs_f64() * 1_000.0;
    let (kind, degree_u, degree_v, closed_u, closed_v, loops, coedges) = face_line_meta(face);
    super::profile::emit_face(
        call, shell, face_index, kind, degree_u, degree_v, closed_u, closed_v, loops, coedges,
        before, wall_ms,
    );
}

pub fn solid_mass_properties(solid: &BrepSolid) -> Result<MassProperties, String> {
    let token = super::profile::begin("solid_mass_properties");
    let result = solid_mass_properties_cached(solid);
    super::profile::end(token);
    if result.is_ok() && sign_terms_oracle_enabled() && solid.kind == crate::BodyKind::Solid
        && !solid.shells.is_empty() && solid.shells.iter().all(|shell| !shell.faces.is_empty())
    {
        verify_solid_sign_terms(solid)?;
    }
    if let (Some(dump), Ok(properties)) = (super::profile::identity_dump(), result.as_ref()) {
        super::profile::emit_identity(
            dump,
            "solid_mass_properties",
            solid,
            &[
                ("volume_bits", properties.volume),
                ("area_bits", properties.surface_area),
            ],
        );
    }
    result
}

/// Validate the memo against the current geometry on EVERY read: topology
/// records are publicly editable, and copies may have been transformed or healed.
fn solid_mass_properties_cached(solid: &BrepSolid) -> Result<MassProperties, String> {
    let identity = face_set_identity(solid);
    if let Some((cached_identity, properties)) = solid.mass_properties_cache.entry.get() {
        if cached_identity == identity {
            if super::profile::mass_profile_enabled() {
                let measured = solid_mass_properties_inner(solid)?;
                assert_eq!(properties.volume.to_bits(), measured.volume.to_bits(),
                    "mass cache changed volume");
                assert_eq!(properties.surface_area.to_bits(), measured.surface_area.to_bits(),
                    "mass cache changed area");
                eprintln!("mass.cache hit faces={} verified=true", identity.faces);
            }
            return Ok(properties);
        }
    }
    // Never retain a failed computation, nor an old entry for modified geometry.
    solid.mass_properties_cache.entry.set(None);
    let properties = solid_mass_properties_inner(solid)?;
    solid.mass_properties_cache.entry.set(Some((identity, properties)));
    Ok(properties)
}

fn solid_mass_properties_inner(solid: &BrepSolid) -> Result<MassProperties, String> {
    let mut properties = MassProperties {
        surface_area: 0.0,
        volume: 0.0,
    };
    let mut volume_compensation = 0.0;
    let face_lines = super::profile::face_lines_enabled();
    for (shell_index, shell) in solid.shells.iter().enumerate() {
        if shell.faces.is_empty() {
            continue;
        }
        // Use the same local reference as the signed-volume orientation gate.
        // World-origin flux terms can dwarf a small translated solid's volume;
        // even tiny quadrature or boundary errors then dominate their sum.
        let reference = shell_volume_reference(shell)?;
        let kinds = [Integrand::Area, Integrand::VolumeAbout(reference)];
        for (face_index, face) in shell.faces.iter().enumerate() {
            mass_profile(|p| p.faces += 1);
            let line_before = face_lines.then(super::profile::snapshot);
            let line_started = face_lines.then(Instant::now);
            let gate_started = super::profile::profile_started();
            let (area, volume) = if let Some(values) = biperiodic_band_integral(face, &kinds)? {
                mass_profile(|p| {
                    p.route_biperiodic += 1;
                    p.gate_ms += super::profile::elapsed_ms(gate_started);
                });
                (values[0], values[1] / 3.0)
            } else if !is_affine(&face.surface)? && !is_untrimmed(face)? {
                mass_profile(|p| {
                    p.trimmed_faces += 1;
                    p.gate_ms += super::profile::elapsed_ms(gate_started);
                });
                // Preserve the shared cell decomposition and integration pass.
                let values = integrate_trimmed_multi(face, &kinds)?;
                (values[0], values[1] / 3.0)
            } else if is_affine(&face.surface)? {
                mass_profile(|p| {
                    p.route_affine += 1;
                    p.gate_ms += super::profile::elapsed_ms(gate_started);
                });
                // One parameter-space area and one planar metric for both
                // numbers, instead of `face_area` and
                // `face_volume_contribution_about` each walking the trim.
                affine_area_and_volume_about(face, reference)?
            } else {
                mass_profile(|p| {
                    p.route_untrimmed += 1;
                    p.gate_ms += super::profile::elapsed_ms(gate_started);
                });
                // One station sweep carrying both integrands, instead of one
                // sweep per integrand.
                let started = super::profile::profile_started();
                let values = integrate_untrimmed_multi(face, &kinds)?;
                mass_profile(|p| p.untrimmed_ms += super::profile::elapsed_ms(started));
                (values[0], values[1] / 3.0)
            };
            emit_face_line(
                "solid_mass_properties",
                shell_index,
                face_index,
                face,
                line_before,
                line_started,
            );
            properties.surface_area += area;
            let next = properties.volume + volume;
            if properties.volume.abs() >= volume.abs() {
                volume_compensation += (properties.volume - next) + volume;
            } else {
                volume_compensation += (volume - next) + properties.volume;
            }
            properties.volume = next;
        }
    }
    properties.volume += volume_compensation;
    Ok(properties)
}

/// Exact signed volume. A single nonempty shell shares its area/volume
/// measurement with subsequent property queries. Multiple shells retain the
/// original per-shell compensated sum: substituting the across-face sum can
/// change the last bits and an orientation gate must not change its answer.
pub fn solid_signed_volume(solid: &BrepSolid) -> Result<f64, String> {
    let token = super::profile::begin("solid_signed_volume");
    let result = if solid.shells.len() == 1 && !solid.shells[0].faces.is_empty() {
        match solid_mass_properties_cached(solid) {
            Ok(properties) => {
                if super::profile::mass_profile_enabled() {
                    let original = solid_signed_volume_uncached(solid)
                        .expect("shared mass measurement changed a signed-volume refusal");
                    assert_eq!(properties.volume.to_bits(), original.to_bits(),
                        "shared mass measurement changed signed volume");
                }
                Ok(properties.volume)
            }
            // Area computation must not introduce a new signed-volume refusal.
            Err(_) => solid_signed_volume_uncached(solid),
        }
    } else {
        solid_signed_volume_uncached(solid)
    };
    super::profile::end(token);
    if result.is_ok() && sign_terms_oracle_enabled() && solid.kind == crate::BodyKind::Solid {
        verify_solid_sign_terms(solid)?;
    }
    if let (Some(dump), Ok(volume)) = (super::profile::identity_dump(), result.as_ref()) {
        super::profile::emit_identity(dump, "solid_signed_volume", solid, &[("signed_bits", *volume)]);
    }
    result
}

/// The margin, as a fraction of the sum of the face contributions' magnitudes,
/// inside which [`solid_signed_volume_for_sign`] trusts no reading of its own
/// and integrates exactly. The skipped corrections are zero to rounding
/// (collinear control points, 1e-12 of the extent), so this is a very wide
/// safety margin, not a measured error.
const SIGN_READING_MARGIN: f64 = 1e-6;

/// [`solid_signed_volume_for_sign`] for a caller that compares the result with
/// `bar` and nothing else (the boolean assembly's closed tail, the shell's
/// orientation, the direct edit's inversion check — 2026-10-17): the memoised
/// sign reading, whose verdict against the bar is the exact integral's.
/// `BREP_SIGN_READERS_EXACT=1` restores the exact read at those call sites,
/// for an on/off census. Read once.
pub fn signed_volume_against(solid: &BrepSolid, bar: f64) -> Result<f64, String> {
    static EXACT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    if *EXACT.get_or_init(|| std::env::var("BREP_SIGN_READERS_EXACT").as_deref() == Ok("1")) {
        return solid_signed_volume(solid);
    }
    solid_signed_volume_for_sign(solid, bar)
}

/// [`solid_signed_volume`] read for its SIGN against `bar`, as the boolean's
/// assembly reads it (`volume <= tolerance³` refuses an inverted shell).
///
/// The exact integration spends most of a trimmed wall's time on the sliver
/// correction behind every chord of its rim pcurves; where such a pcurve is a
/// straight line in uv (a bore's rims, 85 % of the plate case's 105 ms check:
/// 256 chords per wall half, 442 368 correction stations in all) the sliver
/// has no area and the correction is zero to rounding, so this reading skips
/// it (`trimmed::with_straight_corrections_skipped`). Face volume and vector
/// area terms are integrated together and retained by content, then evaluated
/// about the same shell reference as `solid_signed_volume`.
///
/// Native two-sphere supports with the certified trim scope can return a
/// positive lower bound; `BREP_SPHERE_SIGN_BOUND=0|off` keeps the old path. Only a
/// comparison against `bar` is meaningful for that result; it is never stored
/// in the full mass cache. If the bound cannot prove `> bar`, the old path runs.
///
/// The verdict is the exact check's: when the reading sits within
/// `SIGN_READING_MARGIN` of the magnitudes of the bar, the exact value is
/// returned instead, bit for bit. Callers compare the result with `bar`.
pub fn solid_signed_volume_for_sign(solid: &BrepSolid, bar: f64) -> Result<f64, String> {
    let enabled = match std::env::var("BREP_SPHERE_SIGN_BOUND") {
        Ok(value) => value == "1" || value == "on",
        Err(std::env::VarError::NotPresent) => true,
        Err(_) => false,
    };
    let result = solid_signed_volume_for_sign_with_bound(solid, bar, enabled);
    if result.is_ok() && sign_terms_oracle_enabled() {
        verify_solid_sign_terms(solid)?;
    }
    result
}

pub(super) fn solid_signed_volume_for_sign_with_bound(solid: &BrepSolid, bar: f64, enabled: bool) -> Result<f64, String> {
    if enabled {
        if let Some(lower) = super::sphere_sign::positive_volume_bound(solid) {
            if bar.is_finite() && lower > bar {
                if crate::profile::profile_enabled() {
                    profile_line!("mass.sign_certificate kind=trimmed_spheres lower={lower:.9} bar={bar:.3e}");
                }
                return Ok(lower);
            }
        }
    }
    if sliver_bound_enabled() {
        if let Some(lower) = sliver_bound_certificate(solid, bar) {
            return Ok(lower);
        }
    }
    let token = super::profile::begin("solid_signed_volume_for_sign");
    let outcome = solid_sign_terms_reading(solid);
    super::profile::end(token);
    let (reading, magnitude) = outcome?;
    if (reading - bar).abs() > SIGN_READING_MARGIN * magnitude {
        return Ok(reading);
    }
    solid_signed_volume(solid)
}

/// `BREP_SIGN_SLIVER_BOUND` (on by default since 2026-11-03,
/// tier-P promotion; `0`/`off` restores the reading alone): before the sign
/// reading, try a certificate that integrates every face's cells exactly as
/// the reading does but skips the surface stations of its chord corrections,
/// bounding them instead (see [`sliver_bound_certificate`]). Read on every
/// call.
fn sliver_bound_enabled() -> bool {
    switch!(live "BREP_SIGN_SLIVER_BOUND", true)
}


/// A lower bound on the sign reading that proves its verdict, or `None`.
///
/// The reading sums, per face, the cells' quadrature plus the chord
/// corrections' quadrature `Σ w_k f(Q_k)` (`trimmed::curved_boundary_correction`,
/// positive Gauss weights times the sliver jacobian). Its correction is at most
/// `Σ |w_k| · sup |f|`: the first factor is the face's sliver measure
/// (`trimmed::with_sliver_measure`, read from the pcurves alone), the second
/// comes from the carrier's control net ([`surface_flux_bounds`]): the volume
/// integrand `(P - local) · N` is at most `r · n`, the vector area's `N` at most
/// `n`, so a face's contribution about the shell reference moves by at most
/// `measure · n · (r + |local - reference|) / 3`. Faces the reading already
/// holds exact terms for are taken as they are (bound zero); faces whose route
/// reads its own corrections are integrated exactly, as the reading does.
///
/// The certificate stands only when the bounded sum clears the bar by the
/// reading's own margin, with every bound and a rounding slack added to the
/// magnitude: then the reading would return a value above the bar without its
/// exact fallback, and this returns a lower bound on that value. Otherwise
/// `None`, and the reading runs as before (an error anywhere also yields
/// `None`, so the reading reports it).
pub(super) fn sliver_bound_certificate(solid: &BrepSolid, bar: f64) -> Option<f64> {
    if !bar.is_finite() {
        return None;
    }
    let token = super::profile::begin("solid_sign_sliver_bound");
    let outcome = super::trimmed::with_straight_corrections_skipped(|| -> Option<(f64, f64, f64, f64, [usize; 3])> {
        let (mut reading, mut magnitude, mut bound, mut scale) = (0.0, 0.0, 0.0, 0.0);
        let mut counts = [0usize; 3]; // exact terms held, bounded, integrated exactly
        for shell in &solid.shells {
            let reference = shell_volume_reference(shell).ok()?;
            let (mut volume, mut compensation) = (0.0f64, 0.0f64);
            for face in &shell.faces {
                let local = face_volume_reference(face).unwrap_or(reference);
                let identity = super::identity::face_contribution_identity(face, local);
                let offset = local.sub(reference);
                let (terms, face_bound, face_scale) = match crate::reading_memo::peek_sign_terms(identity) {
                    Some(terms) => {
                        counts[0] += 1;
                        (terms?, 0.0, 0.0)
                    }
                    None => match crate::reading_memo::memoized_bounded_sign_terms(identity, || bounded_face_terms(face, local)) {
                        Some((terms, per_offset, fixed, rounding)) => {
                            counts[1] += 1;
                            (terms, fixed + per_offset * offset.length(), rounding)
                        }
                        None => {
                            counts[2] += 1;
                            let terms = crate::reading_memo::memoized_sign_terms(identity, || {
                                face_volume_terms_about(face, local).ok()
                            })?;
                            (terms, 0.0, 0.0)
                        }
                    },
                };
                let area = Vec3::new(terms[1], terms[2], terms[3]);
                let contribution = terms[0] + offset.dot(area);
                magnitude += contribution.abs();
                bound += face_bound;
                scale += terms[0].abs() + offset.length() * area.length() + face_bound + face_scale * (1.0 + offset.length());
                let next = volume + contribution;
                if volume.abs() >= contribution.abs() {
                    compensation += (volume - next) + contribution;
                } else {
                    compensation += (contribution - next) + volume;
                }
                volume = next;
            }
            reading += volume + compensation;
        }
        Some((reading, magnitude, bound, scale, counts))
    });
    super::profile::end(token);
    let (reading, magnitude, bound, scale, counts) = outcome?;
    // Rounding: the reading adds each correction station to a running total
    // the cells started, and the certificate does not; a face's stations number
    // well under 1e6, so their re-association moves a slot by far less than
    // 1e-9 of the face's scale.
    let slack = 1e-9 * scale;
    let lower = reading - bound - slack;
    let certified = [reading, magnitude, bound, scale, lower].iter().all(|v| v.is_finite())
        && lower > bar
        && lower - bar > SIGN_READING_MARGIN * (magnitude + bound + slack);
    if crate::profile::profile_enabled() {
        profile_line!(
            "mass.sign_certificate kind=sliver_bound certified={certified} cells={reading:.9e} bound={bound:.3e} slack={slack:.3e} magnitude={magnitude:.3e} held={} bounded={} exact={}",
            counts[0], counts[1], counts[2]
        );
    }
    certified.then_some(lower)
}

/// One face's sign terms with the chord corrections bounded, as
/// `(terms, per_offset, fixed, rounding)`: the face's contribution about a
/// shell reference `ref` lies within `fixed + per_offset · |local - ref|` of
/// the reading's, and `rounding` is a scale for the certificate's slack.
/// `None` when the face's route reads its own corrections, a bound is not
/// finite, or the integration fails (the reading then integrates it).
pub(super) fn bounded_face_terms(face: &FaceRecord, local: Vec3) -> Option<([f64; 4], f64, f64, f64)> {
    let (terms, measure) = super::trimmed::with_sliver_measure(|| face_volume_terms_about(face, local));
    let terms = terms.ok()?;
    if measure.declined || !terms.iter().all(|v| v.is_finite()) {
        return None;
    }
    if measure.measure == 0.0 {
        return Some((terms, 0.0, 0.0, measure.complement / 3.0));
    }
    let (n, r) = surface_flux_bounds(&face.surface, local)?;
    let per_offset = measure.measure * n / 3.0;
    let fixed = per_offset * r;
    [per_offset, fixed].iter().all(|v| v.is_finite()).then_some((terms, per_offset, fixed, measure.complement / 3.0))
}

/// Bounds from the control net of `surface`, valid over its whole domain (and
/// its periodic wraps): `n >= |S_u × S_v|` and `r >= |S - center|`.
///
/// With homogeneous controls `Q = (w (P - center), w)`, all weights positive:
/// `S - center` is a convex combination of the `P - center`, so `r` is their
/// largest length; the homogeneous derivative `A_u` is a convex combination
/// of `p (Q_{i+1} - Q_i) / (u_{i+p+1} - u_{i+1})` (spline differentiation,
/// partition of unity of the degree-lowered basis), so its point part and its
/// weight part are at most the largest lengths of those differences' parts;
/// and `S_u = (X_u - w_u (S - center)) / w` with `w >= ` the smallest weight.
/// `None` for a non-positive or non-finite weight or control.
pub(super) fn surface_flux_bounds(surface: &crate::NurbsSurface, center: Vec3) -> Option<(f64, f64)> {
    let net = &surface.control_points;
    let rows = net.len();
    let columns = net.first()?.len();
    if rows == 0 || columns == 0 || net.iter().any(|row| row.len() != columns) {
        return None;
    }
    let relative = |i: usize, j: usize| -> Option<[f64; 4]> {
        let q = net[i][j];
        let values = [q.x - center.x * q.w, q.y - center.y * q.w, q.z - center.z * q.w, q.w];
        (values.iter().all(|v| v.is_finite()) && q.w > 0.0).then_some(values)
    };
    let mut w_min = f64::INFINITY;
    let mut r = 0.0f64;
    for i in 0..rows {
        for j in 0..columns {
            let q = relative(i, j)?;
            w_min = w_min.min(q[3]);
            r = r.max((q[0] * q[0] + q[1] * q[1] + q[2] * q[2]).sqrt() / q[3]);
        }
    }
    // (largest |X_d|, largest |w_d|) in one parameter direction.
    let derivative = |along_u: bool| -> Option<(f64, f64)> {
        let (degree, knots, count) = if along_u {
            (surface.degree_u, &surface.knots_u, rows)
        } else {
            (surface.degree_v, &surface.knots_v, columns)
        };
        if knots.len() < count + degree + 1 {
            return None;
        }
        let (mut point, mut weight) = (0.0f64, 0.0f64);
        if degree == 0 {
            return Some((0.0, 0.0));
        }
        for k in 0..count.saturating_sub(1) {
            let span = knots[k + degree + 1] - knots[k + 1];
            if !(span > 0.0) {
                continue;
            }
            let factor = degree as f64 / span;
            let others = if along_u { columns } else { rows };
            for other in 0..others {
                let (a, b) = if along_u {
                    (relative(k, other)?, relative(k + 1, other)?)
                } else {
                    (relative(other, k)?, relative(other, k + 1)?)
                };
                let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2], b[3] - a[3]];
                point = point.max(factor * (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt());
                weight = weight.max(factor * d[3].abs());
            }
        }
        Some((point, weight))
    };
    let (xu, wu) = derivative(true)?;
    let (xv, wv) = derivative(false)?;
    let su = (xu + wu * r) / w_min;
    let sv = (xv + wv * r) / w_min;
    let n = su * sv;
    // A little headroom for the evaluator's own rounding.
    let (n, r) = (n * (1.0 + 1e-9), r * (1.0 + 1e-9));
    (n.is_finite() && r.is_finite() && w_min.is_finite()).then_some((n, r))
}

/// Retain the exact path's shell references and compensated face order.
/// Each face's volume flux is affine in the reference: retain its local
/// volume and vector area, then translate the term to the shell reference.
/// Unchanged faces survive both id renumbering and a moving shell reference.
fn solid_sign_terms_reading(solid: &BrepSolid) -> Result<(f64, f64), String> {
    super::trimmed::with_straight_corrections_skipped(|| {
        let (mut reading, mut magnitude) = (0.0, 0.0);
        for (shell_index, shell) in solid.shells.iter().enumerate() {
            let (volume, faces) = shell_volume_sign_reading(shell, shell_index)?;
            reading += volume;
            magnitude += faces;
        }
        Ok((reading, magnitude))
    })
}

fn sign_terms_oracle_enabled() -> bool {
    switch!(live "BREP_SIGN_TERMS_ORACLE", false)
}

/// Diagnostic census only; the shipped reading and the sphere certificate
/// stay unchanged. The cold oracle never uses the mass cache or reading memo.
fn verify_solid_sign_terms(solid: &BrepSolid) -> Result<(), String> {
    let token = super::profile::begin("solid_sign_terms_oracle");
    let reading = solid_sign_terms_reading(solid).map(|pair| pair.0);
    super::profile::end(token);
    check_sign_terms(solid, reading?)
}

pub(super) fn check_sign_terms(solid: &BrepSolid, reading: f64) -> Result<(), String> {
    let exact = solid_signed_volume_uncached(solid)?;
    let error = (reading - exact).abs();
    let bar = 1e-9 * exact.abs();
    if !reading.is_finite() || !exact.is_finite() || error > bar {
        return Err(format!("sign terms oracle: retained {reading:.17e}, whole-body {exact:.17e}, error {error:.3e} exceeds {bar:.3e}"));
    }
    super::profile::emit_sign_oracle(solid, reading, exact)?;
    Ok(())
}

/// [`shell_signed_volume`]'s sum under the caller's correction policy, with
/// the sum of the face contributions' magnitudes beside it (the scale the
/// sign reading's margin is read against).
fn shell_volume_sign_reading(shell: &ShellRecord, shell_index: usize) -> Result<(f64, f64), String> {
    let reference = shell_volume_reference(shell)?;
    if crate::profile::profile_enabled() {
        profile_line!(
            "mass.sign_reference faces={} reference=({:.9},{:.9},{:.9})",
            shell.faces.len(), reference.x, reference.y, reference.z
        );
    }
    let mut volume = 0.0;
    let mut compensation = 0.0;
    let mut magnitude = 0.0;
    let face_lines = super::profile::face_lines_enabled();
    for (face_index, face) in shell.faces.iter().enumerate() {
        mass_profile(|p| p.faces += 1);
        let line_before = face_lines.then(super::profile::snapshot);
        let line_started = face_lines.then(Instant::now);
        // V_f(r) = V_f(a) + (a-r) · A_f / 3. Integrate both terms at
        // the SAME quadrature stations, including trim corrections. Using a
        // boundary-only vector area would miss the integrator's numerical
        // residual and could change the sign reading on inherited trims.
        // Anchor each face locally for accuracy far from the world origin.
        let local = face_volume_reference(face).unwrap_or(reference);
        let hash_started = super::profile::profile_started();
        let identity = super::identity::face_contribution_identity(face, local);
        let hash_ms = super::profile::elapsed_ms(hash_started);
        let mut reread = false;
        let terms = match crate::reading_memo::memoized_sign_terms(identity, || {
            reread = true;
            face_volume_terms_about(face, local).ok()
        }) {
            Some(terms) => terms,
            None => face_volume_terms_about(face, local)?,
        };
        let contribution = terms[0] + local.sub(reference).dot(Vec3::new(terms[1], terms[2], terms[3]));
        super::profile::sign_face(shell_index, face, reread, hash_ms);
        emit_face_line("shell_volume_sign_reading", shell_index, face_index, face, line_before, line_started);
        magnitude += contribution.abs();
        let next = volume + contribution;
        if volume.abs() >= contribution.abs() {
            compensation += (volume - next) + contribution;
        } else {
            compensation += (contribution - next) + volume;
        }
        volume = next;
    }
    Ok((volume + compensation, magnitude))
}

fn solid_signed_volume_uncached(solid: &BrepSolid) -> Result<f64, String> {
    let mut volume = 0.0;
    for shell in &solid.shells {
        volume += shell_signed_volume(shell)?;
    }
    Ok(volume)
}

pub(super) fn shell_volume_reference(shell: &ShellRecord) -> Result<Vec3, String> {
    shell.faces.iter().find_map(face_volume_reference)
        .ok_or_else(|| "mass_properties: shell has no finite geometric reference".to_string())
}

/// One finite authored point, with the same fallbacks as the exact integral.
pub(super) fn face_volume_reference(face: &FaceRecord) -> Option<Vec3> {
    let finite = |point: Vec3| point.x.is_finite() && point.y.is_finite() && point.z.is_finite();
    if let Some(coedge) = face
        .loops
        .first()
        .and_then(|loop_record| loop_record.coedges.first())
    {
        if let Ok(domain) = coedge.pcurve.domain() {
            if let Ok(uv) = coedge.pcurve.evaluate(domain[0]) {
                if let Ok(point) = face.surface.evaluate(uv.x, uv.y) {
                    if finite(point) {
                        return Some(point);
                    }
                }
            }
        }
    }
    if let Ok((u_breaks, v_breaks)) = surface_breaks(&face.surface) {
        let u = 0.5 * (u_breaks[0] + u_breaks[u_breaks.len() - 1]);
        let v = 0.5 * (v_breaks[0] + v_breaks[v_breaks.len() - 1]);
        if let Ok(point) = face.surface.evaluate(u, v) {
            if finite(point) {
                return Some(point);
            }
        }
    }
    for row in &face.surface.control_points {
        for control in row {
            if let Ok(point) = control.point() {
                if finite(point) {
                    return Some(point);
                }
            }
        }
    }
    None
}

/// Exact signed volume of one closed shell. Multi-shell tessellation uses this
/// to preserve the authored material orientation: exterior shells contribute
/// positively, while a void boundary contributes negatively.
pub(crate) fn shell_signed_volume(shell: &ShellRecord) -> Result<f64, String> {
    let reference = shell_volume_reference(shell)?;

    // A closed shell's divergence-theorem volume is independent of origin,
    // but evaluating each face about the world origin can cancel enormous
    // translated face terms down to a tiny cavity volume. Anchor the
    // integrand on an authored boundary point and compensate the remaining
    // face sum so the sign is stable for small, far-translated shells.
    let mut volume = 0.0;
    let mut compensation = 0.0;
    let face_lines = super::profile::face_lines_enabled();
    for (face_index, face) in shell.faces.iter().enumerate() {
        mass_profile(|p| p.faces += 1);
        let line_before = face_lines.then(super::profile::snapshot);
        let line_started = face_lines.then(Instant::now);
        let contribution = face_volume_contribution_about(face, reference)?;
        emit_face_line(
            "shell_signed_volume",
            0,
            face_index,
            face,
            line_before,
            line_started,
        );
        let next = volume + contribution;
        if volume.abs() >= contribution.abs() {
            compensation += (volume - next) + contribution;
        } else {
            compensation += (contribution - next) + volume;
        }
        volume = next;
    }
    Ok(volume + compensation)
}

/// Exact moments for affine faces via Green's theorem over the trim
/// pcurves: ∬ g du dv = ∮ G dv with G(u,v) = ∫ g dt.  On an affine carrier
/// every moment integrand is a low-degree polynomial, so the inner Gauss
/// antiderivative is exact and the boundary quadrature has the same quality
/// as `parameter_space_area` — no trim-polygon sampling error.  The loop
/// winding supplies the orientation sign, matching the affine volume path.
pub(super) fn affine_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
    let ku = crate::KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)?;
    let kv = crate::KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)?;
    let [u0, u1] = ku.domain();
    let [v0, v1] = kv.domain();
    let points = &face.surface.control_points;
    let p00 = points[0][0].point()?;
    let p10 = points[1][0].point()?;
    let p01 = points[0][1].point()?;
    let du = p10.sub(p00).scale(1.0 / (u1 - u0));
    let dv = p01.sub(p00).scale(1.0 / (v1 - v0));
    let weighted_normal = du.cross(dv);
    let g = |u: f64, v: f64| {
        let point = p00.add(du.scale(u - u0)).add(dv.scale(v - v0));
        integrand_value(kind, point, weighted_normal)
    };
    let inner = |u: f64, v: f64| {
        let half = (u - u0) * 0.5;
        let middle = (u + u0) * 0.5;
        let mut sum = 0.0;
        for index in 0..GAUSS_X.len() {
            sum += GAUSS_W[index] * g(middle + half * GAUSS_X[index], v);
        }
        sum * half
    };
    let mut total = 0.0;
    for loop_record in &face.loops {
        for coedge in &loop_record.coedges {
            for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
                // The inner antiderivative is a polynomial in u on an affine
                // carrier and is exact at any order; the boundary walk is the
                // pcurve's own, so it takes the pcurve's panels (`rule`).
                for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
                    for (parameter, weight) in panel.stations() {
                        let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
                        total += weight * inner(point.x, point.y) * tangent.y;
                    }
                }
            }
        }
    }
    // The loops closed as the area closes them (`closed_parameter_space_area`):
    // an open boundary integral moves with the uv origin. Along a straight
    // chord the integrand is a polynomial of degree at most four, which the
    // eight-station rule integrates exactly.
    for (end, start) in loop_closing_chords(face)? {
        let step = start.y - end.y;
        if step == 0.0 {
            continue;
        }
        for index in 0..GAUSS_X.len() {
            let fraction = 0.5 * (GAUSS_X[index] + 1.0);
            let u = end.x + (start.x - end.x) * fraction;
            let v = end.y + step * fraction;
            total += 0.5 * GAUSS_W[index] * inner(u, v) * step;
        }
    }
    Ok(total)
}

pub(super) fn face_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
    if is_affine(&face.surface)? {
        return affine_moment(face, kind);
    }
    if let Some(values) = biperiodic_band_integral(face, &[kind])? {
        return Ok(values[0]);
    }
    if is_untrimmed(face)? {
        integrate_untrimmed(face, kind)
    } else {
        integrate_trimmed(face, kind)
    }
}

/// Symmetric-matrix product `A[i][j] = M[k][i] * M[k][j]` reused by the Jacobi
/// sweep — kept tiny and explicit rather than pulling in a matrix crate.
pub(super) fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
    let mut r = [[0.0f64; 3]; 3];
    for i in 0..3 {
        for j in 0..3 {
            for k in 0..3 {
                r[i][j] += a[i][k] * b[k][j];
            }
        }
    }
    r
}

pub(super) fn mat3_transpose(a: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
    let mut r = [[0.0f64; 3]; 3];
    for i in 0..3 {
        for j in 0..3 {
            r[i][j] = a[j][i];
        }
    }
    r
}

/// Classic Jacobi eigenvalue iteration for a SYMMETRIC 3×3 matrix. Repeatedly
/// applies a Givens rotation in the plane of the largest off-diagonal element,
/// each rotation zeroing that element, until the matrix is diagonal to machine
/// precision. Returns `(eigenvalues, vectors)` where `vectors` holds the
/// eigenvectors as COLUMNS (`vectors[i][k]` is component `i` of eigenvector
/// `k`), unsorted. For a symmetric matrix Jacobi is unconditionally
/// convergent and the accumulated rotations stay orthonormal, so the columns
/// are mutually orthonormal by construction.
pub(super) fn jacobi_eigen_symmetric_3x3(matrix: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
    // Symmetrize defensively against tiny asymmetry from round-off upstream.
    let mut a = [
        [matrix[0][0], 0.0, 0.0],
        [0.0, matrix[1][1], 0.0],
        [0.0, 0.0, matrix[2][2]],
    ];
    a[0][1] = 0.5 * (matrix[0][1] + matrix[1][0]);
    a[1][0] = a[0][1];
    a[0][2] = 0.5 * (matrix[0][2] + matrix[2][0]);
    a[2][0] = a[0][2];
    a[1][2] = 0.5 * (matrix[1][2] + matrix[2][1]);
    a[2][1] = a[1][2];

    let mut v = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
    let scale = a[0][0].abs() + a[1][1].abs() + a[2][2].abs() + 1.0;
    for _sweep in 0..64 {
        // Pick the largest off-diagonal magnitude.
        let pairs = [(0usize, 1usize), (0, 2), (1, 2)];
        let (mut p, mut q, mut best) = (0usize, 1usize, 0.0f64);
        for &(i, j) in &pairs {
            if a[i][j].abs() > best {
                best = a[i][j].abs();
                p = i;
                q = j;
            }
        }
        if best <= 1e-18 * scale {
            break;
        }
        // Angle that zeroes a[p][q]: t = tan(theta) is the smaller root of
        // t² + 2·theta·t − 1 = 0 with theta = (a_qq − a_pp)/(2 a_pq).
        let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
        let t = if theta == 0.0 {
            1.0
        } else {
            theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt())
        };
        let c = 1.0 / (t * t + 1.0).sqrt();
        let s = t * c;
        // Givens rotation J: J[p][p]=J[q][q]=c, J[p][q]=s, J[q][p]=−s.
        let mut j = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
        j[p][p] = c;
        j[q][q] = c;
        j[p][q] = s;
        j[q][p] = -s;
        // A ← Jᵀ A J   (drives a[p][q] to zero), V ← V J.
        a = mat3_mul(mat3_transpose(j), mat3_mul(a, j));
        v = mat3_mul(v, j);
    }
    ([a[0][0], a[1][1], a[2][2]], v)
}

/// Principal axes/moments from a centroidal inertia tensor (Golovanov §8.11).
/// Diagonalizes the symmetric tensor, sorts the eigenpairs by moment
/// ASCENDING, returns each eigenvector as a ROW (`axes[i]` pairs with
/// `moments[i]`) normalized to unit length, and fixes the sign of the third
/// axis so the frame is right-handed (determinant +1).
pub(super) fn principal_frame(inertia: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
    let (values, vectors) = jacobi_eigen_symmetric_3x3(inertia);
    // Column k of `vectors` is the eigenvector for `values[k]`.
    let mut order = [0usize, 1, 2];
    order.sort_by(|&a, &b| values[a].total_cmp(&values[b]));
    let mut moments = [0.0f64; 3];
    let mut axes = [[0.0f64; 3]; 3];
    for (slot, &k) in order.iter().enumerate() {
        moments[slot] = values[k];
        let mut axis = [vectors[0][k], vectors[1][k], vectors[2][k]];
        let length = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
        if length > 0.0 {
            axis = [axis[0] / length, axis[1] / length, axis[2] / length];
        }
        axes[slot] = axis;
    }
    // Right-hand the frame: if axis0 × axis1 points opposite axis2, flip axis2.
    let cross = [
        axes[0][1] * axes[1][2] - axes[0][2] * axes[1][1],
        axes[0][2] * axes[1][0] - axes[0][0] * axes[1][2],
        axes[0][0] * axes[1][1] - axes[0][1] * axes[1][0],
    ];
    let det = cross[0] * axes[2][0] + cross[1] * axes[2][1] + cross[2] * axes[2][2];
    if det < 0.0 {
        axes[2] = [-axes[2][0], -axes[2][1], -axes[2][2]];
    }
    (moments, axes)
}

/// Area, volume, centroid, and centroidal inertia (unit density).  Area and
/// volume use the same exact paths as `solid_mass_properties`; the moment
/// integrals use divergence-theorem surface quadrature (exact for untrimmed
/// spans, trim-polygon scanline accuracy for trimmed faces).
pub fn solid_mass_properties_full(solid: &BrepSolid) -> Result<FullMassProperties, String> {
    let base = solid_mass_properties(solid)?;
    let token = super::profile::begin("solid_mass_properties_full.moments");
    let result = solid_mass_properties_full_moments(solid, base);
    super::profile::end(token);
    result
}

fn solid_mass_properties_full_moments(
    solid: &BrepSolid,
    base: MassProperties,
) -> Result<FullMassProperties, String> {
    const MOMENT_KINDS: [Integrand; 9] = [
        Integrand::MomentX,
        Integrand::MomentY,
        Integrand::MomentZ,
        Integrand::SecondXX,
        Integrand::SecondYY,
        Integrand::SecondZZ,
        Integrand::ProductXY,
        Integrand::ProductXZ,
        Integrand::ProductYZ,
    ];
    let mut moments = [0.0f64; 3];
    let mut seconds = [0.0f64; 3];
    let mut products = [0.0f64; 3];
    for shell in &solid.shells {
        for face in &shell.faces {
            mass_profile(|p| p.faces += 1);
            let results = if !is_affine(&face.surface)? && !is_untrimmed(face)? {
                mass_profile(|p| p.trimmed_faces += 1);
                // One cell decomposition, all nine moment integrands per
                // station, instead of nine full passes per face.
                integrate_trimmed_multi(face, &MOMENT_KINDS)?
            } else {
                MOMENT_KINDS
                    .iter()
                    .map(|kind| face_moment(face, *kind))
                    .collect::<Result<Vec<_>, _>>()?
            };
            moments[0] += results[0];
            moments[1] += results[1];
            moments[2] += results[2];
            seconds[0] += results[3];
            seconds[1] += results[4];
            seconds[2] += results[5];
            products[0] += results[6];
            products[1] += results[7];
            products[2] += results[8];
        }
    }
    let volume = base.volume;
    if volume.abs() <= 1e-30 {
        return Err("solid_mass_properties_full: non-positive volume".into());
    }
    let centroid = Vec3::new(
        moments[0] / volume,
        moments[1] / volume,
        moments[2] / volume,
    );
    // Inertia about the origin, then parallel-axis down to the centroid.
    let ixx =
        seconds[1] + seconds[2] - volume * (centroid.y * centroid.y + centroid.z * centroid.z);
    let iyy =
        seconds[0] + seconds[2] - volume * (centroid.x * centroid.x + centroid.z * centroid.z);
    let izz =
        seconds[0] + seconds[1] - volume * (centroid.x * centroid.x + centroid.y * centroid.y);
    let ixy = -(products[0] - volume * centroid.x * centroid.y);
    let ixz = -(products[1] - volume * centroid.x * centroid.z);
    let iyz = -(products[2] - volume * centroid.y * centroid.z);
    let inertia = [[ixx, ixy, ixz], [ixy, iyy, iyz], [ixz, iyz, izz]];
    let (principal_moments, principal_axes) = principal_frame(inertia);
    Ok(FullMassProperties {
        surface_area: base.surface_area,
        volume,
        centroid,
        inertia,
        principal_moments,
        principal_axes,
    })
}