Skip to main content

brep_kernel/props/mass_properties/
integration.rs

1pub(super) use crate::curve::interior_knots;
2use super::*;
3
4pub(crate) fn curve_breaks(curve: &NurbsCurve) -> Result<Vec<f64>, String> {
5    let [start, end] = curve.domain()?;
6    let mut result = vec![start];
7    result.extend(interior_knots(&curve.knots, curve.degree));
8    result.push(end);
9    Ok(result)
10}
11
12pub fn parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
13    let mut area = 0.0;
14    for loop_record in &face.loops {
15        for coedge in &loop_record.coedges {
16            for pair in curve_breaks(&coedge.pcurve)?.windows(2) {
17                for panel in rule::curve_panels(&coedge.pcurve, pair[0], pair[1])? {
18                    for (parameter, weight) in panel.stations() {
19                        let (point, tangent) = coedge.pcurve.deriv1(parameter)?;
20                        area += weight * 0.5 * (point.x * tangent.y - point.y * tangent.x);
21                    }
22                }
23            }
24        }
25    }
26    Ok(area)
27}
28
29/// The escape hatch for [`closed_parameter_space_area`]: `BREP_OPEN_PLANAR_LOOPS=1`
30/// reads every planar face's trim loops open again, as they were read before
31/// the closing chords, so the two readings are two cells of one binary.
32fn open_planar_loops() -> bool {
33    static OPEN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
34    *OPEN.get_or_init(|| std::env::var_os("BREP_OPEN_PLANAR_LOOPS").is_some())
35}
36
37/// Every straight uv chord that closes a trim loop of `face`: from where one
38/// coedge's pcurve ends to where the next one's begins, the last back to the
39/// first. A loop whose pcurves meet contributes chords of zero length.
40pub(super) fn loop_closing_chords(face: &FaceRecord) -> Result<Vec<(Vec3, Vec3)>, String> {
41    let mut chords = Vec::new();
42    if open_planar_loops() {
43        return Ok(chords);
44    }
45    for loop_record in &face.loops {
46        let count = loop_record.coedges.len();
47        for index in 0..count {
48            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
49            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
50            chords.push((
51                loop_record.coedges[index].pcurve.evaluate(end)?,
52                loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?,
53            ));
54        }
55    }
56    Ok(chords)
57}
58
59/// [`parameter_space_area`] with every trim loop CLOSED by its chords
60/// ([`loop_closing_chords`]). The mass lane of a planar face reads its area
61/// here.
62///
63/// `½∮(u dv − v du)` is independent of where the uv origin sits only over a
64/// closed path. Summed over pcurves whose ends miss one another by `δ`, it
65/// reads `½(e × δ)` too much or too little at each joint `e`, so the same
66/// region read about a translated parameterization gives a different area.
67/// The offset shell's planar faces carry such joints — the pcurve ends of the
68/// box-bore-sphere shells' opening cork miss their vertices by up to 5.6e-5
69/// while the 3D vertices are exact — and on `offsetShellProblem` that alone
70/// put the cork's area 6.680e-4 short and the solid's volume 4.453e-3 short of
71/// a kernel-free integral. Closed, the same face reads within 1e-8 of it.
72///
73/// The chord closes what the face record names. The curved lane's trim
74/// polygons close the same way, implicitly, which is why a curved face with
75/// the same gaps already read true. [`parameter_space_area`] itself stays
76/// OPEN: its other callers read its SIGN as a loop's winding, and on a
77/// periodic carrier a loop that wraps once is not closed in uv by design.
78pub(crate) fn closed_parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
79    let mut area = parameter_space_area(face)?;
80    for (end, start) in loop_closing_chords(face)? {
81        area += 0.5 * (end.x * start.y - start.x * end.y);
82    }
83    Ok(area)
84}
85
86/// The fraction of a face's own extent within which two parameter points are the SAME
87/// point of the carrier. It separates a SEAM — where a loop steps from one edge of the
88/// domain to the other and both parameters name one 3D point, so their evaluations agree
89/// to floating-point rounding — from a trim that misses its own joint.
90///
91/// Set from the separation the population shows, not picked: across 92,000 readings of
92/// this kernel's corpus and both suites, a seam or pole joint's two images agree to
93/// ~1e-14 of the face's extent, while the smallest real miss measured is 1.06e-7 — five
94/// orders above this bar, and a hundred above double-precision evaluation noise.
95const SEAM_COINCIDENCE_REL: f64 = 1e-12;
96
97/// [`parameter_space_area`] with every joint that MISSES closed by a chord, and every
98/// joint that steps across a SEAM left open — the reading a caller on a carrier that may
99/// be periodic or have a pole needs.
100///
101/// The affine lane closes every joint ([`closed_parameter_space_area`]) because a plane has
102/// neither. A general carrier has both: a loop that wraps a closed direction steps a whole
103/// period at one joint by design, and a chord there cancels the sweep — measured on the lib
104/// suite, such a reading collapses to 5e-17 — while a pole's degenerate edge steps a whole
105/// domain edge that is one point. Both are recognised the same way, and by GEOMETRY rather
106/// than by a flag: the two parameters name one point or they do not. `closed_directions()`
107/// is analytic-keyed and answers `false` for a FITTED periodic patch, which is exactly the
108/// carrier a flag-keyed test would mistake.
109///
110/// Nothing is evaluated for a joint whose pcurves meet exactly, which is all but 216 of the
111/// 15,443 calls one corpus replay makes through here.
112pub(crate) fn closed_parameter_space_area_on_carrier(face: &FaceRecord) -> Result<f64, String> {
113    let mut area = parameter_space_area(face)?;
114    let mut coincidence: Option<f64> = None;
115    for loop_record in &face.loops {
116        let count = loop_record.coedges.len();
117        for index in 0..count {
118            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
119            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
120            let here = loop_record.coedges[index].pcurve.evaluate(end)?;
121            let next = loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?;
122            if here.x == next.x && here.y == next.y {
123                continue;
124            }
125            let bar = *coincidence.get_or_insert_with(|| {
126                SEAM_COINCIDENCE_REL
127                    * crate::tolerance::model_scale(
128                        face.surface
129                            .control_points
130                            .iter()
131                            .flatten()
132                            .filter_map(|control| control.point().ok()),
133                    )
134            });
135            let (image_here, image_next) = (
136                face.surface.evaluate_extended(here.x, here.y)?,
137                face.surface.evaluate_extended(next.x, next.y)?,
138            );
139            if image_here.sub(image_next).length() <= bar {
140                continue;
141            }
142            area += 0.5 * (here.x * next.y - next.x * here.y);
143        }
144    }
145    Ok(area)
146}
147
148pub(super) fn is_affine(surface: &NurbsSurface) -> Result<bool, String> {
149    // Keep exact metric shortcuts consistent with geometry recognition.
150    surface.is_affine()
151}
152
153pub(crate) fn surface_breaks(surface: &NurbsSurface) -> Result<(Vec<f64>, Vec<f64>), String> {
154    let ku = crate::KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
155    let kv = crate::KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
156    let [u0, u1] = ku.domain();
157    let [v0, v1] = kv.domain();
158    let mut u = vec![u0];
159    u.extend(interior_knots(&surface.knots_u, surface.degree_u));
160    u.push(u1);
161    let mut v = vec![v0];
162    v.extend(interior_knots(&surface.knots_v, surface.degree_v));
163    v.push(v1);
164    Ok((u, v))
165}
166
167pub(super) fn integrand_value(kind: Integrand, point: Vec3, weighted_normal: Vec3) -> f64 {
168    let (x, y, z) = (point.x, point.y, point.z);
169    match kind {
170        Integrand::Area => weighted_normal.length(),
171        Integrand::Volume => point.dot(weighted_normal),
172        Integrand::VolumeAbout(reference) => point.sub(reference).dot(weighted_normal),
173        Integrand::MomentX => 0.5 * x * x * weighted_normal.x,
174        Integrand::MomentY => 0.5 * y * y * weighted_normal.y,
175        Integrand::MomentZ => 0.5 * z * z * weighted_normal.z,
176        Integrand::SecondXX => x * x * x / 3.0 * weighted_normal.x,
177        Integrand::SecondYY => y * y * y / 3.0 * weighted_normal.y,
178        Integrand::SecondZZ => z * z * z / 3.0 * weighted_normal.z,
179        Integrand::ProductXY => 0.5 * x * x * y * weighted_normal.x,
180        Integrand::ProductXZ => 0.5 * x * x * z * weighted_normal.x,
181        Integrand::ProductYZ => 0.5 * y * y * z * weighted_normal.y,
182    }
183}
184
185
186/// Stations per direction in a fixed tensor Gauss block.
187pub(super) const GAUSS_COUNT: usize = GAUSS_X.len();
188
189/// The tensor-block station evaluator is on unless `BREP_MASS_TENSOR_BLOCK=0`
190/// turns it off. It is bit-identical to the per-station path by construction
191/// (`NurbsSurface::deriv1_tensor_each`), so the switch buys nothing but a
192/// paired A/B timing of the two in ONE binary under ONE load — which is the
193/// only honest way to quote a speed-up on a box that runs eight agents.
194pub(super) fn tensor_blocks_on() -> bool {
195    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
196    *ON.get_or_init(|| std::env::var("BREP_MASS_TENSOR_BLOCK").as_deref() != Ok("0"))
197}
198
199/// Accumulate every `kind` over ONE parameter cell by tensor Gauss–Legendre,
200/// with every station's weight scaled — the trimmed path's full cells carry
201/// their winding and the sweep's orientation there. `scale` multiplies FIRST,
202/// as every call site has always written the product, so a cell read at the
203/// base rule is bit-identical to the one-block rule it replaces.
204///
205/// Identical arithmetic to the per-station loop it replaces (kept as the
206/// tests' reference sweep) — the same stations in the same i-outer/j-inner
207/// order, the same `weight_u * weight_v * half_u * half_v * value` product and
208/// the same running sum per slot — but each of the block's u and v
209/// spans/basis rows is evaluated ONCE rather than once per station it takes
210/// part in, which at the base rule is eight rows each instead of sixty-four
211/// evaluations.
212pub(super) fn integrate_cell_scaled(
213    face: &FaceRecord,
214    cell: [f64; 4],
215    scale: f64,
216    kinds: &[Integrand],
217    totals: &mut [f64],
218    rules: &mut rule::SurfaceRules,
219) -> Result<usize, String> {
220    // A rational carrier's cell is read on the panels and at the orders its
221    // own weights ask for (`rule`); a polynomial one keeps ONE base-order
222    // block over the whole cell.
223    let (u_panels, v_panels) = rules.panels(&face.surface, cell)?;
224    let mut stations = 0;
225    for u_panel in &u_panels {
226        for v_panel in &v_panels {
227            integrate_block(face, *u_panel, *v_panel, scale, kinds, totals)?;
228            stations += u_panel.order * v_panel.order;
229        }
230    }
231    Ok(stations)
232}
233
234/// One tensor Gauss block: every station of `u_panel × v_panel`, every kind.
235fn integrate_block(
236    face: &FaceRecord,
237    u_panel: rule::Panel,
238    v_panel: rule::Panel,
239    scale: f64,
240    kinds: &[Integrand],
241    totals: &mut [f64],
242) -> Result<(), String> {
243    let half_u = (u_panel.hi - u_panel.lo) * 0.5;
244    let middle_u = (u_panel.hi + u_panel.lo) * 0.5;
245    let half_v = (v_panel.hi - v_panel.lo) * 0.5;
246    let middle_v = (v_panel.hi + v_panel.lo) * 0.5;
247    let (u_x, u_w) = u_panel.nodes();
248    let (v_x, v_w) = v_panel.nodes();
249    let sign = if face.same_sense { 1.0 } else { -1.0 };
250    // The base rule, written against the fixed-size tables: its trip count is
251    // a constant the compiler unrolls, and reading the nodes through a slice
252    // of run-time length instead cost 0.28 µs a station on a 900 000-station
253    // import (measured 2026-09-15). Every polynomial carrier is on this path,
254    // and it is the arithmetic the one-block rule always did.
255    let base_rule = u_x.len() == GAUSS_COUNT && v_x.len() == GAUSS_COUNT;
256    if base_rule && tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
257        let mut u_stations = [0.0f64; GAUSS_COUNT];
258        let mut v_stations = [0.0f64; GAUSS_COUNT];
259        for index in 0..GAUSS_COUNT {
260            u_stations[index] = middle_u + half_u * GAUSS_X[index];
261            v_stations[index] = middle_v + half_v * GAUSS_X[index];
262        }
263        return face
264            .surface
265            .deriv1_tensor_each(&u_stations, &v_stations, |i, j, point, su, sv| {
266                let weighted_normal = su.cross(sv).scale(sign);
267                for (slot, kind) in kinds.iter().enumerate() {
268                    totals[slot] += scale
269                        * GAUSS_W[i]
270                        * GAUSS_W[j]
271                        * half_u
272                        * half_v
273                        * integrand_value(*kind, point, weighted_normal);
274                }
275                Ok(())
276            });
277    }
278    if base_rule && !face.surface.deriv1_tensor_supported() {
279        for i in 0..GAUSS_COUNT {
280            for j in 0..GAUSS_COUNT {
281                let (point, su, sv) = face
282                    .surface
283                    .deriv1(middle_u + half_u * GAUSS_X[i], middle_v + half_v * GAUSS_X[j])?;
284                let weighted_normal = su.cross(sv).scale(sign);
285                for (slot, kind) in kinds.iter().enumerate() {
286                    totals[slot] += scale
287                        * GAUSS_W[i]
288                        * GAUSS_W[j]
289                        * half_u
290                        * half_v
291                        * integrand_value(*kind, point, weighted_normal);
292                }
293            }
294        }
295        return Ok(());
296    }
297    if tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
298        let mut u_stations = [0.0f64; rule::MAX_ORDER];
299        let mut v_stations = [0.0f64; rule::MAX_ORDER];
300        for index in 0..u_x.len() {
301            u_stations[index] = middle_u + half_u * u_x[index];
302        }
303        for index in 0..v_x.len() {
304            v_stations[index] = middle_v + half_v * v_x[index];
305        }
306        return face.surface.deriv1_tensor_each(
307            &u_stations[..u_x.len()],
308            &v_stations[..v_x.len()],
309            |i, j, point, su, sv| {
310                let weighted_normal = su.cross(sv).scale(sign);
311                for (slot, kind) in kinds.iter().enumerate() {
312                    totals[slot] += scale
313                        * u_w[i]
314                        * v_w[j]
315                        * half_u
316                        * half_v
317                        * integrand_value(*kind, point, weighted_normal);
318                }
319                Ok(())
320            },
321        );
322    }
323    for i in 0..u_x.len() {
324        for j in 0..v_x.len() {
325            let (point, su, sv) = face
326                .surface
327                .deriv1(middle_u + half_u * u_x[i], middle_v + half_v * v_x[j])?;
328            let weighted_normal = su.cross(sv).scale(sign);
329            for (slot, kind) in kinds.iter().enumerate() {
330                totals[slot] += scale
331                    * u_w[i]
332                    * v_w[j]
333                    * half_u
334                    * half_v
335                    * integrand_value(*kind, point, weighted_normal);
336            }
337        }
338    }
339    Ok(())
340}
341
342/// Every `kind` over the whole (untrimmed) knot-span grid in ONE sweep.
343/// `solid_mass_properties` asks an untrimmed face for its area and its volume
344/// flux; two single-kind sweeps evaluated every station twice for a second
345/// integrand that costs a multiply.
346pub(super) fn integrate_untrimmed_multi(
347    face: &FaceRecord,
348    kinds: &[Integrand],
349) -> Result<Vec<f64>, String> {
350    let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
351    let mut totals = vec![0.0f64; kinds.len()];
352    let mut rules = rule::SurfaceRules::new(&face.surface)?;
353    for upair in u_breaks.windows(2) {
354        for vpair in v_breaks.windows(2) {
355            integrate_cell_scaled(
356                face,
357                [upair[0], upair[1], vpair[0], vpair[1]],
358                1.0,
359                kinds,
360                &mut totals,
361                &mut rules,
362            )?;
363        }
364    }
365    Ok(totals)
366}
367
368pub(super) fn integrate_untrimmed(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
369    Ok(integrate_untrimmed_multi(face, &[kind])?[0])
370}
371
372/// A bi-periodic band face (surface closed in both u and v, exactly two loops
373/// each a full-wrap constant-cross-level rim) whose trim is NOT expressed with a
374/// seam ruling — the fillet-torus bands OCC/STEP emit as two rim circles. Such a
375/// face integrates to ZERO on the trimmed path (both loops are degenerate iso
376/// lines in parameter space), so it is handled analytically over the seam-cut
377/// rectangle instead. See [`biperiodic_band_range`].
378#[derive(Clone, Copy)]
379pub(super) struct BiBand {
380    /// Which parameter is the periodic (full-wrap) one.
381    pub(super) p_is_u: bool,
382    /// The two rim cross-levels, ascending (q_lo <= q_hi) in the cross param.
383    pub(super) q_lo: f64,
384    pub(super) q_hi: f64,
385    /// True when the material band is the CROSS-SEAM COMPLEMENT of [q_lo, q_hi]
386    /// rather than the between-rims strip (mirrors the tessellator's
387    /// `close_periodic_trim_dir` orientation test).
388    pub(super) complement: bool,
389    /// The larger of the two rims' cross-parameter extents, as a fraction of
390    /// the cross domain. Zero (to double noise) for the rim circles OCC/STEP
391    /// emit as exact iso lines; a few 1e-3 for a rim PROJECTED from a vendor
392    /// 3D curve that sits off the carrier, whose pcurve then wanders in the
393    /// cross parameter. Decides between the seam-cut rectangle and the
394    /// rim-following strip — see [`biperiodic_band_integral`].
395    pub(super) rim_wobble: f64,
396}
397
398/// Above this fraction of the cross domain a rim is not an iso line, and the
399/// band between the rims is integrated along the rims' own pcurves instead
400/// of over the rectangle between their mean levels.
401///
402/// The bar is double noise, not a geometric tolerance: a rim that IS an iso
403/// line measures ~1e-15 here, and the two paths agree on it to quadrature
404/// precision, so nothing that reads exactly today moves. Set at 1e-9 rather
405/// than at the noise floor so a level rim of a large-domain surface is never
406/// pushed onto the pcurve walk by rounding alone. `importTestWorking`
407/// SOLID_03 face 90 (record `kernel-step-precision-and-importtestworking-
408/// 2026-09-12.md`): a torus fillet strip whose upper rim was projected from
409/// an edge 2.2e-3 mm off the torus wanders over v ∈ [0.746903, 0.750195] —
410/// 3.3e-3 of the period — and the rectangle at the mean level 0.748549 read
411/// the strip 9.67e-3 mm² (0.09%) small and its origin flux 0.388 low.
412pub(super) const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;
413
414/// Detect the bi-periodic band configuration of `face` and choose which of the
415/// two regions its rims bound is material. The choice replicates the watertight
416/// tessellator (`watertight_tessellation::close_periodic_trim_dir`): the
417/// material is to the LEFT of the boundary traversal, so the between-rims strip
418/// is kept unless the cross direction wraps AND the rim senses conclusively name
419/// the complement. Returns None for anything that is not a clean two-rim band.
420pub(super) fn biperiodic_band_range(face: &FaceRecord) -> Result<Option<BiBand>, String> {
421    let surface = &face.surface;
422    let (closed_u, closed_v) = surface.closed_directions()?;
423    if !(closed_u && closed_v) {
424        return Ok(None);
425    }
426    let [u0, u1] = surface.domain_u()?;
427    let [v0, v1] = surface.domain_v()?;
428    let u_span = (u1 - u0).abs().max(1e-30);
429    let v_span = (v1 - v0).abs().max(1e-30);
430    // Sample each loop's pcurves (in coedge/traversal order) into (u,v) points.
431    // A DEGENERATE loop — a pole/apex vertex whose whole trace collapses to one
432    // parameter point (a fat fillet torus touches its outer equator at a single
433    // seam point: ABC 00000039 faces 68/70) — is not a band boundary; drop it
434    // and keep the two real rims. Anything else leaves the band ambiguous.
435    let mut loop_points: Vec<Vec<[f64; 2]>> = Vec::with_capacity(2);
436    for loop_record in &face.loops {
437        let mut points = Vec::new();
438        for coedge in &loop_record.coedges {
439            let [d0, d1] = coedge.pcurve.domain()?;
440            // 32 per coedge: enough to see a projected rim wander, which a
441            // 12-sample read of a smooth pcurve could straddle.
442            let samples = 32;
443            for k in 0..=samples {
444                let t = d0 + (d1 - d0) * k as f64 / samples as f64;
445                let p = coedge.pcurve.evaluate(t)?;
446                points.push([p.x, p.y]);
447            }
448        }
449        if points.len() < 2 {
450            return Ok(None);
451        }
452        let (mut umin, mut umax, mut vmin, mut vmax) = (
453            f64::INFINITY,
454            f64::NEG_INFINITY,
455            f64::INFINITY,
456            f64::NEG_INFINITY,
457        );
458        for pt in &points {
459            umin = umin.min(pt[0]);
460            umax = umax.max(pt[0]);
461            vmin = vmin.min(pt[1]);
462            vmax = vmax.max(pt[1]);
463        }
464        if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
465            continue; // degenerate pole/apex loop
466        }
467        loop_points.push(points);
468    }
469    if loop_points.len() != 2 {
470        return Ok(None);
471    }
472    for p_is_u in [true, false] {
473        let (period, _p0, _p1) = if p_is_u {
474            (u1 - u0, u0, u1)
475        } else {
476            (v1 - v0, v0, v1)
477        };
478        let (q_dom_lo, q_dom_hi) = if p_is_u { (v0, v1) } else { (u0, u1) };
479        let q_extent = (q_dom_hi - q_dom_lo).abs().max(1e-30);
480        if !(period > 0.0) {
481            continue;
482        }
483        let coord = |pt: &[f64; 2]| -> (f64, f64) {
484            if p_is_u {
485                (pt[0], pt[1])
486            } else {
487                (pt[1], pt[0])
488            }
489        };
490        // (level, winding-direction) for each rim; None if any loop is not a
491        // clean full-wrap constant-cross-level rim in this p direction.
492        let mut rings: Vec<(f64, i32)> = Vec::with_capacity(2);
493        let mut clean = true;
494        let mut rim_wobble = 0.0f64;
495        for points in &loop_points {
496            let (mut pmin, mut pmax, mut qmin, mut qmax) = (
497                f64::INFINITY,
498                f64::NEG_INFINITY,
499                f64::INFINITY,
500                f64::NEG_INFINITY,
501            );
502            for pt in points {
503                let (p, q) = coord(pt);
504                pmin = pmin.min(p);
505                pmax = pmax.max(p);
506                qmin = qmin.min(q);
507                qmax = qmax.max(q);
508            }
509            if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
510                clean = false;
511                break;
512            }
513            rim_wobble = rim_wobble.max((qmax - qmin) / q_extent);
514            let mut net = 0.0;
515            for pair in points.windows(2) {
516                let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
517                if delta > 0.5 * period {
518                    delta -= period;
519                } else if delta < -0.5 * period {
520                    delta += period;
521                }
522                net += delta;
523            }
524            let direction = if net > 0.25 * period {
525                1
526            } else if net < -0.25 * period {
527                -1
528            } else {
529                0
530            };
531            rings.push((0.5 * (qmin + qmax), direction));
532        }
533        if !clean || rings.len() != 2 {
534            continue;
535        }
536        rings.sort_by(|a, b| a.0.total_cmp(&b.0));
537        let (q_lo, lower_dir) = rings[0];
538        let (q_hi, upper_dir) = rings[1];
539        let inconclusive = lower_dir == 0 || upper_dir == 0 || lower_dir == upper_dir;
540        let between_rims_is_ccw_uv = if p_is_u { lower_dir > 0 } else { lower_dir < 0 };
541        let complement = !inconclusive && between_rims_is_ccw_uv != face.same_sense;
542        return Ok(Some(BiBand {
543            p_is_u,
544            q_lo,
545            q_hi,
546            complement,
547            rim_wobble,
548        }));
549    }
550    Ok(None)
551}
552
553/// Gauss–Legendre integral of `kind` over the axis-aligned parameter rectangle
554/// [u_lo,u_hi]×[v_lo,v_hi], subdividing at knot spans clipped to the rectangle.
555pub(super) fn integrate_rectangle(
556    face: &FaceRecord,
557    u_lo: f64,
558    u_hi: f64,
559    v_lo: f64,
560    v_hi: f64,
561    kind: Integrand,
562) -> Result<f64, String> {
563    let (u_full, v_full) = surface_breaks(&face.surface)?;
564    let clamp = |breaks: &[f64], lo: f64, hi: f64| -> Vec<f64> {
565        let eps = 1e-9 * (hi - lo).abs().max(1e-30);
566        let mut out = vec![lo];
567        for &b in breaks {
568            if b > lo + eps && b < hi - eps {
569                out.push(b);
570            }
571        }
572        out.push(hi);
573        out
574    };
575    let u_breaks = clamp(&u_full, u_lo, u_hi);
576    let v_breaks = clamp(&v_full, v_lo, v_hi);
577    let mut totals = [0.0f64];
578    let mut rules = rule::SurfaceRules::new(&face.surface)?;
579    for upair in u_breaks.windows(2) {
580        for vpair in v_breaks.windows(2) {
581            integrate_cell_scaled(
582                face,
583                [upair[0], upair[1], vpair[0], vpair[1]],
584                1.0,
585                &[kind],
586                &mut totals,
587                &mut rules,
588            )?;
589        }
590    }
591    Ok(totals[0])
592}
593
594/// Integrate each of `kinds` over a bi-periodic band face, or return None when
595/// `face` is not such a band. The between-rims strip integrates over the full
596/// periodic span × the cross-level strip; the complement is the full-domain
597/// integral MINUS that strip (the two tile the closed cross period, so no
598/// domain-extended evaluation is needed).
599///
600/// Two readings of the strip. Rims that ARE iso lines (every rim circle a
601/// kernel-built or exactly exported torus carries) integrate over the
602/// seam-cut rectangle between their levels. A rim that wanders in the cross
603/// parameter — a pcurve PROJECTED from a vendor edge that sits off the
604/// carrier — is not at any one level, and the rectangle at its mean level
605/// mis-reads the strip by the wander times the rim length; such a band is
606/// integrated along the rims' own pcurves by the winding boundary integral
607/// (`∮ −G du`, [`super::winding::winding_loops_integral`]), which reads the
608/// trim exactly as given. The material choice (`complement`) is the same in
609/// both readings; only the strip's quadrature differs.
610pub(super) fn biperiodic_band_integral(
611    face: &FaceRecord,
612    kinds: &[Integrand],
613) -> Result<Option<Vec<f64>>, String> {
614    let Some(band) = biperiodic_band_range(face)? else {
615        return Ok(None);
616    };
617    let [u0, u1] = face.surface.domain_u()?;
618    let [v0, v1] = face.surface.domain_v()?;
619    let (u_lo, u_hi, v_lo, v_hi) = if band.p_is_u {
620        (u0, u1, band.q_lo, band.q_hi)
621    } else {
622        (band.q_lo, band.q_hi, v0, v1)
623    };
624    let strips: Vec<f64> = if band.rim_wobble <= BAND_RIM_LEVEL_TOLERANCE_REL {
625        kinds
626            .iter()
627            .map(|&kind| integrate_rectangle(face, u_lo, u_hi, v_lo, v_hi, kind))
628            .collect::<Result<_, _>>()?
629    } else {
630        super::winding::winding_loops_integral(face, kinds, band.p_is_u, 1)?
631    };
632    let mut out = Vec::with_capacity(kinds.len());
633    for (&kind, strip) in kinds.iter().zip(strips) {
634        let value = if band.complement {
635            integrate_untrimmed(face, kind)? - strip
636        } else {
637            strip
638        };
639        out.push(value);
640    }
641    Ok(Some(out))
642}