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: a torus fillet strip whose upper rim was projected from
408/// an edge 2.2e-3 mm off the torus wanders over v ∈ [0.746903, 0.750195] —
409/// 3.3e-3 of the period — and the rectangle at the mean level 0.748549 read
410/// the strip 9.67e-3 mm² (0.09%) small and its origin flux 0.388 low.
411pub(super) const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;
412
413/// Detect the bi-periodic band configuration of `face` and choose which of the
414/// two regions its rims bound is material. The choice replicates the watertight
415/// tessellator (`watertight_tessellation::close_periodic_trim_dir`): the
416/// material is to the LEFT of the boundary traversal, so the between-rims strip
417/// is kept unless the cross direction wraps AND the rim senses conclusively name
418/// the complement. Returns None for anything that is not a clean two-rim band.
419pub(super) fn biperiodic_band_range(face: &FaceRecord) -> Result<Option<BiBand>, String> {
420    let surface = &face.surface;
421    let (closed_u, closed_v) = surface.closed_directions()?;
422    if !(closed_u && closed_v) {
423        return Ok(None);
424    }
425    let [u0, u1] = surface.domain_u()?;
426    let [v0, v1] = surface.domain_v()?;
427    let u_span = (u1 - u0).abs().max(1e-30);
428    let v_span = (v1 - v0).abs().max(1e-30);
429    // Sample each loop's pcurves (in coedge/traversal order) into (u,v) points.
430    // A DEGENERATE loop — a pole/apex vertex whose whole trace collapses to one
431    // parameter point (a fat fillet torus touches its outer equator at a single
432    // seam point: ABC 00000039 faces 68/70) — is not a band boundary; drop it
433    // and keep the two real rims. Anything else leaves the band ambiguous.
434    let mut loop_points: Vec<Vec<[f64; 2]>> = Vec::with_capacity(2);
435    for loop_record in &face.loops {
436        let mut points = Vec::new();
437        for coedge in &loop_record.coedges {
438            let [d0, d1] = coedge.pcurve.domain()?;
439            // 32 per coedge: enough to see a projected rim wander, which a
440            // 12-sample read of a smooth pcurve could straddle.
441            let samples = 32;
442            for k in 0..=samples {
443                let t = d0 + (d1 - d0) * k as f64 / samples as f64;
444                let p = coedge.pcurve.evaluate(t)?;
445                points.push([p.x, p.y]);
446            }
447        }
448        if points.len() < 2 {
449            return Ok(None);
450        }
451        let (mut umin, mut umax, mut vmin, mut vmax) = (
452            f64::INFINITY,
453            f64::NEG_INFINITY,
454            f64::INFINITY,
455            f64::NEG_INFINITY,
456        );
457        for pt in &points {
458            umin = umin.min(pt[0]);
459            umax = umax.max(pt[0]);
460            vmin = vmin.min(pt[1]);
461            vmax = vmax.max(pt[1]);
462        }
463        if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
464            continue; // degenerate pole/apex loop
465        }
466        loop_points.push(points);
467    }
468    if loop_points.len() != 2 {
469        return Ok(None);
470    }
471    for p_is_u in [true, false] {
472        let (period, _p0, _p1) = if p_is_u {
473            (u1 - u0, u0, u1)
474        } else {
475            (v1 - v0, v0, v1)
476        };
477        let (q_dom_lo, q_dom_hi) = if p_is_u { (v0, v1) } else { (u0, u1) };
478        let q_extent = (q_dom_hi - q_dom_lo).abs().max(1e-30);
479        if !(period > 0.0) {
480            continue;
481        }
482        let coord = |pt: &[f64; 2]| -> (f64, f64) {
483            if p_is_u {
484                (pt[0], pt[1])
485            } else {
486                (pt[1], pt[0])
487            }
488        };
489        // (level, winding-direction) for each rim; None if any loop is not a
490        // clean full-wrap constant-cross-level rim in this p direction.
491        let mut rings: Vec<(f64, i32)> = Vec::with_capacity(2);
492        let mut clean = true;
493        let mut rim_wobble = 0.0f64;
494        for points in &loop_points {
495            let (mut pmin, mut pmax, mut qmin, mut qmax) = (
496                f64::INFINITY,
497                f64::NEG_INFINITY,
498                f64::INFINITY,
499                f64::NEG_INFINITY,
500            );
501            for pt in points {
502                let (p, q) = coord(pt);
503                pmin = pmin.min(p);
504                pmax = pmax.max(p);
505                qmin = qmin.min(q);
506                qmax = qmax.max(q);
507            }
508            if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
509                clean = false;
510                break;
511            }
512            rim_wobble = rim_wobble.max((qmax - qmin) / q_extent);
513            let mut net = 0.0;
514            for pair in points.windows(2) {
515                let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
516                if delta > 0.5 * period {
517                    delta -= period;
518                } else if delta < -0.5 * period {
519                    delta += period;
520                }
521                net += delta;
522            }
523            let direction = if net > 0.25 * period {
524                1
525            } else if net < -0.25 * period {
526                -1
527            } else {
528                0
529            };
530            rings.push((0.5 * (qmin + qmax), direction));
531        }
532        if !clean || rings.len() != 2 {
533            continue;
534        }
535        rings.sort_by(|a, b| a.0.total_cmp(&b.0));
536        let (q_lo, lower_dir) = rings[0];
537        let (q_hi, upper_dir) = rings[1];
538        let inconclusive = lower_dir == 0 || upper_dir == 0 || lower_dir == upper_dir;
539        let between_rims_is_ccw_uv = if p_is_u { lower_dir > 0 } else { lower_dir < 0 };
540        let complement = !inconclusive && between_rims_is_ccw_uv != face.same_sense;
541        return Ok(Some(BiBand {
542            p_is_u,
543            q_lo,
544            q_hi,
545            complement,
546            rim_wobble,
547        }));
548    }
549    Ok(None)
550}
551
552/// Gauss–Legendre integral of `kind` over the axis-aligned parameter rectangle
553/// [u_lo,u_hi]×[v_lo,v_hi], subdividing at knot spans clipped to the rectangle.
554pub(super) fn integrate_rectangle(
555    face: &FaceRecord,
556    u_lo: f64,
557    u_hi: f64,
558    v_lo: f64,
559    v_hi: f64,
560    kind: Integrand,
561) -> Result<f64, String> {
562    let (u_full, v_full) = surface_breaks(&face.surface)?;
563    let clamp = |breaks: &[f64], lo: f64, hi: f64| -> Vec<f64> {
564        let eps = 1e-9 * (hi - lo).abs().max(1e-30);
565        let mut out = vec![lo];
566        for &b in breaks {
567            if b > lo + eps && b < hi - eps {
568                out.push(b);
569            }
570        }
571        out.push(hi);
572        out
573    };
574    let u_breaks = clamp(&u_full, u_lo, u_hi);
575    let v_breaks = clamp(&v_full, v_lo, v_hi);
576    let mut totals = [0.0f64];
577    let mut rules = rule::SurfaceRules::new(&face.surface)?;
578    for upair in u_breaks.windows(2) {
579        for vpair in v_breaks.windows(2) {
580            integrate_cell_scaled(
581                face,
582                [upair[0], upair[1], vpair[0], vpair[1]],
583                1.0,
584                &[kind],
585                &mut totals,
586                &mut rules,
587            )?;
588        }
589    }
590    Ok(totals[0])
591}
592
593/// Integrate each of `kinds` over a bi-periodic band face, or return None when
594/// `face` is not such a band. The between-rims strip integrates over the full
595/// periodic span × the cross-level strip; the complement is the full-domain
596/// integral MINUS that strip (the two tile the closed cross period, so no
597/// domain-extended evaluation is needed).
598///
599/// Two readings of the strip. Rims that ARE iso lines (every rim circle a
600/// kernel-built or exactly exported torus carries) integrate over the
601/// seam-cut rectangle between their levels. A rim that wanders in the cross
602/// parameter — a pcurve PROJECTED from a vendor edge that sits off the
603/// carrier — is not at any one level, and the rectangle at its mean level
604/// mis-reads the strip by the wander times the rim length; such a band is
605/// integrated along the rims' own pcurves by the winding boundary integral
606/// (`∮ −G du`, [`super::winding::winding_loops_integral`]), which reads the
607/// trim exactly as given. The material choice (`complement`) is the same in
608/// both readings; only the strip's quadrature differs.
609pub(super) fn biperiodic_band_integral(
610    face: &FaceRecord,
611    kinds: &[Integrand],
612) -> Result<Option<Vec<f64>>, String> {
613    let Some(band) = biperiodic_band_range(face)? else {
614        return Ok(None);
615    };
616    let [u0, u1] = face.surface.domain_u()?;
617    let [v0, v1] = face.surface.domain_v()?;
618    let (u_lo, u_hi, v_lo, v_hi) = if band.p_is_u {
619        (u0, u1, band.q_lo, band.q_hi)
620    } else {
621        (band.q_lo, band.q_hi, v0, v1)
622    };
623    let strips: Vec<f64> = if band.rim_wobble <= BAND_RIM_LEVEL_TOLERANCE_REL {
624        kinds
625            .iter()
626            .map(|&kind| integrate_rectangle(face, u_lo, u_hi, v_lo, v_hi, kind))
627            .collect::<Result<_, _>>()?
628    } else {
629        super::winding::winding_loops_integral(face, kinds, band.p_is_u, 1)?
630    };
631    let mut out = Vec::with_capacity(kinds.len());
632    for (&kind, strip) in kinds.iter().zip(strips) {
633        let value = if band.complement {
634            integrate_untrimmed(face, kind)? - strip
635        } else {
636            strip
637        };
638        out.push(value);
639    }
640    Ok(Some(out))
641}