Skip to main content

brep_topology/props/mass_properties/
solid_props.rs

1pub use super::*;
2use super::mass_profile;
3use web_time::Instant;
4
5/// The static facts a `mass.face` line carries beside the route: the
6/// recognized carrier kind, the patch degrees and closed directions, and the
7/// trim's size. Read only when `BREP_PROFILE_MASS_FACES` armed the lines.
8fn face_line_meta(face: &FaceRecord) -> (&'static str, usize, usize, bool, bool, usize, usize) {
9    // `kind_label` spells the general carrier with spaces; the profile line is
10    // whitespace-tokenized, so collapse it to one word.
11    let kind = match face.surface.analytic().map(|analytic| analytic.kind_label()) {
12        Some("Surface of revolution") => "Revolution",
13        Some(label) => label,
14        None => "Fitted",
15    };
16    let (closed_u, closed_v) = face.surface.closed_directions().unwrap_or((false, false));
17    let coedges = face
18        .loops
19        .iter()
20        .map(|loop_record| loop_record.coedges.len())
21        .sum();
22    (
23        kind,
24        face.surface.degree_u,
25        face.surface.degree_v,
26        closed_u,
27        closed_v,
28        face.loops.len(),
29        coedges,
30    )
31}
32
33/// Emit one `mass.face` line for the face just integrated. `before` is the
34/// counter snapshot taken ahead of its work and `started` the wall clock at
35/// the same point; both are `None` unless the lines are armed.
36fn emit_face_line(
37    call: &str,
38    shell: usize,
39    face_index: usize,
40    face: &FaceRecord,
41    before: Option<super::profile::MassProfile>,
42    started: Option<Instant>,
43) {
44    let (Some(before), Some(started)) = (before, started) else {
45        return;
46    };
47    let wall_ms = started.elapsed().as_secs_f64() * 1_000.0;
48    let (kind, degree_u, degree_v, closed_u, closed_v, loops, coedges) = face_line_meta(face);
49    super::profile::emit_face(
50        call, shell, face_index, kind, degree_u, degree_v, closed_u, closed_v, loops, coedges,
51        before, wall_ms,
52    );
53}
54
55pub fn solid_mass_properties(solid: &BrepSolid) -> Result<MassProperties, String> {
56    let token = super::profile::begin("solid_mass_properties");
57    let result = solid_mass_properties_cached(solid);
58    super::profile::end(token);
59    if result.is_ok() && sign_terms_oracle_enabled() && solid.kind == crate::BodyKind::Solid
60        && !solid.shells.is_empty() && solid.shells.iter().all(|shell| !shell.faces.is_empty())
61    {
62        verify_solid_sign_terms(solid)?;
63    }
64    if let (Some(dump), Ok(properties)) = (super::profile::identity_dump(), result.as_ref()) {
65        super::profile::emit_identity(
66            dump,
67            "solid_mass_properties",
68            solid,
69            &[
70                ("volume_bits", properties.volume),
71                ("area_bits", properties.surface_area),
72            ],
73        );
74    }
75    result
76}
77
78/// Validate the memo against the current geometry on EVERY read: topology
79/// records are publicly editable, and copies may have been transformed or healed.
80fn solid_mass_properties_cached(solid: &BrepSolid) -> Result<MassProperties, String> {
81    let identity = face_set_identity(solid);
82    if let Some((cached_identity, properties)) = solid.mass_properties_cache.entry.get() {
83        if cached_identity == identity {
84            if super::profile::mass_profile_enabled() {
85                let measured = solid_mass_properties_inner(solid)?;
86                assert_eq!(properties.volume.to_bits(), measured.volume.to_bits(),
87                    "mass cache changed volume");
88                assert_eq!(properties.surface_area.to_bits(), measured.surface_area.to_bits(),
89                    "mass cache changed area");
90                eprintln!("mass.cache hit faces={} verified=true", identity.faces);
91            }
92            return Ok(properties);
93        }
94    }
95    // Never retain a failed computation, nor an old entry for modified geometry.
96    solid.mass_properties_cache.entry.set(None);
97    let properties = solid_mass_properties_inner(solid)?;
98    solid.mass_properties_cache.entry.set(Some((identity, properties)));
99    Ok(properties)
100}
101
102pub fn solid_mass_properties_inner(solid: &BrepSolid) -> Result<MassProperties, String> {
103    let mut properties = MassProperties {
104        surface_area: 0.0,
105        volume: 0.0,
106    };
107    let mut volume_compensation = 0.0;
108    let face_lines = super::profile::face_lines_enabled();
109    for (shell_index, shell) in solid.shells.iter().enumerate() {
110        if shell.faces.is_empty() {
111            continue;
112        }
113        // Use the same local reference as the signed-volume orientation gate.
114        // World-origin flux terms can dwarf a small translated solid's volume;
115        // even tiny quadrature or boundary errors then dominate their sum.
116        let reference = shell_volume_reference(shell)?;
117        let kinds = [Integrand::Area, Integrand::VolumeAbout(reference)];
118        for (face_index, face) in shell.faces.iter().enumerate() {
119            mass_profile(|p| p.faces += 1);
120            let line_before = face_lines.then(super::profile::snapshot);
121            let line_started = face_lines.then(Instant::now);
122            let gate_started = super::profile::profile_started();
123            let (area, volume) = if let Some(values) = biperiodic_band_integral(face, &kinds)? {
124                mass_profile(|p| {
125                    p.route_biperiodic += 1;
126                    p.gate_ms += super::profile::elapsed_ms(gate_started);
127                });
128                (values[0], values[1] / 3.0)
129            } else if !is_affine(&face.surface)? && !is_untrimmed(face)? {
130                mass_profile(|p| {
131                    p.trimmed_faces += 1;
132                    p.gate_ms += super::profile::elapsed_ms(gate_started);
133                });
134                // Preserve the shared cell decomposition and integration pass.
135                let values = integrate_trimmed_multi(face, &kinds)?;
136                (values[0], values[1] / 3.0)
137            } else if is_affine(&face.surface)? {
138                mass_profile(|p| {
139                    p.route_affine += 1;
140                    p.gate_ms += super::profile::elapsed_ms(gate_started);
141                });
142                // One parameter-space area and one planar metric for both
143                // numbers, instead of `face_area` and
144                // `face_volume_contribution_about` each walking the trim.
145                affine_area_and_volume_about(face, reference)?
146            } else {
147                mass_profile(|p| {
148                    p.route_untrimmed += 1;
149                    p.gate_ms += super::profile::elapsed_ms(gate_started);
150                });
151                // One station sweep carrying both integrands, instead of one
152                // sweep per integrand.
153                let started = super::profile::profile_started();
154                let values = integrate_untrimmed_multi(face, &kinds)?;
155                mass_profile(|p| p.untrimmed_ms += super::profile::elapsed_ms(started));
156                (values[0], values[1] / 3.0)
157            };
158            emit_face_line(
159                "solid_mass_properties",
160                shell_index,
161                face_index,
162                face,
163                line_before,
164                line_started,
165            );
166            properties.surface_area += area;
167            let next = properties.volume + volume;
168            if properties.volume.abs() >= volume.abs() {
169                volume_compensation += (properties.volume - next) + volume;
170            } else {
171                volume_compensation += (volume - next) + properties.volume;
172            }
173            properties.volume = next;
174        }
175    }
176    properties.volume += volume_compensation;
177    Ok(properties)
178}
179
180/// Exact signed volume. A single nonempty shell shares its area/volume
181/// measurement with subsequent property queries. Multiple shells retain the
182/// original per-shell compensated sum: substituting the across-face sum can
183/// change the last bits and an orientation gate must not change its answer.
184pub fn solid_signed_volume(solid: &BrepSolid) -> Result<f64, String> {
185    let token = super::profile::begin("solid_signed_volume");
186    let result = if solid.shells.len() == 1 && !solid.shells[0].faces.is_empty() {
187        match solid_mass_properties_cached(solid) {
188            Ok(properties) => {
189                if super::profile::mass_profile_enabled() {
190                    let original = solid_signed_volume_uncached(solid)
191                        .expect("shared mass measurement changed a signed-volume refusal");
192                    assert_eq!(properties.volume.to_bits(), original.to_bits(),
193                        "shared mass measurement changed signed volume");
194                }
195                Ok(properties.volume)
196            }
197            // Area computation must not introduce a new signed-volume refusal.
198            Err(_) => solid_signed_volume_uncached(solid),
199        }
200    } else {
201        solid_signed_volume_uncached(solid)
202    };
203    super::profile::end(token);
204    if result.is_ok() && sign_terms_oracle_enabled() && solid.kind == crate::BodyKind::Solid {
205        verify_solid_sign_terms(solid)?;
206    }
207    if let (Some(dump), Ok(volume)) = (super::profile::identity_dump(), result.as_ref()) {
208        super::profile::emit_identity(dump, "solid_signed_volume", solid, &[("signed_bits", *volume)]);
209    }
210    result
211}
212
213/// The margin, as a fraction of the sum of the face contributions' magnitudes,
214/// inside which [`solid_signed_volume_for_sign`] trusts no reading of its own
215/// and integrates exactly. The skipped corrections are zero to rounding
216/// (collinear control points, 1e-12 of the extent), so this is a very wide
217/// safety margin, not a measured error.
218const SIGN_READING_MARGIN: f64 = 1e-6;
219
220/// [`solid_signed_volume_for_sign`] for a caller that compares the result with
221/// `bar` and nothing else (the boolean assembly's closed tail, the shell's
222/// orientation, the direct edit's inversion check — 2026-10-17): the memoised
223/// sign reading, whose verdict against the bar is the exact integral's.
224/// `BREP_SIGN_READERS_EXACT=1` restores the exact read at those call sites,
225/// for an on/off census. Read once.
226pub fn signed_volume_against(solid: &BrepSolid, bar: f64) -> Result<f64, String> {
227    static EXACT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
228    if *EXACT.get_or_init(|| std::env::var("BREP_SIGN_READERS_EXACT").as_deref() == Ok("1")) {
229        return solid_signed_volume(solid);
230    }
231    solid_signed_volume_for_sign(solid, bar)
232}
233
234/// [`solid_signed_volume`] read for its SIGN against `bar`, as the boolean's
235/// assembly reads it (`volume <= tolerance³` refuses an inverted shell).
236///
237/// The exact integration spends most of a trimmed wall's time on the sliver
238/// correction behind every chord of its rim pcurves; where such a pcurve is a
239/// straight line in uv (a bore's rims, 85 % of the plate case's 105 ms check:
240/// 256 chords per wall half, 442 368 correction stations in all) the sliver
241/// has no area and the correction is zero to rounding, so this reading skips
242/// it (`trimmed::with_straight_corrections_skipped`). Face volume and vector
243/// area terms are integrated together and retained by content, then evaluated
244/// about the same shell reference as `solid_signed_volume`.
245///
246/// Native two-sphere supports with the certified trim scope can return a
247/// positive lower bound; `BREP_SPHERE_SIGN_BOUND=0|off` keeps the old path. Only a
248/// comparison against `bar` is meaningful for that result; it is never stored
249/// in the full mass cache. If the bound cannot prove `> bar`, the old path runs.
250///
251/// The verdict is the exact check's: when the reading sits within
252/// `SIGN_READING_MARGIN` of the magnitudes of the bar, the exact value is
253/// returned instead, bit for bit. Callers compare the result with `bar`.
254pub fn solid_signed_volume_for_sign(solid: &BrepSolid, bar: f64) -> Result<f64, String> {
255    let enabled = match std::env::var("BREP_SPHERE_SIGN_BOUND") {
256        Ok(value) => value == "1" || value == "on",
257        Err(std::env::VarError::NotPresent) => true,
258        Err(_) => false,
259    };
260    let result = solid_signed_volume_for_sign_with_bound(solid, bar, enabled);
261    if result.is_ok() && sign_terms_oracle_enabled() {
262        verify_solid_sign_terms(solid)?;
263    }
264    result
265}
266
267pub fn solid_signed_volume_for_sign_with_bound(solid: &BrepSolid, bar: f64, enabled: bool) -> Result<f64, String> {
268    if enabled {
269        if let Some(lower) = super::sphere_sign::positive_volume_bound(solid) {
270            if bar.is_finite() && lower > bar {
271                if crate::profile::profile_enabled() {
272                    profile_line!("mass.sign_certificate kind=trimmed_spheres lower={lower:.9} bar={bar:.3e}");
273                }
274                return Ok(lower);
275            }
276        }
277    }
278    if sliver_bound_enabled() {
279        if let Some(lower) = sliver_bound_certificate(solid, bar) {
280            return Ok(lower);
281        }
282    }
283    let token = super::profile::begin("solid_signed_volume_for_sign");
284    let outcome = solid_sign_terms_reading(solid);
285    super::profile::end(token);
286    let (reading, magnitude) = outcome?;
287    if (reading - bar).abs() > SIGN_READING_MARGIN * magnitude {
288        return Ok(reading);
289    }
290    solid_signed_volume(solid)
291}
292
293/// The quadtree depth of [`solid_sign_coarse_certificate`]: boundary cells
294/// split this often, against four times for the exact reading.
295pub const COARSE_SIGN_DEPTH: usize = 1;
296
297/// `BREP_SEW_SIGN_COARSE_THIN` (default on since the 2026-11-20
298/// promotion; `=0` restores the coarse quadtree on every face): in
299/// [`solid_sign_coarse_certificate`], a face whose trim cannot hold one whole
300/// coarse cell ([`trim_holds_no_coarse_cell`]) is read by its exact route
301/// instead of the coarse quadtree. The coarse pass reads nothing of such a
302/// face and bounds all of it by its net, so this only replaces a bound with
303/// the reading's own terms.
304pub fn sign_coarse_thin_enabled() -> bool {
305    crate::switch!("BREP_SEW_SIGN_COARSE_THIN", true)
306}
307
308/// Whether no cell of the coarse quadtree at `depth` can lie inside the
309/// face's trim, so that the coarse pass would integrate none of it. The
310/// quadtree's root cells are the carrier's knot spans, halved `depth` times;
311/// a region narrower in u (or in v) than those cells on every span it meets
312/// holds none whole. The region is boxed by its pcurves' control points
313/// (with positive weights each pcurve lies in their hull). A routing test
314/// only: either answer leaves the certificate sound. `false` when the box
315/// cannot be read, or lies off the carrier's spans (an unwrapped trim).
316fn trim_holds_no_coarse_cell(face: &FaceRecord, depth: usize) -> bool {
317    let Ok((u_breaks, v_breaks)) = surface_breaks(&face.surface) else {
318        return false;
319    };
320    let (mut low, mut high) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
321    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
322        for control in &coedge.pcurve.control_points {
323            let Ok(point) = control.point() else {
324                return false;
325            };
326            if !(control.w > 0.0) || !point.x.is_finite() || !point.y.is_finite() {
327                return false;
328            }
329            low = [low[0].min(point.x), low[1].min(point.y)];
330            high = [high[0].max(point.x), high[1].max(point.y)];
331        }
332    }
333    let cell = 0.5f64.powi(depth.min(60) as i32);
334    let narrow = |breaks: &[f64], low: f64, high: f64| -> bool {
335        let mut met = false;
336        for pair in breaks.windows(2) {
337            if pair[1] <= low || pair[0] >= high {
338                continue;
339            }
340            met = true;
341            if !(high - low < (pair[1] - pair[0]) * cell) {
342                return false;
343            }
344        }
345        met
346    };
347    low[0] <= high[0] && low[1] <= high[1]
348        && (narrow(&u_breaks, low[0], high[0]) || narrow(&v_breaks, low[1], high[1]))
349}
350
351/// [`solid_sign_coarse_certificate`]'s reading and the half-width of the
352/// interval it certifies.
353#[derive(Clone, Copy, Debug)]
354pub struct CoarseSign {
355    /// The faces' contributions with every boundary cell left at the coarse
356    /// depth skipped.
357    pub reading: f64,
358    /// The skipped regions' bound plus the rounding slack: the volume lies
359    /// in `reading ± bound`.
360    pub bound: f64,
361    /// The skipped parameter-plane measure, summed over the faces (a census
362    /// figure).
363    pub skipped: f64,
364}
365
366/// A CERTIFICATE for the sign of [`solid_signed_volume`] read with a coarse
367/// quadtree: `Some(CoarseSign)` whose `reading ± bound` holds the volume, or
368/// `None` when no bound can be stated (the caller then reads the sign
369/// exactly).
370///
371/// Every face is integrated by its exact route, at the exact route's
372/// stations, except that a trimmed face's boundary cells refine only to
373/// `depth` and the partial cells left there are NOT integrated
374/// ([`super::trimmed::with_coarse_quadtree`]). The full cells, the chord
375/// corrections and every other route are term for term the exact reading's.
376/// Under `BREP_SEW_SIGN_COARSE_THIN` ([`sign_coarse_thin_enabled`]) a face
377/// whose trim cannot hold one whole cell at `depth`
378/// ([`trim_holds_no_coarse_cell`]) is read whole by its exact route, with no
379/// skipped region and so no bound: a thin strip of a full-turn carrier, whose
380/// coarse cells are all boundary cells, otherwise adds its whole area times
381/// the net's `n · r` to the bound.
382///
383/// The bound, per face. The volume flux is
384/// `(1/3) ∫∫_R (S − ref)·(S_u × S_v) du dv` over the trimmed region `R`.
385/// A skipped region `K` (the trim fragments clipped to the skipped cells)
386/// therefore contributes at most `(1/3) |K| · sup|S − ref| · sup|S_u × S_v|`
387/// in magnitude. Here:
388/// - `|K|` is the sum of the fragments' absolute shoelace areas. That is
389///   exactly their measure for simple trim loops: a simple loop's winding
390///   number is 0 or ±1, and the clip keeps it.
391/// - `|S − ref| ≤ |S − local| + |local − ref| ≤ r + |local − ref|`.
392/// - `|S_u × S_v| ≤ n`.
393/// - `(n, r)` are the control-net bounds about `local` of the knot span
394///   holding `K` ([`surface_flux_bounds_on_span`]: by local support only that
395///   span's `(p+1)(q+1)` controls weigh there). A cell that is not inside one
396///   span, or that lies past the domain, takes the whole net's
397///   ([`surface_flux_bounds`], valid over the domain and its periodic wraps).
398///   A skipped region past an OPEN end of the carrier declines, because no
399///   net bound holds on the extension.
400///
401/// So the true integral of the skipped regions lies within `Σ` of those
402/// bounds of zero. The reading is what the exact reading would give with
403/// those regions removed. A sign is decided only when `|reading ∓ bar|`
404/// exceeds the bound.
405///
406/// What this certifies: the sign of any integration that agrees with the
407/// exact reading on the cells and corrections both share, and reads the
408/// skipped regions within their true bound. The exact reading's own
409/// quadrature of those regions (finer cells and triangle cubature) is not
410/// itself bounded here.
411///
412/// Declined (`None`):
413/// - a face on the hopped unwrap route, which chooses its region by an area
414///   read over cells the coarse pass skips;
415/// - a carrier with no net bound (a non-positive weight), or a call whose
416///   kinds carry no volume reference;
417/// - any non-finite value.
418///
419/// Rounding: the reading re-associates no station within a face. A skipped
420/// cell only removes addends, so `1e-9` of the faces' scale covers the
421/// difference in summation order, as in [`sliver_bound_certificate`].
422/// Nothing is memoised.
423pub fn solid_sign_coarse_certificate(solid: &BrepSolid, depth: usize) -> Option<CoarseSign> {
424    let (mut reading, mut bound, mut scale, mut skipped) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
425    // Early out: a sign is settled only when |reading| exceeds the bound, and
426    // a body's volume is at most that of a box holding its carriers' controls
427    // (their convex hulls hold the faces). Once the bound passes that box,
428    // nothing is left to settle. Stopping only falls through to the exact
429    // path, so this never weakens the certificate.
430    let reach = control_box_volume(solid);
431    // The faces in falling order of what their skipped cells could add to the
432    // bound (the whole net's `n · r` over the carrier's domain, read from
433    // controls alone), so that a body the certificate cannot settle reaches
434    // the early out after a few faces rather than most of them. On the
435    // bench's spiroid, a few cone walls (integrand zero about their apex,
436    // net bound large) carry most of the bound. The order changes only the
437    // summation order, which the slack covers.
438    let mut faces = Vec::new();
439    for shell in &solid.shells {
440        let reference = shell_volume_reference(shell).ok()?;
441        for face in &shell.faces {
442            let local = face_volume_reference(face).unwrap_or(reference);
443            faces.push((face, local, reference, bound_potential(&face.surface, local)));
444        }
445    }
446    faces.sort_by(|a, b| b.3.total_cmp(&a.3));
447    {
448        let thin_route = sign_coarse_thin_enabled();
449        for &(face, local, reference, _) in &faces {
450            let (terms, measure) = if thin_route && trim_holds_no_coarse_cell(face, depth) {
451                // Read whole by its exact route: bound zero, the reading's own terms.
452                (face_volume_terms_about(face, local), super::trimmed::CoarseMeasure { depth, ..Default::default() })
453            } else {
454                super::trimmed::with_coarse_quadtree(depth, || face_volume_terms_about(face, local))
455            };
456            let terms = terms.ok()?;
457            if measure.declined || !terms.iter().all(|v| v.is_finite()) {
458                return None;
459            }
460            let offset = local.sub(reference);
461            let area = Vec3::new(terms[1], terms[2], terms[3]);
462            let contribution = terms[0] + offset.dot(area);
463            let face_bound = (measure.flux + measure.normal * offset.length()) / 3.0;
464            reading += contribution;
465            bound += face_bound;
466            skipped += measure.skipped;
467            scale += terms[0].abs() + offset.length() * area.length() + face_bound;
468            if !(bound <= reach) {
469                return None;
470            }
471        }
472    }
473    let bound = bound + 1e-9 * scale;
474    [reading, bound, skipped].iter().all(|v| v.is_finite()).then_some(CoarseSign { reading, bound, skipped })
475}
476
477/// The whole net's `n · r` about `center` times the carrier's parameter
478/// domain area: an ordering key for [`solid_sign_coarse_certificate`], not a
479/// bound it relies on. Infinite where no net bound holds, so such a face
480/// (which declines) comes first.
481fn bound_potential(surface: &crate::NurbsSurface, center: Vec3) -> f64 {
482    let span = |knots: &[f64], degree: usize| -> f64 {
483        match (knots.get(degree), knots.len().checked_sub(degree + 1).and_then(|i| knots.get(i))) {
484            (Some(low), Some(high)) => (high - low).abs(),
485            _ => f64::INFINITY,
486        }
487    };
488    let area = span(&surface.knots_u, surface.degree_u) * span(&surface.knots_v, surface.degree_v);
489    match surface_flux_bounds(surface, center) {
490        Some((n, r)) if (n * r * area).is_finite() => n * r * area,
491        _ => f64::INFINITY,
492    }
493}
494
495/// The volume of the axis-aligned box holding every face carrier's control
496/// points; infinite when there are none or any is not finite.
497fn control_box_volume(solid: &BrepSolid) -> f64 {
498    let (mut low, mut high) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
499    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
500        for control in face.surface.control_points.iter().flatten() {
501            let Ok(point) = control.point() else { return f64::INFINITY };
502            for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
503                low[axis] = low[axis].min(value);
504                high[axis] = high[axis].max(value);
505            }
506        }
507    }
508    let volume = (0..3).map(|axis| high[axis] - low[axis]).product::<f64>();
509    if volume.is_finite() { volume } else { f64::INFINITY }
510}
511
512/// `BREP_SIGN_SLIVER_BOUND` (on by default since 2026-11-03,
513/// promotion; `0`/`off` restores the reading alone): before the sign
514/// reading, try a certificate that integrates every face's cells exactly as
515/// the reading does but skips the surface stations of its chord corrections,
516/// bounding them instead (see [`sliver_bound_certificate`]). Read on every
517/// call.
518fn sliver_bound_enabled() -> bool {
519    switch!(live "BREP_SIGN_SLIVER_BOUND", true)
520}
521
522
523/// A lower bound on the sign reading that proves its verdict, or `None`.
524///
525/// The reading sums, per face, the cells' quadrature plus the chord
526/// corrections' quadrature `Σ w_k f(Q_k)` (`trimmed::curved_boundary_correction`,
527/// positive Gauss weights times the sliver jacobian). Its correction is at most
528/// `Σ |w_k| · sup |f|`: the first factor is the face's sliver measure
529/// (`trimmed::with_sliver_measure`, read from the pcurves alone), the second
530/// comes from the carrier's control net ([`surface_flux_bounds`]): the volume
531/// integrand `(P - local) · N` is at most `r · n`, the vector area's `N` at most
532/// `n`, so a face's contribution about the shell reference moves by at most
533/// `measure · n · (r + |local - reference|) / 3`. Faces the reading already
534/// holds exact terms for are taken as they are (bound zero); faces whose route
535/// reads its own corrections are integrated exactly, as the reading does.
536///
537/// The certificate stands only when the bounded sum clears the bar by the
538/// reading's own margin, with every bound and a rounding slack added to the
539/// magnitude: then the reading would return a value above the bar without its
540/// exact fallback, and this returns a lower bound on that value. Otherwise
541/// `None`, and the reading runs as before (an error anywhere also yields
542/// `None`, so the reading reports it).
543///
544/// Under `BREP_SIGN_CANONICAL_LOOPS` ([`sign_canonical_loops_mode`]) every face
545/// is read in its canonical rotation ([`canonical_loops`]), so that a face a
546/// later boolean hands back with its loops started one coedge further on keys
547/// and reads the same terms as before.
548pub fn sliver_bound_certificate(solid: &BrepSolid, bar: f64) -> Option<f64> {
549    match sign_canonical_loops_mode() {
550        crate::env_read::Mode::Off => sliver_bound_reading(solid, bar, false),
551        crate::env_read::Mode::On => sliver_bound_reading(solid, bar, true),
552        crate::env_read::Mode::Check => {
553            let given = sliver_bound_reading(solid, bar, false);
554            let canonical = sliver_bound_reading(solid, bar, true);
555            canonical_loops_check(solid, given, canonical);
556            given
557        }
558    }
559}
560
561/// `BREP_SIGN_CANONICAL_LOOPS` (default on since the 2026-11-21
562/// promotion; `0|off` reads every face as given; `check` reads both and prints
563/// one `mass.sign_canonical_check` line per certificate, the given rotation
564/// deciding): see [`sliver_bound_certificate`].
565pub fn sign_canonical_loops_mode() -> crate::env_read::Mode {
566    crate::mode_switch!(live "BREP_SIGN_CANONICAL_LOOPS", true)
567}
568
569
570/// `face` with each loop started at the coedge that makes its sequence of
571/// `(pcurve identity, sense)` least (loop order kept): the same region, read
572/// from the same pcurves, whichever coedge a boolean happened to start the
573/// loop at. Borrowed when every loop already starts there.
574pub fn canonical_loops(face: &FaceRecord) -> std::borrow::Cow<'_, FaceRecord> {
575    let starts: Vec<usize> = face
576        .loops
577        .iter()
578        .map(|loop_record| {
579            let keys: Vec<([u64; 2], bool)> = loop_record
580                .coedges
581                .iter()
582                .map(|coedge| {
583                    let mut lane = super::identity::TwoLane::new();
584                    super::identity::hash_curve(&mut lane, &coedge.pcurve);
585                    (lane.finish(), coedge.forward)
586                })
587                .collect();
588            let n = keys.len();
589            (0..n)
590                .min_by(|&a, &b| (0..n).map(|k| keys[(a + k) % n]).cmp((0..n).map(|k| keys[(b + k) % n])))
591                .unwrap_or(0)
592        })
593        .collect();
594    if starts.iter().all(|&start| start == 0) {
595        return std::borrow::Cow::Borrowed(face);
596    }
597    let mut rotated = face.clone();
598    for (loop_record, start) in rotated.loops.iter_mut().zip(starts) {
599        loop_record.coedges.rotate_left(start);
600    }
601    std::borrow::Cow::Owned(rotated)
602}
603
604/// The key the sign certificate's memo holds `face`'s terms under: its content
605/// identity about its own volume reference (`reference` when it has none).
606pub fn sign_face_identity(face: &FaceRecord, reference: Vec3) -> [u64; 2] {
607    let local = face_volume_reference(face).unwrap_or(reference);
608    super::identity::face_contribution_identity(face, local)
609}
610
611/// The check mode of `BREP_SIGN_CANONICAL_LOOPS`: both certificates' verdicts,
612/// and per face the worst relative difference between its bounded terms read
613/// in the given and the canonical rotation (its contribution about the shell
614/// reference against the face's own magnitude, and its vector area).
615fn canonical_loops_check(solid: &BrepSolid, given: Option<f64>, canonical: Option<f64>) {
616    let (mut faces, mut rotated, mut worst_contribution, mut worst_area, mut unread) = (0usize, 0usize, 0.0f64, 0.0f64, 0usize);
617    let mut worst_face = String::from("-");
618    let mut worst_of_bound = 0.0f64;
619    // The certificate's margin is relative to the faces' summed magnitudes, so
620    // each face's difference is read against that too.
621    let (mut worst_absolute, mut total_magnitude) = (0.0f64, 0.0f64);
622    super::trimmed::with_straight_corrections_skipped(|| {
623        for shell in &solid.shells {
624            let Ok(reference) = shell_volume_reference(shell) else { continue };
625            for face in &shell.faces {
626                faces += 1;
627                if let Some(local) = face_volume_reference(face) {
628                    if let Ok(terms) = face_volume_terms_about(face, local) {
629                        let area = Vec3::new(terms[1], terms[2], terms[3]);
630                        total_magnitude += (terms[0] + local.sub(reference).dot(area)).abs();
631                    }
632                }
633                let canon = canonical_loops(face);
634                let std::borrow::Cow::Owned(canon) = canon else { continue };
635                rotated += 1;
636                let read = |face: &FaceRecord| {
637                    let local = face_volume_reference(face).unwrap_or(reference);
638                    let offset = local.sub(reference).length();
639                    let (terms, bound) = match bounded_face_terms(face, local) {
640                        Some((terms, per_offset, fixed, _)) => (terms, fixed + per_offset * offset),
641                        None => (face_volume_terms_about(face, local).ok()?, 0.0),
642                    };
643                    let area = Vec3::new(terms[1], terms[2], terms[3]);
644                    Some((terms[0] + local.sub(reference).dot(area), area, terms[0].abs() + offset * area.length(), bound))
645                };
646                match (read(face), read(&canon)) {
647                    (Some((c0, a0, m0, b0)), Some((c1, a1, m1, b1))) => {
648                        // Both readings leave the same region's corrections out and bound them:
649                        // their difference must lie inside the two bounds together.
650                        worst_of_bound = worst_of_bound.max((c0 - c1).abs() / (b0 + b1).max(f64::MIN_POSITIVE));
651                        worst_absolute = worst_absolute.max((c0 - c1).abs());
652                        let magnitude = m0.max(m1).max(f64::MIN_POSITIVE);
653                        let relative = (c0 - c1).abs() / magnitude;
654                        if relative > worst_contribution {
655                            worst_contribution = relative;
656                            let (closed_u, closed_v) = face.surface.closed_directions().unwrap_or((false, false));
657                            worst_face = format!(
658                                "{}:{}{}:loops{}",
659                                face.surface.analytic().map_or("freeform", |kind| kind.kind_label()).replace(' ', "_"),
660                                if closed_u { "U" } else { "u" },
661                                if closed_v { "V" } else { "v" },
662                                face.loops.len()
663                            );
664                        }
665                        worst_area = worst_area.max(a0.sub(a1).length() / a0.length().max(a1.length()).max(f64::MIN_POSITIVE));
666                    }
667                    _ => unread += 1,
668                }
669            }
670        }
671    });
672    let verdict = |value: Option<f64>| if value.is_some() { "certified" } else { "none" };
673    // Both certify, or both leave the sign to the reading: anything else is a
674    // disagreement to look at, though either outcome stays sound.
675    let agree = given.is_some() == canonical.is_some();
676    eprintln!(
677        "mass.sign_canonical_check{} given={} canonical={} faces={faces} rotated={rotated} unread={unread} worst_rel_contribution={worst_contribution:.3e} worst_rel_area={worst_area:.3e} worst_face={worst_face} difference_of_bound={worst_of_bound:.3e} difference_of_shell={:.3e} thread={}",
678        if agree { "" } else { " DISAGREE" },
679        verdict(given),
680        verdict(canonical),
681        worst_absolute / total_magnitude.max(f64::MIN_POSITIVE),
682        std::thread::current().name().unwrap_or("-"),
683    );
684}
685
686/// A face's bounded sign terms read about `from` (the canonical rotation's
687/// reference), restated about `to` (the given rotation's): the volume term moves
688/// by `(from - to) · area`, exactly as the divergence theorem moves it, and the
689/// correction bound is recomputed about `to` from the same control net and the
690/// same skipped measure (`per_offset = measure · n / 3`, `fixed = per_offset ·
691/// r`, with `(n, r)` the net's bounds about the point), so the certificate
692/// reads what the given rotation reads, to rounding.
693fn rebase_bounded(
694    surface: &crate::NurbsSurface,
695    from: Vec3,
696    to: Vec3,
697    (terms, per_offset, fixed, rounding): ([f64; 4], f64, f64, f64),
698) -> Option<([f64; 4], f64, f64, f64)> {
699    let terms = rebase_terms(from, to, terms);
700    if per_offset == 0.0 && fixed == 0.0 {
701        return Some((terms, 0.0, 0.0, rounding));
702    }
703    let (n_from, _) = surface_flux_bounds(surface, from)?;
704    let (n_to, r_to) = surface_flux_bounds(surface, to)?;
705    let measure = 3.0 * per_offset / n_from;
706    let per_offset = measure * n_to / 3.0;
707    let fixed = per_offset * r_to;
708    [per_offset, fixed].iter().all(|v| v.is_finite()).then_some((terms, per_offset, fixed, rounding))
709}
710
711/// Volume and vector-area terms about `from`, restated about `to`.
712fn rebase_terms(from: Vec3, to: Vec3, terms: [f64; 4]) -> [f64; 4] {
713    let area = Vec3::new(terms[1], terms[2], terms[3]);
714    [terms[0] + from.sub(to).dot(area), terms[1], terms[2], terms[3]]
715}
716
717fn sliver_bound_reading(solid: &BrepSolid, bar: f64, canonical: bool) -> Option<f64> {
718    if !bar.is_finite() {
719        return None;
720    }
721    let token = super::profile::begin("solid_sign_sliver_bound");
722    // `BREP_SIGN_PREFETCH`: a large solid's face terms start on idle threads;
723    // the loop below takes each finished one in place of computing it.
724    let mut prefetched = SignPrefetch::spawn(solid, canonical);
725    let outcome = super::trimmed::with_straight_corrections_skipped(|| -> Option<(f64, f64, f64, f64, [usize; 3])> {
726        let (mut reading, mut magnitude, mut bound, mut scale) = (0.0, 0.0, 0.0, 0.0);
727        let mut counts = [0usize; 3]; // exact terms held, bounded, integrated exactly
728        let mut slot = 0usize;
729        for shell in &solid.shells {
730            let reference = shell_volume_reference(shell).ok()?;
731            let (mut volume, mut compensation) = (0.0f64, 0.0f64);
732            for face in &shell.faces {
733                // The terms are read (and memoised) in the canonical rotation about its
734                // own reference, then restated about the given rotation's, so every
735                // number below is the given rotation's to rounding.
736                let given = face_volume_reference(face).unwrap_or(reference);
737                let held = if canonical { canonical_loops(face) } else { std::borrow::Cow::Borrowed(face) };
738                let read_face: &FaceRecord = &held;
739                let local = if canonical { face_volume_reference(read_face).unwrap_or(reference) } else { given };
740                let identity = super::identity::face_contribution_identity(read_face, local);
741                let moved = [local.x, local.y, local.z].map(f64::to_bits) != [given.x, given.y, given.z].map(f64::to_bits);
742                let offset = given.sub(reference);
743                let ready = prefetched.as_mut().and_then(|prefetched| prefetched.claim(slot));
744                slot += 1;
745                let (ready_bounded, ready_exact) = match ready {
746                    Some((bounded, exact)) => (Some(bounded), exact),
747                    None => (None, None),
748                };
749                let (terms, face_bound, face_scale) = match crate::reading_memo::peek_sign_terms(identity) {
750                    Some(terms) => {
751                        counts[0] += 1;
752                        let terms = terms?;
753                        (if moved { rebase_terms(local, given, terms) } else { terms }, 0.0, 0.0)
754                    }
755                    None => match crate::reading_memo::memoized_bounded_sign_terms(identity, || {
756                        prefetched_or(ready_bounded, || bounded_face_terms(read_face, local))
757                    }) {
758                        Some(bounded) => {
759                            counts[1] += 1;
760                            let (terms, per_offset, fixed, rounding) =
761                                if moved { rebase_bounded(&read_face.surface, local, given, bounded)? } else { bounded };
762                            (terms, fixed + per_offset * offset.length(), rounding)
763                        }
764                        None => {
765                            counts[2] += 1;
766                            let terms = crate::reading_memo::memoized_sign_terms(identity, || {
767                                prefetched_or(ready_exact, || face_volume_terms_about(read_face, local).ok())
768                            })?;
769                            (if moved { rebase_terms(local, given, terms) } else { terms }, 0.0, 0.0)
770                        }
771                    },
772                };
773                let area = Vec3::new(terms[1], terms[2], terms[3]);
774                let contribution = terms[0] + offset.dot(area);
775                magnitude += contribution.abs();
776                bound += face_bound;
777                scale += terms[0].abs() + offset.length() * area.length() + face_bound + face_scale * (1.0 + offset.length());
778                let next = volume + contribution;
779                if volume.abs() >= contribution.abs() {
780                    compensation += (volume - next) + contribution;
781                } else {
782                    compensation += (contribution - next) + volume;
783                }
784                volume = next;
785            }
786            reading += volume + compensation;
787        }
788        Some((reading, magnitude, bound, scale, counts))
789    });
790    super::profile::end(token);
791    if let Some(prefetched) = prefetched {
792        prefetched.report();
793    }
794    let (reading, magnitude, bound, scale, counts) = outcome?;
795    // Rounding: the reading adds each correction station to a running total
796    // the cells started, and the certificate does not; a face's stations number
797    // well under 1e6, so their re-association moves a slot by far less than
798    // 1e-9 of the face's scale.
799    let slack = 1e-9 * scale;
800    let lower = reading - bound - slack;
801    let certified = [reading, magnitude, bound, scale, lower].iter().all(|v| v.is_finite())
802        && lower > bar
803        && lower - bar > SIGN_READING_MARGIN * (magnitude + bound + slack);
804    if crate::profile::profile_enabled() {
805        profile_line!(
806            "mass.sign_certificate kind=sliver_bound certified={certified} cells={reading:.9e} bound={bound:.3e} slack={slack:.3e} magnitude={magnitude:.3e} held={} bounded={} exact={}",
807            counts[0], counts[1], counts[2]
808        );
809    }
810    certified.then_some(lower)
811}
812
813/// `BREP_SIGN_PREFETCH` (default on; `0` off, `check` compares): the sliver
814/// certificate's face terms for a solid of [`SIGN_PREFETCH_MIN_FACES`] or more
815/// faces are computed on idle pool threads ahead of its face loop
816/// ([`crate::claim_slots`]). Each helper computes exactly what the loop would
817/// on a memo miss — [`bounded_face_terms`], and [`face_volume_terms_about`]
818/// when that declines — under the same straight-chord flag, on a clone of the
819/// face, about the same local reference. The loop is unchanged: it consults
820/// the memos in the same order, and only where it would have computed a term
821/// does it take the helper's instead (or compute it, when the helper has not
822/// finished; it never waits). `check` computes every term on the loop as before
823/// and compares it with the helper's (`mass.sign_prefetch` under
824/// `BREP_PROFILE`). A helper's face-level profile counters are not added to
825/// the loop's `mass.profile` line.
826const SIGN_PREFETCH_MIN_FACES: usize = 64;
827
828fn sign_prefetch_mode() -> crate::env_read::Mode {
829    #[cfg(not(test))]
830    {
831        crate::mode_switch!("BREP_SIGN_PREFETCH", true)
832    }
833}
834
835
836type BoundedTerms = Option<([f64; 4], f64, f64, f64)>;
837type SignReady = (BoundedTerms, Option<Option<[f64; 4]>>);
838
839struct SignJob {
840    face: FaceRecord,
841    local: Vec3,
842}
843
844fn sign_job(job: SignJob) -> SignReady {
845    super::trimmed::with_straight_corrections_skipped(|| {
846        let bounded = bounded_face_terms(&job.face, job.local);
847        let exact = bounded.is_none().then(|| face_volume_terms_about(&job.face, job.local).ok());
848        (bounded, exact)
849    })
850}
851
852#[derive(Clone, Copy, Default)]
853struct SignPrefetchTally {
854    check: bool,
855    hits: usize,
856    compared: usize,
857    disagree: usize,
858}
859
860thread_local! {
861    /// The tally of the certificate loop running on this thread, if prefetched.
862    static SIGN_PREFETCH_TALLY: std::cell::Cell<Option<SignPrefetchTally>> = const { std::cell::Cell::new(None) };
863}
864
865struct SignPrefetch {
866    slots: crate::claim_slots::ClaimSlots<SignJob, SignReady>,
867    previous: Option<SignPrefetchTally>,
868}
869
870impl SignPrefetch {
871    fn spawn(solid: &BrepSolid, canonical: bool) -> Option<Self> {
872        let mode = sign_prefetch_mode();
873        let faces: usize = solid.shells.iter().map(|shell| shell.faces.len()).sum();
874        if mode == crate::env_read::Mode::Off
875            || faces < SIGN_PREFETCH_MIN_FACES
876            || !crate::claim_slots::helpers_available()
877        {
878            return None;
879        }
880        let mut jobs = Vec::with_capacity(faces);
881        for shell in &solid.shells {
882            let reference = shell_volume_reference(shell).ok()?;
883            for face in &shell.faces {
884                let face = if canonical { canonical_loops(face).into_owned() } else { face.clone() };
885                let local = face_volume_reference(&face).unwrap_or(reference);
886                jobs.push(SignJob { face, local });
887            }
888        }
889        let slots = crate::claim_slots::ClaimSlots::spawn(jobs, sign_job)?;
890        let tally = SignPrefetchTally { check: mode == crate::env_read::Mode::Check, ..Default::default() };
891        let previous = SIGN_PREFETCH_TALLY.with(|cell| cell.replace(Some(tally)));
892        Some(Self { slots, previous })
893    }
894
895    fn claim(&mut self, index: usize) -> Option<SignReady> {
896        self.slots.claim(index)
897    }
898
899    fn report(self) {
900        let tally = SIGN_PREFETCH_TALLY.with(|cell| cell.replace(self.previous)).unwrap_or_default();
901        if crate::profile::profile_enabled() {
902            profile_line!(
903                "mass.sign_prefetch faces={} check={} taken={} claimed={} hits={} compared={} disagree={}",
904                self.slots.len(),
905                u8::from(tally.check),
906                self.slots.taken,
907                self.slots.claimed,
908                tally.hits,
909                tally.compared,
910                tally.disagree
911            );
912        }
913    }
914}
915
916/// A helper's value when the loop holds one for this face, else `compute`;
917/// in check mode always `compute`, compared with the helper's to the bit
918/// (shortest round-trip rendering of every float).
919fn prefetched_or<T: std::fmt::Debug>(ready: Option<T>, compute: impl FnOnce() -> T) -> T {
920    let Some(value) = ready else {
921        return compute();
922    };
923    let check = SIGN_PREFETCH_TALLY.with(|cell| cell.get()).is_some_and(|tally| tally.check);
924    if !check {
925        SIGN_PREFETCH_TALLY.with(|cell| cell.set(cell.get().map(|mut tally| { tally.hits += 1; tally })));
926        return value;
927    }
928    let fresh = compute();
929    let agrees = format!("{fresh:?}") == format!("{value:?}");
930    SIGN_PREFETCH_TALLY.with(|cell| {
931        cell.set(cell.get().map(|mut tally| {
932            tally.compared += 1;
933            tally.disagree += usize::from(!agrees);
934            tally
935        }))
936    });
937    fresh
938}
939
940/// One face's sign terms with the chord corrections bounded, as
941/// `(terms, per_offset, fixed, rounding)`: the face's contribution about a
942/// shell reference `ref` lies within `fixed + per_offset · |local - ref|` of
943/// the reading's, and `rounding` is a scale for the certificate's slack.
944/// `None` when the face's route reads its own corrections, a bound is not
945/// finite, or the integration fails (the reading then integrates it).
946pub fn bounded_face_terms(face: &FaceRecord, local: Vec3) -> Option<([f64; 4], f64, f64, f64)> {
947    let (terms, measure) = super::trimmed::with_sliver_measure(|| face_volume_terms_about(face, local));
948    let terms = terms.ok()?;
949    if measure.declined || !terms.iter().all(|v| v.is_finite()) {
950        return None;
951    }
952    if measure.measure == 0.0 {
953        return Some((terms, 0.0, 0.0, measure.complement / 3.0));
954    }
955    let (n, r) = surface_flux_bounds(&face.surface, local)?;
956    let per_offset = measure.measure * n / 3.0;
957    let fixed = per_offset * r;
958    [per_offset, fixed].iter().all(|v| v.is_finite()).then_some((terms, per_offset, fixed, measure.complement / 3.0))
959}
960
961/// Bounds from the control net of `surface`, valid over its whole domain (and
962/// its periodic wraps): `n >= |S_u × S_v|` and `r >= |S - center|`.
963///
964/// With homogeneous controls `Q = (w (P - center), w)`, all weights positive:
965/// `S - center` is a convex combination of the `P - center`, so `r` is their
966/// largest length; the homogeneous derivative `A_u` is a convex combination
967/// of `p (Q_{i+1} - Q_i) / (u_{i+p+1} - u_{i+1})` (spline differentiation,
968/// partition of unity of the degree-lowered basis), so its point part and its
969/// weight part are at most the largest lengths of those differences' parts;
970/// and `S_u = (X_u - w_u (S - center)) / w` with `w >= ` the smallest weight.
971/// `None` for a non-positive or non-finite weight or control.
972pub fn surface_flux_bounds(surface: &crate::NurbsSurface, center: Vec3) -> Option<(f64, f64)> {
973    let net = &surface.control_points;
974    let rows = net.len();
975    let columns = net.first()?.len();
976    surface_flux_bounds_over(surface, center, 0..rows, 0..columns)
977}
978
979/// [`surface_flux_bounds`] over one knot span `[u_i, u_{i+1}) × [v_j,
980/// v_{j+1})`: there only the controls `i-p..=i` × `j-q..=j` carry basis
981/// weight (local support), so the same argument over that sub-net bounds
982/// `|S_u × S_v|` and `|S - center|` on the span. `None` for an index
983/// outside the net (the caller then takes the whole-net bound).
984pub fn surface_flux_bounds_on_span(surface: &crate::NurbsSurface, center: Vec3, span_u: usize, span_v: usize) -> Option<(f64, f64)> {
985    let (p, q) = (surface.degree_u, surface.degree_v);
986    if span_u < p || span_v < q {
987        return None;
988    }
989    surface_flux_bounds_over(surface, center, span_u - p..span_u + 1, span_v - q..span_v + 1)
990}
991
992fn surface_flux_bounds_over(
993    surface: &crate::NurbsSurface,
994    center: Vec3,
995    row_range: std::ops::Range<usize>,
996    column_range: std::ops::Range<usize>,
997) -> Option<(f64, f64)> {
998    let net = &surface.control_points;
999    let rows = net.len();
1000    let columns = net.first()?.len();
1001    if rows == 0 || columns == 0 || net.iter().any(|row| row.len() != columns)
1002        || row_range.is_empty() || column_range.is_empty() || row_range.end > rows || column_range.end > columns
1003    {
1004        return None;
1005    }
1006    let relative = |i: usize, j: usize| -> Option<[f64; 4]> {
1007        let q = net[i][j];
1008        let values = [q.x - center.x * q.w, q.y - center.y * q.w, q.z - center.z * q.w, q.w];
1009        (values.iter().all(|v| v.is_finite()) && q.w > 0.0).then_some(values)
1010    };
1011    let mut w_min = f64::INFINITY;
1012    let mut r = 0.0f64;
1013    for i in row_range.clone() {
1014        for j in column_range.clone() {
1015            let q = relative(i, j)?;
1016            w_min = w_min.min(q[3]);
1017            r = r.max((q[0] * q[0] + q[1] * q[1] + q[2] * q[2]).sqrt() / q[3]);
1018        }
1019    }
1020    // (largest |X_d|, largest |w_d|) in one parameter direction.
1021    let derivative = |along_u: bool| -> Option<(f64, f64)> {
1022        let (degree, knots, count, range) = if along_u {
1023            (surface.degree_u, &surface.knots_u, rows, row_range.clone())
1024        } else {
1025            (surface.degree_v, &surface.knots_v, columns, column_range.clone())
1026        };
1027        if knots.len() < count + degree + 1 {
1028            return None;
1029        }
1030        let (mut point, mut weight) = (0.0f64, 0.0f64);
1031        if degree == 0 {
1032            return Some((0.0, 0.0));
1033        }
1034        // The derivative's controls over the range: consecutive differences
1035        // of the controls in it (all of them for the whole net).
1036        for k in range.start..range.end.saturating_sub(1) {
1037            let span = knots[k + degree + 1] - knots[k + 1];
1038            if !(span > 0.0) {
1039                continue;
1040            }
1041            let factor = degree as f64 / span;
1042            let others = if along_u { column_range.clone() } else { row_range.clone() };
1043            for other in others {
1044                let (a, b) = if along_u {
1045                    (relative(k, other)?, relative(k + 1, other)?)
1046                } else {
1047                    (relative(other, k)?, relative(other, k + 1)?)
1048                };
1049                let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2], b[3] - a[3]];
1050                point = point.max(factor * (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt());
1051                weight = weight.max(factor * d[3].abs());
1052            }
1053        }
1054        Some((point, weight))
1055    };
1056    let (xu, wu) = derivative(true)?;
1057    let (xv, wv) = derivative(false)?;
1058    let su = (xu + wu * r) / w_min;
1059    let sv = (xv + wv * r) / w_min;
1060    let n = su * sv;
1061    // A little headroom for the evaluator's own rounding.
1062    let (n, r) = (n * (1.0 + 1e-9), r * (1.0 + 1e-9));
1063    (n.is_finite() && r.is_finite() && w_min.is_finite()).then_some((n, r))
1064}
1065
1066/// Retain the exact path's shell references and compensated face order.
1067/// Each face's volume flux is affine in the reference: retain its local
1068/// volume and vector area, then translate the term to the shell reference.
1069/// Unchanged faces survive both id renumbering and a moving shell reference.
1070fn solid_sign_terms_reading(solid: &BrepSolid) -> Result<(f64, f64), String> {
1071    super::trimmed::with_straight_corrections_skipped(|| {
1072        let (mut reading, mut magnitude) = (0.0, 0.0);
1073        for (shell_index, shell) in solid.shells.iter().enumerate() {
1074            let (volume, faces) = shell_volume_sign_reading(shell, shell_index)?;
1075            reading += volume;
1076            magnitude += faces;
1077        }
1078        Ok((reading, magnitude))
1079    })
1080}
1081
1082fn sign_terms_oracle_enabled() -> bool {
1083    switch!(live "BREP_SIGN_TERMS_ORACLE", false)
1084}
1085
1086/// Diagnostic census only; the shipped reading and the sphere certificate
1087/// stay unchanged. The cold oracle never uses the mass cache or reading memo.
1088fn verify_solid_sign_terms(solid: &BrepSolid) -> Result<(), String> {
1089    let token = super::profile::begin("solid_sign_terms_oracle");
1090    let reading = solid_sign_terms_reading(solid).map(|pair| pair.0);
1091    super::profile::end(token);
1092    check_sign_terms(solid, reading?)
1093}
1094
1095pub fn check_sign_terms(solid: &BrepSolid, reading: f64) -> Result<(), String> {
1096    let exact = solid_signed_volume_uncached(solid)?;
1097    let error = (reading - exact).abs();
1098    let bar = 1e-9 * exact.abs();
1099    if !reading.is_finite() || !exact.is_finite() || error > bar {
1100        return Err(format!("sign terms oracle: retained {reading:.17e}, whole-body {exact:.17e}, error {error:.3e} exceeds {bar:.3e}"));
1101    }
1102    super::profile::emit_sign_oracle(solid, reading, exact)?;
1103    Ok(())
1104}
1105
1106/// [`shell_signed_volume`]'s sum under the caller's correction policy, with
1107/// the sum of the face contributions' magnitudes beside it (the scale the
1108/// sign reading's margin is read against).
1109fn shell_volume_sign_reading(shell: &ShellRecord, shell_index: usize) -> Result<(f64, f64), String> {
1110    let reference = shell_volume_reference(shell)?;
1111    if crate::profile::profile_enabled() {
1112        profile_line!(
1113            "mass.sign_reference faces={} reference=({:.9},{:.9},{:.9})",
1114            shell.faces.len(), reference.x, reference.y, reference.z
1115        );
1116    }
1117    let mut volume = 0.0;
1118    let mut compensation = 0.0;
1119    let mut magnitude = 0.0;
1120    let face_lines = super::profile::face_lines_enabled();
1121    for (face_index, face) in shell.faces.iter().enumerate() {
1122        mass_profile(|p| p.faces += 1);
1123        let line_before = face_lines.then(super::profile::snapshot);
1124        let line_started = face_lines.then(Instant::now);
1125        // V_f(r) = V_f(a) + (a-r) · A_f / 3. Integrate both terms at
1126        // the SAME quadrature stations, including trim corrections. Using a
1127        // boundary-only vector area would miss the integrator's numerical
1128        // residual and could change the sign reading on inherited trims.
1129        // Anchor each face locally for accuracy far from the world origin.
1130        let local = face_volume_reference(face).unwrap_or(reference);
1131        let hash_started = super::profile::profile_started();
1132        let identity = super::identity::face_contribution_identity(face, local);
1133        let hash_ms = super::profile::elapsed_ms(hash_started);
1134        let mut reread = false;
1135        let terms = match crate::reading_memo::memoized_sign_terms(identity, || {
1136            reread = true;
1137            face_volume_terms_about(face, local).ok()
1138        }) {
1139            Some(terms) => terms,
1140            None => face_volume_terms_about(face, local)?,
1141        };
1142        let contribution = terms[0] + local.sub(reference).dot(Vec3::new(terms[1], terms[2], terms[3]));
1143        super::profile::sign_face(shell_index, face, reread, hash_ms);
1144        emit_face_line("shell_volume_sign_reading", shell_index, face_index, face, line_before, line_started);
1145        magnitude += contribution.abs();
1146        let next = volume + contribution;
1147        if volume.abs() >= contribution.abs() {
1148            compensation += (volume - next) + contribution;
1149        } else {
1150            compensation += (contribution - next) + volume;
1151        }
1152        volume = next;
1153    }
1154    Ok((volume + compensation, magnitude))
1155}
1156
1157pub fn solid_signed_volume_uncached(solid: &BrepSolid) -> Result<f64, String> {
1158    let mut volume = 0.0;
1159    for shell in &solid.shells {
1160        volume += shell_signed_volume(shell)?;
1161    }
1162    Ok(volume)
1163}
1164
1165pub fn shell_volume_reference(shell: &ShellRecord) -> Result<Vec3, String> {
1166    shell.faces.iter().find_map(face_volume_reference)
1167        .ok_or_else(|| "mass_properties: shell has no finite geometric reference".to_string())
1168}
1169
1170/// One finite authored point, with the same fallbacks as the exact integral.
1171pub fn face_volume_reference(face: &FaceRecord) -> Option<Vec3> {
1172    let finite = |point: Vec3| point.x.is_finite() && point.y.is_finite() && point.z.is_finite();
1173    if let Some(coedge) = face
1174        .loops
1175        .first()
1176        .and_then(|loop_record| loop_record.coedges.first())
1177    {
1178        if let Ok(domain) = coedge.pcurve.domain() {
1179            if let Ok(uv) = coedge.pcurve.evaluate(domain[0]) {
1180                if let Ok(point) = face.surface.evaluate(uv.x, uv.y) {
1181                    if finite(point) {
1182                        return Some(point);
1183                    }
1184                }
1185            }
1186        }
1187    }
1188    if let Ok((u_breaks, v_breaks)) = surface_breaks(&face.surface) {
1189        let u = 0.5 * (u_breaks[0] + u_breaks[u_breaks.len() - 1]);
1190        let v = 0.5 * (v_breaks[0] + v_breaks[v_breaks.len() - 1]);
1191        if let Ok(point) = face.surface.evaluate(u, v) {
1192            if finite(point) {
1193                return Some(point);
1194            }
1195        }
1196    }
1197    for row in &face.surface.control_points {
1198        for control in row {
1199            if let Ok(point) = control.point() {
1200                if finite(point) {
1201                    return Some(point);
1202                }
1203            }
1204        }
1205    }
1206    None
1207}
1208
1209/// Exact signed volume of one closed shell. Multi-shell tessellation uses this
1210/// to preserve the authored material orientation: exterior shells contribute
1211/// positively, while a void boundary contributes negatively.
1212pub fn shell_signed_volume(shell: &ShellRecord) -> Result<f64, String> {
1213    let reference = shell_volume_reference(shell)?;
1214
1215    // A closed shell's divergence-theorem volume is independent of origin,
1216    // but evaluating each face about the world origin can cancel enormous
1217    // translated face terms down to a tiny cavity volume. Anchor the
1218    // integrand on an authored boundary point and compensate the remaining
1219    // face sum so the sign is stable for small, far-translated shells.
1220    let mut volume = 0.0;
1221    let mut compensation = 0.0;
1222    let face_lines = super::profile::face_lines_enabled();
1223    for (face_index, face) in shell.faces.iter().enumerate() {
1224        mass_profile(|p| p.faces += 1);
1225        let line_before = face_lines.then(super::profile::snapshot);
1226        let line_started = face_lines.then(Instant::now);
1227        let contribution = face_volume_contribution_about(face, reference)?;
1228        emit_face_line(
1229            "shell_signed_volume",
1230            0,
1231            face_index,
1232            face,
1233            line_before,
1234            line_started,
1235        );
1236        let next = volume + contribution;
1237        if volume.abs() >= contribution.abs() {
1238            compensation += (volume - next) + contribution;
1239        } else {
1240            compensation += (contribution - next) + volume;
1241        }
1242        volume = next;
1243    }
1244    Ok(volume + compensation)
1245}
1246
1247/// Exact moments for affine faces via Green's theorem over the trim
1248/// pcurves: ∬ g du dv = ∮ G dv with G(u,v) = ∫ g dt.  On an affine carrier
1249/// every moment integrand is a low-degree polynomial, so the inner Gauss
1250/// antiderivative is exact and the boundary quadrature has the same quality
1251/// as `parameter_space_area` — no trim-polygon sampling error.  The loop
1252/// winding supplies the orientation sign, matching the affine volume path.
1253pub(super) fn affine_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
1254    let ku = crate::KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)?;
1255    let kv = crate::KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)?;
1256    let [u0, u1] = ku.domain();
1257    let [v0, v1] = kv.domain();
1258    let points = &face.surface.control_points;
1259    let p00 = points[0][0].point()?;
1260    let p10 = points[1][0].point()?;
1261    let p01 = points[0][1].point()?;
1262    let du = p10.sub(p00).scale(1.0 / (u1 - u0));
1263    let dv = p01.sub(p00).scale(1.0 / (v1 - v0));
1264    let weighted_normal = du.cross(dv);
1265    let g = |u: f64, v: f64| {
1266        let point = p00.add(du.scale(u - u0)).add(dv.scale(v - v0));
1267        integrand_value(kind, point, weighted_normal)
1268    };
1269    let inner = |u: f64, v: f64| {
1270        let half = (u - u0) * 0.5;
1271        let middle = (u + u0) * 0.5;
1272        let mut sum = 0.0;
1273        for index in 0..GAUSS_X.len() {
1274            sum += GAUSS_W[index] * g(middle + half * GAUSS_X[index], v);
1275        }
1276        sum * half
1277    };
1278    let mut total = 0.0;
1279    for loop_record in &face.loops {
1280        for coedge in &loop_record.coedges {
1281            for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
1282                // The inner antiderivative is a polynomial in u on an affine
1283                // carrier and is exact at any order; the boundary walk is the
1284                // pcurve's own, so it takes the pcurve's panels (`rule`).
1285                for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
1286                    for (parameter, weight) in panel.stations() {
1287                        let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
1288                        total += weight * inner(point.x, point.y) * tangent.y;
1289                    }
1290                }
1291            }
1292        }
1293    }
1294    // The loops closed as the area closes them (`closed_parameter_space_area`):
1295    // an open boundary integral moves with the uv origin. Along a straight
1296    // chord the integrand is a polynomial of degree at most four, which the
1297    // eight-station rule integrates exactly.
1298    for (end, start) in loop_closing_chords(face)? {
1299        let step = start.y - end.y;
1300        if step == 0.0 {
1301            continue;
1302        }
1303        for index in 0..GAUSS_X.len() {
1304            let fraction = 0.5 * (GAUSS_X[index] + 1.0);
1305            let u = end.x + (start.x - end.x) * fraction;
1306            let v = end.y + step * fraction;
1307            total += 0.5 * GAUSS_W[index] * inner(u, v) * step;
1308        }
1309    }
1310    Ok(total)
1311}
1312
1313pub fn face_moment(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
1314    if is_affine(&face.surface)? {
1315        return affine_moment(face, kind);
1316    }
1317    if let Some(values) = biperiodic_band_integral(face, &[kind])? {
1318        return Ok(values[0]);
1319    }
1320    if is_untrimmed(face)? {
1321        integrate_untrimmed(face, kind)
1322    } else {
1323        integrate_trimmed(face, kind)
1324    }
1325}
1326
1327/// Symmetric-matrix product `A[i][j] = M[k][i] * M[k][j]` reused by the Jacobi
1328/// sweep — kept tiny and explicit rather than pulling in a matrix crate.
1329pub fn mat3_mul(a: [[f64; 3]; 3], b: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
1330    let mut r = [[0.0f64; 3]; 3];
1331    for i in 0..3 {
1332        for j in 0..3 {
1333            for k in 0..3 {
1334                r[i][j] += a[i][k] * b[k][j];
1335            }
1336        }
1337    }
1338    r
1339}
1340
1341pub fn mat3_transpose(a: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
1342    let mut r = [[0.0f64; 3]; 3];
1343    for i in 0..3 {
1344        for j in 0..3 {
1345            r[i][j] = a[j][i];
1346        }
1347    }
1348    r
1349}
1350
1351/// Classic Jacobi eigenvalue iteration for a SYMMETRIC 3×3 matrix. Repeatedly
1352/// applies a Givens rotation in the plane of the largest off-diagonal element,
1353/// each rotation zeroing that element, until the matrix is diagonal to machine
1354/// precision. Returns `(eigenvalues, vectors)` where `vectors` holds the
1355/// eigenvectors as COLUMNS (`vectors[i][k]` is component `i` of eigenvector
1356/// `k`), unsorted. For a symmetric matrix Jacobi is unconditionally
1357/// convergent and the accumulated rotations stay orthonormal, so the columns
1358/// are mutually orthonormal by construction.
1359pub(super) fn jacobi_eigen_symmetric_3x3(matrix: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
1360    // Symmetrize defensively against tiny asymmetry from round-off upstream.
1361    let mut a = [
1362        [matrix[0][0], 0.0, 0.0],
1363        [0.0, matrix[1][1], 0.0],
1364        [0.0, 0.0, matrix[2][2]],
1365    ];
1366    a[0][1] = 0.5 * (matrix[0][1] + matrix[1][0]);
1367    a[1][0] = a[0][1];
1368    a[0][2] = 0.5 * (matrix[0][2] + matrix[2][0]);
1369    a[2][0] = a[0][2];
1370    a[1][2] = 0.5 * (matrix[1][2] + matrix[2][1]);
1371    a[2][1] = a[1][2];
1372
1373    let mut v = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
1374    let scale = a[0][0].abs() + a[1][1].abs() + a[2][2].abs() + 1.0;
1375    for _sweep in 0..64 {
1376        // Pick the largest off-diagonal magnitude.
1377        let pairs = [(0usize, 1usize), (0, 2), (1, 2)];
1378        let (mut p, mut q, mut best) = (0usize, 1usize, 0.0f64);
1379        for &(i, j) in &pairs {
1380            if a[i][j].abs() > best {
1381                best = a[i][j].abs();
1382                p = i;
1383                q = j;
1384            }
1385        }
1386        if best <= 1e-18 * scale {
1387            break;
1388        }
1389        // Angle that zeroes a[p][q]: t = tan(theta) is the smaller root of
1390        // t² + 2·theta·t − 1 = 0 with theta = (a_qq − a_pp)/(2 a_pq).
1391        let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
1392        let t = if theta == 0.0 {
1393            1.0
1394        } else {
1395            theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt())
1396        };
1397        let c = 1.0 / (t * t + 1.0).sqrt();
1398        let s = t * c;
1399        // Givens rotation J: J[p][p]=J[q][q]=c, J[p][q]=s, J[q][p]=−s.
1400        let mut j = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
1401        j[p][p] = c;
1402        j[q][q] = c;
1403        j[p][q] = s;
1404        j[q][p] = -s;
1405        // A ← Jᵀ A J   (drives a[p][q] to zero), V ← V J.
1406        a = mat3_mul(mat3_transpose(j), mat3_mul(a, j));
1407        v = mat3_mul(v, j);
1408    }
1409    ([a[0][0], a[1][1], a[2][2]], v)
1410}
1411
1412/// Principal axes/moments from a centroidal inertia tensor (Golovanov §8.11).
1413/// Diagonalizes the symmetric tensor, sorts the eigenpairs by moment
1414/// ASCENDING, returns each eigenvector as a ROW (`axes[i]` pairs with
1415/// `moments[i]`) normalized to unit length, and fixes the sign of the third
1416/// axis so the frame is right-handed (determinant +1).
1417pub fn principal_frame(inertia: [[f64; 3]; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
1418    let (values, vectors) = jacobi_eigen_symmetric_3x3(inertia);
1419    // Column k of `vectors` is the eigenvector for `values[k]`.
1420    let mut order = [0usize, 1, 2];
1421    order.sort_by(|&a, &b| values[a].total_cmp(&values[b]));
1422    let mut moments = [0.0f64; 3];
1423    let mut axes = [[0.0f64; 3]; 3];
1424    for (slot, &k) in order.iter().enumerate() {
1425        moments[slot] = values[k];
1426        let mut axis = [vectors[0][k], vectors[1][k], vectors[2][k]];
1427        let length = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
1428        if length > 0.0 {
1429            axis = [axis[0] / length, axis[1] / length, axis[2] / length];
1430        }
1431        axes[slot] = axis;
1432    }
1433    // Right-hand the frame: if axis0 × axis1 points opposite axis2, flip axis2.
1434    let cross = [
1435        axes[0][1] * axes[1][2] - axes[0][2] * axes[1][1],
1436        axes[0][2] * axes[1][0] - axes[0][0] * axes[1][2],
1437        axes[0][0] * axes[1][1] - axes[0][1] * axes[1][0],
1438    ];
1439    let det = cross[0] * axes[2][0] + cross[1] * axes[2][1] + cross[2] * axes[2][2];
1440    if det < 0.0 {
1441        axes[2] = [-axes[2][0], -axes[2][1], -axes[2][2]];
1442    }
1443    (moments, axes)
1444}
1445
1446/// Area, volume, centroid, and centroidal inertia (unit density).  Area and
1447/// volume use the same exact paths as `solid_mass_properties`; the moment
1448/// integrals use divergence-theorem surface quadrature (exact for untrimmed
1449/// spans, trim-polygon scanline accuracy for trimmed faces).
1450pub fn solid_mass_properties_full(solid: &BrepSolid) -> Result<FullMassProperties, String> {
1451    let base = solid_mass_properties(solid)?;
1452    let token = super::profile::begin("solid_mass_properties_full.moments");
1453    let result = solid_mass_properties_full_moments(solid, base);
1454    super::profile::end(token);
1455    result
1456}
1457
1458/// `BREP_MASS_MOMENT_BAND_ROUTE` (default on; `=0` restores the old route): the moment
1459/// integrals take the bi-periodic band route first, as the area and volume
1460/// read in [`solid_mass_properties_inner`] and [`face_moment`] already do.
1461/// Without it a trimmed torus band (two rim loops round the carrier) goes
1462/// straight to the trimmed cell walk, whose raw polygons collapse to a sliver
1463/// on such a band: the face's moments read about zero while its volume reads
1464/// in full, so the centroid is off and moves by a multiple of any
1465/// translation (a 107-face part with three such bands: 2.4e-3 of the offset
1466/// along x and z, and hundreds of millimetres along the torus axis at 1000).
1467pub fn moment_band_route_on() -> bool {
1468    crate::switch!("BREP_MASS_MOMENT_BAND_ROUTE", true)
1469}
1470
1471/// `BREP_MASS_MOMENT_LOCAL_FRAME` (default on; `=0` reads about the world origin): the
1472/// first and second moments are read about a point of the body instead of
1473/// the world origin. In the world frame a moment integrand grows with the
1474/// square of the distance, so a shell whose faces do not close exactly (an
1475/// imported tolerant body: net vector area 1.4e-4 mm² on a 78-face part)
1476/// moves its centroid by `t²/2 · Σn / V` under a translation `t` (0.11 mm at
1477/// 1000 on that part), and the inertia's parallel-axis step cancels digits.
1478/// About a point that moves with the body, both are translation invariant.
1479pub fn moment_local_frame_on() -> bool {
1480    crate::switch!("BREP_MASS_MOMENT_LOCAL_FRAME", true)
1481}
1482
1483fn solid_mass_properties_full_moments(
1484    solid: &BrepSolid,
1485    base: MassProperties,
1486) -> Result<FullMassProperties, String> {
1487    const MOMENT_KINDS: [Integrand; 9] = [
1488        Integrand::MomentX,
1489        Integrand::MomentY,
1490        Integrand::MomentZ,
1491        Integrand::SecondXX,
1492        Integrand::SecondYY,
1493        Integrand::SecondZZ,
1494        Integrand::ProductXY,
1495        Integrand::ProductXZ,
1496        Integrand::ProductYZ,
1497    ];
1498    // `BREP_MASS_MOMENT_LOCAL_FRAME`: every moment about one point of the
1499    // body (the first non-empty shell's volume reference, the point the
1500    // volume is read about), and the centroid that point plus the local one.
1501    let origin = if moment_local_frame_on() {
1502        solid.shells.iter().find(|shell| !shell.faces.is_empty()).map(shell_volume_reference).transpose()?
1503    } else {
1504        None
1505    };
1506    let local_kinds = origin.map(|r| {
1507        [
1508            Integrand::MomentAbout(0, r),
1509            Integrand::MomentAbout(1, r),
1510            Integrand::MomentAbout(2, r),
1511            Integrand::SecondAbout(0, r),
1512            Integrand::SecondAbout(1, r),
1513            Integrand::SecondAbout(2, r),
1514            Integrand::ProductAbout(0, r),
1515            Integrand::ProductAbout(1, r),
1516            Integrand::ProductAbout(2, r),
1517        ]
1518    });
1519    let kinds: &[Integrand; 9] = local_kinds.as_ref().unwrap_or(&MOMENT_KINDS);
1520    let mut moments = [0.0f64; 3];
1521    let mut seconds = [0.0f64; 3];
1522    let mut products = [0.0f64; 3];
1523    for shell in &solid.shells {
1524        for face in &shell.faces {
1525            mass_profile(|p| p.faces += 1);
1526            let band = if moment_band_route_on() {
1527                biperiodic_band_integral(face, kinds)?
1528            } else {
1529                None
1530            };
1531            let results = if let Some(values) = band {
1532                mass_profile(|p| p.route_biperiodic += 1);
1533                values
1534            } else if !is_affine(&face.surface)? && !is_untrimmed(face)? {
1535                mass_profile(|p| p.trimmed_faces += 1);
1536                // One cell decomposition, all nine moment integrands per
1537                // station, instead of nine full passes per face.
1538                integrate_trimmed_multi(face, kinds)?
1539            } else {
1540                kinds
1541                    .iter()
1542                    .map(|kind| face_moment(face, *kind))
1543                    .collect::<Result<Vec<_>, _>>()?
1544            };
1545            moments[0] += results[0];
1546            moments[1] += results[1];
1547            moments[2] += results[2];
1548            seconds[0] += results[3];
1549            seconds[1] += results[4];
1550            seconds[2] += results[5];
1551            products[0] += results[6];
1552            products[1] += results[7];
1553            products[2] += results[8];
1554        }
1555    }
1556    let volume = base.volume;
1557    if volume.abs() <= 1e-30 {
1558        return Err("solid_mass_properties_full: non-positive volume".into());
1559    }
1560    // The centroid in the frame the moments were read in (the world, or
1561    // about `origin`).
1562    let centroid = Vec3::new(
1563        moments[0] / volume,
1564        moments[1] / volume,
1565        moments[2] / volume,
1566    );
1567    // Inertia about the frame's origin, then parallel-axis down to the centroid.
1568    let ixx =
1569        seconds[1] + seconds[2] - volume * (centroid.y * centroid.y + centroid.z * centroid.z);
1570    let iyy =
1571        seconds[0] + seconds[2] - volume * (centroid.x * centroid.x + centroid.z * centroid.z);
1572    let izz =
1573        seconds[0] + seconds[1] - volume * (centroid.x * centroid.x + centroid.y * centroid.y);
1574    let ixy = -(products[0] - volume * centroid.x * centroid.y);
1575    let ixz = -(products[1] - volume * centroid.x * centroid.z);
1576    let iyz = -(products[2] - volume * centroid.y * centroid.z);
1577    let inertia = [[ixx, ixy, ixz], [ixy, iyy, iyz], [ixz, iyz, izz]];
1578    let (principal_moments, principal_axes) = principal_frame(inertia);
1579    let centroid = origin.map_or(centroid, |r| r.add(centroid));
1580    Ok(FullMassProperties {
1581        surface_area: base.surface_area,
1582        volume,
1583        centroid,
1584        inertia,
1585        principal_moments,
1586        principal_axes,
1587    })
1588}
1589
1590