Skip to main content

brep_topology/props/mass_properties/
integration.rs

1pub(super) use crate::curve::interior_knots;
2use super::*;
3
4pub 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/// One pcurve's share of [`parameter_space_area`]: each quadrature station's term, in the
30/// order the sum adds them.
31fn pcurve_area_terms(pcurve: &NurbsCurve) -> Result<Vec<f64>, String> {
32    let mut terms = Vec::new();
33    for pair in curve_breaks(pcurve)?.windows(2) {
34        for panel in rule::curve_panels(pcurve, pair[0], pair[1])? {
35            for (parameter, weight) in panel.stations() {
36                let (point, tangent) = pcurve.deriv1(parameter)?;
37                terms.push(weight * 0.5 * (point.x * tangent.y - point.y * tangent.x));
38            }
39        }
40    }
41    Ok(terms)
42}
43
44/// Station terms of the pcurves read so far, keyed by each pcurve's content, for a caller
45/// that reads [`parameter_space_area`] again and again on faces that change a few pcurves
46/// at a time ([`parameter_space_area_with`]). Hold one for one task; it is not bounded.
47#[derive(Default)]
48pub struct AreaTerms {
49    terms: rustc_hash::FxHashMap<[u64; 2], std::rc::Rc<[f64]>>,
50}
51
52impl AreaTerms {
53    fn of(&mut self, pcurve: &NurbsCurve) -> Result<std::rc::Rc<[f64]>, String> {
54        let mut key = crate::identity_hash::TwoLane::new();
55        crate::identity_hash::hash_curve(&mut key, pcurve);
56        let key = key.finish();
57        if let Some(terms) = self.terms.get(&key) {
58            return Ok(terms.clone());
59        }
60        let terms: std::rc::Rc<[f64]> = pcurve_area_terms(pcurve)?.into();
61        self.terms.insert(key, terms.clone());
62        Ok(terms)
63    }
64}
65
66/// [`parameter_space_area`], bit for bit: the same terms added in the same order, each
67/// pcurve's terms computed once per content and read from `memo` after that.
68pub fn parameter_space_area_with(face: &FaceRecord, memo: &mut AreaTerms) -> Result<f64, String> {
69    let mut area = 0.0;
70    for loop_record in &face.loops {
71        for coedge in &loop_record.coedges {
72            for term in memo.of(&coedge.pcurve)?.iter() {
73                area += *term;
74            }
75        }
76    }
77    Ok(area)
78}
79
80/// The escape hatch for [`closed_parameter_space_area`]: `BREP_OPEN_PLANAR_LOOPS=1`
81/// reads every planar face's trim loops open again, as they were read before
82/// the closing chords, so the two readings are two cells of one binary.
83fn open_planar_loops() -> bool {
84    debug_flag!("BREP_OPEN_PLANAR_LOOPS")
85}
86
87/// Every straight uv chord that closes a trim loop of `face`: from where one
88/// coedge's pcurve ends to where the next one's begins, the last back to the
89/// first. A loop whose pcurves meet contributes chords of zero length.
90pub(super) fn loop_closing_chords(face: &FaceRecord) -> Result<Vec<(Vec3, Vec3)>, String> {
91    let mut chords = Vec::new();
92    if open_planar_loops() {
93        return Ok(chords);
94    }
95    for loop_record in &face.loops {
96        let count = loop_record.coedges.len();
97        for index in 0..count {
98            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
99            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
100            chords.push((
101                loop_record.coedges[index].pcurve.evaluate(end)?,
102                loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?,
103            ));
104        }
105    }
106    Ok(chords)
107}
108
109/// [`parameter_space_area`] with every trim loop CLOSED by its chords
110/// ([`loop_closing_chords`]). The mass lane of a planar face reads its area
111/// here.
112///
113/// `½∮(u dv − v du)` is independent of where the uv origin sits only over a
114/// closed path. Summed over pcurves whose ends miss one another by `δ`, it
115/// reads `½(e × δ)` too much or too little at each joint `e`, so the same
116/// region read about a translated parameterization gives a different area.
117/// The offset shell's planar faces carry such joints — the pcurve ends of the
118/// box-bore-sphere shells' opening cork miss their vertices by up to 5.6e-5
119/// while the 3D vertices are exact — and on `offsetShellProblem` that alone
120/// put the cork's area 6.680e-4 short and the solid's volume 4.453e-3 short of
121/// a kernel-free integral. Closed, the same face reads within 1e-8 of it.
122///
123/// The chord closes what the face record names. The curved lane's trim
124/// polygons close the same way, implicitly, which is why a curved face with
125/// the same gaps already read true. [`parameter_space_area`] itself stays
126/// OPEN: its other callers read its SIGN as a loop's winding, and on a
127/// periodic carrier a loop that wraps once is not closed in uv by design.
128pub fn closed_parameter_space_area(face: &FaceRecord) -> Result<f64, String> {
129    let mut area = parameter_space_area(face)?;
130    for (end, start) in loop_closing_chords(face)? {
131        area += 0.5 * (crate::polygon::area_term([end.x, end.y], [start.x, start.y]));
132    }
133    Ok(area)
134}
135
136/// The fraction of a face's own extent within which two parameter points are the SAME
137/// point of the carrier. It separates a SEAM — where a loop steps from one edge of the
138/// domain to the other and both parameters name one 3D point, so their evaluations agree
139/// to floating-point rounding — from a trim that misses its own joint.
140///
141/// Set from the separation the population shows, not picked: across 92,000 readings of
142/// this kernel's corpus and both suites, a seam or pole joint's two images agree to
143/// ~1e-14 of the face's extent, while the smallest real miss measured is 1.06e-7 — five
144/// orders above this bar, and a hundred above double-precision evaluation noise.
145const SEAM_COINCIDENCE_REL: f64 = 1e-12;
146
147/// [`parameter_space_area`] with every joint that MISSES closed by a chord, and every
148/// joint that steps across a SEAM left open — the reading a caller on a carrier that may
149/// be periodic or have a pole needs.
150///
151/// The affine lane closes every joint ([`closed_parameter_space_area`]) because a plane has
152/// neither. A general carrier has both: a loop that wraps a closed direction steps a whole
153/// period at one joint by design, and a chord there cancels the sweep — measured on the lib
154/// suite, such a reading collapses to 5e-17 — while a pole's degenerate edge steps a whole
155/// domain edge that is one point. Both are recognised the same way, and by GEOMETRY rather
156/// than by a flag: the two parameters name one point or they do not. `closed_directions()`
157/// is analytic-keyed and answers `false` for a FITTED periodic patch, which is exactly the
158/// carrier a flag-keyed test would mistake.
159///
160/// Nothing is evaluated for a joint whose pcurves meet exactly, which is all but 216 of the
161/// 15,443 calls one corpus replay makes through here.
162pub fn closed_parameter_space_area_on_carrier(face: &FaceRecord) -> Result<f64, String> {
163    let mut area = parameter_space_area(face)?;
164    let mut coincidence: Option<f64> = None;
165    for loop_record in &face.loops {
166        let count = loop_record.coedges.len();
167        for index in 0..count {
168            let [_, end] = loop_record.coedges[index].pcurve.domain()?;
169            let [start, _] = loop_record.coedges[(index + 1) % count].pcurve.domain()?;
170            let here = loop_record.coedges[index].pcurve.evaluate(end)?;
171            let next = loop_record.coedges[(index + 1) % count].pcurve.evaluate(start)?;
172            if here.x == next.x && here.y == next.y {
173                continue;
174            }
175            let bar = *coincidence.get_or_insert_with(|| {
176                SEAM_COINCIDENCE_REL
177                    * crate::tolerance::model_scale(
178                        face.surface
179                            .control_points
180                            .iter()
181                            .flatten()
182                            .filter_map(|control| control.point().ok()),
183                    )
184            });
185            let (image_here, image_next) = (
186                face.surface.evaluate_extended(here.x, here.y)?,
187                face.surface.evaluate_extended(next.x, next.y)?,
188            );
189            if image_here.sub(image_next).length() <= bar {
190                continue;
191            }
192            area += 0.5 * (crate::polygon::area_term([here.x, here.y], [next.x, next.y]));
193        }
194    }
195    Ok(area)
196}
197
198pub fn is_affine(surface: &NurbsSurface) -> Result<bool, String> {
199    // Keep exact metric shortcuts consistent with geometry recognition.
200    surface.is_affine()
201}
202
203pub fn surface_breaks(surface: &NurbsSurface) -> Result<(Vec<f64>, Vec<f64>), String> {
204    let ku = crate::KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
205    let kv = crate::KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
206    let [u0, u1] = ku.domain();
207    let [v0, v1] = kv.domain();
208    let mut u = vec![u0];
209    u.extend(interior_knots(&surface.knots_u, surface.degree_u));
210    u.push(u1);
211    let mut v = vec![v0];
212    v.extend(interior_knots(&surface.knots_v, surface.degree_v));
213    v.push(v1);
214    Ok((u, v))
215}
216
217pub fn integrand_value(kind: Integrand, point: Vec3, weighted_normal: Vec3) -> f64 {
218    let (x, y, z) = (point.x, point.y, point.z);
219    match kind {
220        Integrand::Area => weighted_normal.length(),
221        Integrand::Volume => point.dot(weighted_normal),
222        Integrand::VolumeAbout(reference) => point.sub(reference).dot(weighted_normal),
223        Integrand::NormalX => weighted_normal.x,
224        Integrand::NormalY => weighted_normal.y,
225        Integrand::NormalZ => weighted_normal.z,
226        Integrand::MomentX => 0.5 * x * x * weighted_normal.x,
227        Integrand::MomentY => 0.5 * y * y * weighted_normal.y,
228        Integrand::MomentZ => 0.5 * z * z * weighted_normal.z,
229        Integrand::SecondXX => x * x * x / 3.0 * weighted_normal.x,
230        Integrand::SecondYY => y * y * y / 3.0 * weighted_normal.y,
231        Integrand::SecondZZ => z * z * z / 3.0 * weighted_normal.z,
232        Integrand::ProductXY => 0.5 * x * x * y * weighted_normal.x,
233        Integrand::ProductXZ => 0.5 * x * x * z * weighted_normal.x,
234        Integrand::ProductYZ => 0.5 * y * y * z * weighted_normal.y,
235        Integrand::MomentAbout(axis, reference) => {
236            let d = point.sub(reference);
237            let (c, n) = component(d, weighted_normal, axis);
238            0.5 * c * c * n
239        }
240        Integrand::SecondAbout(axis, reference) => {
241            let d = point.sub(reference);
242            let (c, n) = component(d, weighted_normal, axis);
243            c * c * c / 3.0 * n
244        }
245        Integrand::ProductAbout(pair, reference) => {
246            let d = point.sub(reference);
247            match pair {
248                0 => 0.5 * d.x * d.x * d.y * weighted_normal.x,
249                1 => 0.5 * d.x * d.x * d.z * weighted_normal.x,
250                _ => 0.5 * d.y * d.y * d.z * weighted_normal.y,
251            }
252        }
253    }
254}
255
256/// The `axis` components (0 = x, 1 = y, otherwise z) of `d` and `n`.
257fn component(d: Vec3, n: Vec3, axis: usize) -> (f64, f64) {
258    match axis {
259        0 => (d.x, n.x),
260        1 => (d.y, n.y),
261        _ => (d.z, n.z),
262    }
263}
264
265
266/// Stations per direction in a fixed tensor Gauss block.
267pub const GAUSS_COUNT: usize = GAUSS_X.len();
268
269/// The tensor-block station evaluator is on unless `BREP_MASS_TENSOR_BLOCK=0`
270/// turns it off. It is bit-identical to the per-station path by construction
271/// (`NurbsSurface::deriv1_tensor_each`), so the switch buys nothing but a
272/// paired A/B timing of the two in ONE binary under ONE load — which is the
273/// only honest way to quote a speed-up on a box that runs eight agents.
274pub(super) fn tensor_blocks_on() -> bool {
275    switch!("BREP_MASS_TENSOR_BLOCK", true)
276}
277
278/// Accumulate every `kind` over ONE parameter cell by tensor Gauss–Legendre,
279/// with every station's weight scaled — the trimmed path's full cells carry
280/// their winding and the sweep's orientation there. `scale` multiplies FIRST,
281/// as every call site has always written the product, so a cell read at the
282/// base rule is bit-identical to the one-block rule it replaces.
283///
284/// Identical arithmetic to the per-station loop it replaces (kept as the
285/// tests' reference sweep) — the same stations in the same i-outer/j-inner
286/// order, the same `weight_u * weight_v * half_u * half_v * value` product and
287/// the same running sum per slot — but each of the block's u and v
288/// spans/basis rows is evaluated ONCE rather than once per station it takes
289/// part in, which at the base rule is eight rows each instead of sixty-four
290/// evaluations.
291pub fn integrate_cell_scaled(
292    face: &FaceRecord,
293    cell: [f64; 4],
294    scale: f64,
295    kinds: &[Integrand],
296    totals: &mut [f64],
297    rules: &mut rule::SurfaceRules,
298) -> Result<usize, String> {
299    // A rational carrier's cell is read on the panels and at the orders its
300    // own weights ask for (`rule`); a polynomial one keeps ONE base-order
301    // block over the whole cell.
302    let (u_panels, v_panels) = rules.panels(&face.surface, cell)?;
303    let area_slot = if area_adaptive_on() {
304        kinds.iter().position(|kind| matches!(kind, Integrand::Area))
305    } else {
306        None
307    };
308    let before = area_slot.map(|slot| totals[slot]);
309    let mut stations = 0;
310    for u_panel in &u_panels {
311        for v_panel in &v_panels {
312            integrate_block(face, *u_panel, *v_panel, scale, kinds, totals, rules.station_identity)?;
313            stations += u_panel.order * v_panel.order;
314        }
315    }
316    if let (Some(slot), Some(before)) = (area_slot, before) {
317        // The area integrand |S_u × S_v| is a square root: no fixed-order
318        // rule reads it exactly, polynomial carrier or not, so the cell's
319        // AREA alone is re-read adaptively and every other integrand keeps
320        // the reading above bit for bit.
321        let area = match rules.take_local_area_face(face) {
322            // `BREP_MASS_AREA_LOCAL_FRAME`: the same cell of the carrier
323            // translated to its own poles, read afresh there (the station
324            // memo is keyed by the untranslated carrier, so it is not asked).
325            Some(local) => {
326                let coarse = cell_area_reading(&local, cell, rules, None, &mut stations)?;
327                let area = adaptive_cell_area(&local, cell, coarse, rules, None, AREA_ADAPTIVE_DEPTH, &mut stations)?;
328                rules.restore_local_area_face(local);
329                area
330            }
331            None => {
332                let coarse = (totals[slot] - before) / scale;
333                let identity = rules.station_identity;
334                adaptive_cell_area(face, cell, coarse, rules, identity, AREA_ADAPTIVE_DEPTH, &mut stations)?
335            }
336        };
337        totals[slot] = before + scale * area;
338    }
339    Ok(stations)
340}
341
342/// `BREP_MASS_AREA_LOCAL_FRAME` (default on; `=0` restores the global-frame
343/// reading): the adaptive AREA re-read evaluates the carrier translated by
344/// [`local_frame_reference`] (the centre of its poles, where they stand away
345/// from the origin).
346///
347/// `|S_u × S_v|` does not depend on where the surface stands, but its
348/// reading does: the partials are sums of basis-weighted poles, and poles at
349/// a distance `D` from the origin leave about `D · ε` of rounding in a
350/// partial of the patch's own size. A unit fill patch at `x = 1e6` read its
351/// partials ~1e-10 off, ten times the refinement's 1e-11 agreement bar, so
352/// every knot cell was quartered to the depth cap (4^6 sub-cells): 16-18 s
353/// per three-patch fill face against ~4 ms at the origin, the same at
354/// `x = 1e5` (30 s a fill) and already 10x at `x = 1e4`. Translated, the
355/// rounding is that of the patch's own size and the bar is met where it is
356/// met at the origin. The bar itself is unchanged. Only the area is read
357/// there: every other integrand (volume, moments) depends on the frame and
358/// keeps its reading bit for bit.
359pub fn area_local_frame_on() -> bool {
360    switch!("BREP_MASS_AREA_LOCAL_FRAME", true)
361}
362
363/// `a - b` when it is exact in floating point (the TwoSum error term is
364/// zero), else `None`.
365fn exact_difference(a: f64, b: f64) -> Option<f64> {
366    let sum = a - b;
367    let virtual_b = sum - a;
368    let error = (a - (sum - virtual_b)) + (-b - virtual_b);
369    (sum.is_finite() && error == 0.0).then_some(sum)
370}
371
372/// `w · r` when the product is exact (its FMA residual is zero).
373fn exact_product(w: f64, r: f64) -> Option<f64> {
374    let product = w * r;
375    (product.is_finite() && w.mul_add(r, -product) == 0.0).then_some(product)
376}
377
378/// Where the area re-read stands the carrier of `face`: per coordinate, the
379/// centre of the poles rounded to a multiple of the power of two at or above
380/// their extent (a flat coordinate, extent 0, takes the centre itself), when
381/// the poles stand farther from the origin than they spread
382/// (`|centre| > extent`) AND every pole's homogeneous shift `x - w·r` is
383/// EXACT (the product by its FMA residual, the difference by TwoSum). So the
384/// translated carrier is the same surface moved by `r`, never a rounded
385/// copy: a carrier reaching from near the origin out to far coordinates
386/// keeps its frame (its small spans would not survive the move), and so does
387/// a weighted carrier whose `w·r` rounds (a generic weight times a far
388/// reference does), which is read in the global frame as before, correct and
389/// as slow as before. A unit-weight pole's shift is exact whenever it stands
390/// within a factor of two of `r` (Sterbenz). `None` when no coordinate moves,
391/// which leaves the reading as it was, bit for bit.
392pub(super) fn local_frame_reference(face: &FaceRecord) -> Option<Vec3> {
393    let poles = || face.surface.control_points.iter().flatten();
394    let mut low = [f64::INFINITY; 3];
395    let mut high = [f64::NEG_INFINITY; 3];
396    for pole in poles() {
397        if !(pole.w > 0.0) {
398            return None;
399        }
400        for (axis, value) in [pole.x, pole.y, pole.z].into_iter().enumerate() {
401            let value = value / pole.w;
402            low[axis] = low[axis].min(value);
403            high[axis] = high[axis].max(value);
404        }
405    }
406    let mut reference = [0.0f64; 3];
407    for axis in 0..3 {
408        let (centre, extent) = (0.5 * (low[axis] + high[axis]), high[axis] - low[axis]);
409        if !(centre.is_finite() && extent.is_finite()) || centre.abs() <= extent {
410            continue;
411        }
412        let candidate = if extent == 0.0 {
413            centre
414        } else {
415            let quantum = 2.0f64.powi(extent.log2().ceil() as i32);
416            (centre / quantum).round() * quantum
417        };
418        let exact = poles().all(|pole| {
419            exact_product(pole.w, candidate)
420                .and_then(|shift| exact_difference([pole.x, pole.y, pole.z][axis], shift))
421                .is_some()
422        });
423        if exact {
424            reference[axis] = candidate;
425        }
426    }
427    (reference != [0.0; 3]).then(|| Vec3::new(reference[0], reference[1], reference[2]))
428}
429
430/// `face` with its carrier translated by `-reference`: every homogeneous
431/// pole `(x - w·r, y - w·r, z - w·r, w)`, weights, knots, orientation and
432/// trims unchanged. `None` when the carrier refuses to rebuild.
433pub(super) fn translated_face(face: &FaceRecord, reference: Vec3) -> Option<FaceRecord> {
434    let surface = &face.surface;
435    let poles = surface
436        .control_points
437        .iter()
438        .map(|row| {
439            row.iter()
440                .map(|pole| crate::Vec4 {
441                    x: pole.x - pole.w * reference.x,
442                    y: pole.y - pole.w * reference.y,
443                    z: pole.z - pole.w * reference.z,
444                    w: pole.w,
445                })
446                .collect()
447        })
448        .collect();
449    let surface = crate::NurbsSurface::new(
450        surface.degree_u,
451        surface.degree_v,
452        surface.knots_u.clone(),
453        surface.knots_v.clone(),
454        poles,
455    )
456    .ok()?;
457    let mut local = face.clone();
458    local.surface = surface;
459    Some(local)
460}
461
462/// The area over `cell` (unscaled) on the cell's own panels.
463fn cell_area_reading(
464    face: &FaceRecord,
465    cell: [f64; 4],
466    rules: &mut rule::SurfaceRules,
467    station_identity: Option<[u64; 2]>,
468    stations: &mut usize,
469) -> Result<f64, String> {
470    let (u_panels, v_panels) = rules.panels(&face.surface, cell)?;
471    let mut area = [0.0f64];
472    for u_panel in &u_panels {
473        for v_panel in &v_panels {
474            integrate_block(face, *u_panel, *v_panel, 1.0, &[Integrand::Area], &mut area, station_identity)?;
475            *stations += u_panel.order * v_panel.order;
476        }
477    }
478    Ok(area[0])
479}
480
481/// `BREP_MASS_AREA_ADAPTIVE` (default on) re-reads each cell's AREA by quadrant
482/// refinement until a cell and its four quadrants agree to
483/// [`AREA_ADAPTIVE_TOLERANCE`] of the cell's own area. Default ON since the
484/// 2026-11-05 promotion (owner: accuracy beats speed); `=0` restores one
485/// fixed-rule reading per cell for every integrand.
486///
487/// brep-bench 2026-11-05: one 8-point block per knot cell read the degree-15
488/// Bézier dome's patch (`geometry/high-degree-bezier-dome`) 2.3e-5 small and
489/// the twisted sweep's degree 1×3 blade faces (`loft/twisted-thin-blade`)
490/// 1.7e-5 large, while their volumes were exact to round-off; refined, they
491/// read 1.6e-9 and 1.4e-7 of the closed forms.
492pub fn area_adaptive_on() -> bool {
493    switch!("BREP_MASS_AREA_ADAPTIVE", true)
494}
495
496/// How many times a cell may be quartered while its area is re-read.
497const AREA_ADAPTIVE_DEPTH: usize = 6;
498
499/// Relative agreement between a cell's area and the sum of its quadrants'
500/// that ends the refinement: a few hundred ulps of the cell's own area.
501const AREA_ADAPTIVE_TOLERANCE: f64 = 1e-11;
502
503/// The area over `cell` (unscaled), given the reading `coarse` of the whole
504/// cell: the four quadrants are read on their own panels, and any quadrant
505/// whose own refinement still moves is quartered again, to `depth` levels.
506fn adaptive_cell_area(
507    face: &FaceRecord,
508    cell: [f64; 4],
509    coarse: f64,
510    rules: &mut rule::SurfaceRules,
511    station_identity: Option<[u64; 2]>,
512    depth: usize,
513    stations: &mut usize,
514) -> Result<f64, String> {
515    if depth == 0 {
516        return Ok(coarse);
517    }
518    let [u_lo, u_hi, v_lo, v_hi] = cell;
519    let (u_mid, v_mid) = (0.5 * (u_lo + u_hi), 0.5 * (v_lo + v_hi));
520    let quadrants = [
521        [u_lo, u_mid, v_lo, v_mid],
522        [u_mid, u_hi, v_lo, v_mid],
523        [u_lo, u_mid, v_mid, v_hi],
524        [u_mid, u_hi, v_mid, v_hi],
525    ];
526    let mut readings = [0.0f64; 4];
527    for (index, quadrant) in quadrants.iter().enumerate() {
528        readings[index] = cell_area_reading(face, *quadrant, rules, station_identity, stations)?;
529    }
530    let fine: f64 = readings.iter().sum();
531    if (fine - coarse).abs() <= AREA_ADAPTIVE_TOLERANCE * fine.abs() {
532        return Ok(fine);
533    }
534    let mut total = 0.0;
535    for (index, quadrant) in quadrants.iter().enumerate() {
536        total += adaptive_cell_area(face, *quadrant, readings[index], rules, station_identity, depth - 1, stations)?;
537    }
538    Ok(total)
539}
540
541/// One tensor Gauss block: every station of `u_panel × v_panel`, every kind.
542/// The existing tensor rule without area refinement, for an interior cell
543/// of an extended trim. The covering-grid caller already used this rule;
544/// only repeated surface-basis evaluation is removed.
545pub(super) fn integrate_interior_cell_base(
546    face: &FaceRecord, cell: [f64; 4], scale: f64, kinds: &[Integrand],
547    totals: &mut [f64], rules: &mut rule::SurfaceRules,
548) -> Result<Option<usize>, String> {
549    let (us, vs) = rules.panels(&face.surface, cell)?;
550    if us.len() != 1 || vs.len() != 1 || us[0].order != GAUSS_COUNT || vs[0].order != GAUSS_COUNT {
551        return Ok(None);
552    }
553    integrate_block(face, us[0], vs[0], scale, kinds, totals, rules.station_identity)?;
554    Ok(Some(GAUSS_COUNT * GAUSS_COUNT))
555}
556
557fn integrate_block(
558    face: &FaceRecord,
559    u_panel: rule::Panel,
560    v_panel: rule::Panel,
561    scale: f64,
562    kinds: &[Integrand],
563    totals: &mut [f64],
564    station_identity: Option<[u64; 2]>,
565) -> Result<(), String> {
566    let half_u = (u_panel.hi - u_panel.lo) * 0.5;
567    let middle_u = (u_panel.hi + u_panel.lo) * 0.5;
568    let half_v = (v_panel.hi - v_panel.lo) * 0.5;
569    let middle_v = (v_panel.hi + v_panel.lo) * 0.5;
570    let (u_x, u_w) = u_panel.nodes();
571    let (v_x, v_w) = v_panel.nodes();
572    let sign = if face.same_sense { 1.0 } else { -1.0 };
573    // The base rule, written against the fixed-size tables: its trip count is
574    // a constant the compiler unrolls, and reading the nodes through a slice
575    // of run-time length instead cost 0.28 µs a station on a 900 000-station
576    // import (measured 2026-09-15). Every polynomial carrier is on this path,
577    // and it is the arithmetic the one-block rule always did.
578    let base_rule = u_x.len() == GAUSS_COUNT && v_x.len() == GAUSS_COUNT;
579    if base_rule && tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
580        let mut u_stations = [0.0f64; GAUSS_COUNT];
581        let mut v_stations = [0.0f64; GAUSS_COUNT];
582        for index in 0..GAUSS_COUNT {
583            u_stations[index] = middle_u + half_u * GAUSS_X[index];
584            v_stations[index] = middle_v + half_v * GAUSS_X[index];
585        }
586        return super::cell_memo::each(&face.surface, station_identity, &u_stations, &v_stations, |i, j, point, su, sv| {
587                let weighted_normal = su.cross(sv).scale(sign);
588                for (slot, kind) in kinds.iter().enumerate() {
589                    totals[slot] += scale
590                        * GAUSS_W[i]
591                        * GAUSS_W[j]
592                        * half_u
593                        * half_v
594                        * integrand_value(*kind, point, weighted_normal);
595                }
596                Ok(())
597            });
598    }
599    if base_rule && !face.surface.deriv1_tensor_supported() {
600        for i in 0..GAUSS_COUNT {
601            for j in 0..GAUSS_COUNT {
602                let (point, su, sv) = face
603                    .surface
604                    .deriv1(middle_u + half_u * GAUSS_X[i], middle_v + half_v * GAUSS_X[j])?;
605                let weighted_normal = su.cross(sv).scale(sign);
606                for (slot, kind) in kinds.iter().enumerate() {
607                    totals[slot] += scale
608                        * GAUSS_W[i]
609                        * GAUSS_W[j]
610                        * half_u
611                        * half_v
612                        * integrand_value(*kind, point, weighted_normal);
613                }
614            }
615        }
616        return Ok(());
617    }
618    if tensor_blocks_on() && face.surface.deriv1_tensor_supported() {
619        let mut u_stations = [0.0f64; rule::MAX_ORDER];
620        let mut v_stations = [0.0f64; rule::MAX_ORDER];
621        for index in 0..u_x.len() {
622            u_stations[index] = middle_u + half_u * u_x[index];
623        }
624        for index in 0..v_x.len() {
625            v_stations[index] = middle_v + half_v * v_x[index];
626        }
627        return super::cell_memo::each(
628            &face.surface, station_identity,
629            &u_stations[..u_x.len()],
630            &v_stations[..v_x.len()],
631            |i, j, point, su, sv| {
632                let weighted_normal = su.cross(sv).scale(sign);
633                for (slot, kind) in kinds.iter().enumerate() {
634                    totals[slot] += scale
635                        * u_w[i]
636                        * v_w[j]
637                        * half_u
638                        * half_v
639                        * integrand_value(*kind, point, weighted_normal);
640                }
641                Ok(())
642            },
643        );
644    }
645    for i in 0..u_x.len() {
646        for j in 0..v_x.len() {
647            let (point, su, sv) = face
648                .surface
649                .deriv1(middle_u + half_u * u_x[i], middle_v + half_v * v_x[j])?;
650            let weighted_normal = su.cross(sv).scale(sign);
651            for (slot, kind) in kinds.iter().enumerate() {
652                totals[slot] += scale
653                    * u_w[i]
654                    * v_w[j]
655                    * half_u
656                    * half_v
657                    * integrand_value(*kind, point, weighted_normal);
658            }
659        }
660    }
661    Ok(())
662}
663
664/// Every `kind` over the whole (untrimmed) knot-span grid in ONE sweep.
665/// `solid_mass_properties` asks an untrimmed face for its area and its volume
666/// flux; two single-kind sweeps evaluated every station twice for a second
667/// integrand that costs a multiply.
668pub fn integrate_untrimmed_multi(
669    face: &FaceRecord,
670    kinds: &[Integrand],
671) -> Result<Vec<f64>, String> {
672    let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
673    let mut totals = vec![0.0f64; kinds.len()];
674    let mut rules = rule::SurfaceRules::new(&face.surface)?;
675    for upair in u_breaks.windows(2) {
676        for vpair in v_breaks.windows(2) {
677            integrate_cell_scaled(
678                face,
679                [upair[0], upair[1], vpair[0], vpair[1]],
680                1.0,
681                kinds,
682                &mut totals,
683                &mut rules,
684            )?;
685        }
686    }
687    Ok(totals)
688}
689
690/// Every `kind` over the knot-span grid CLIPPED to `rectangle`
691/// (`[u_lo, u_hi, v_lo, v_hi]`, inside the domain): the untrimmed sweep's
692/// own rules on each cell's intersection with the rectangle, so a face whose
693/// single loop is an iso-rectangle (`polygons::iso_rectangle_trim`) is read
694/// without the trimmed route's chord polygons, cell quadtree and triangle
695/// cubature. Lane O, 2026-10-28: the filleted box's outward offset carried
696/// its quarter-cylinder image as such a face (the carrier extended past the
697/// walls, the trim v in [0.069, 0.931]) and the trimmed route spent 6.5 ms
698/// on 496 full cells and 31 744 stations for a one-span surface; this sweep
699/// reads it in a few stations per span.
700pub fn integrate_iso_rectangle_multi(
701    face: &FaceRecord,
702    rectangle: [f64; 4],
703    kinds: &[Integrand],
704) -> Result<Vec<f64>, String> {
705    let (u_breaks, v_breaks) = surface_breaks(&face.surface)?;
706    let mut totals = vec![0.0f64; kinds.len()];
707    let mut rules = rule::SurfaceRules::new(&face.surface)?;
708    for upair in u_breaks.windows(2) {
709        let (u_lo, u_hi) = (upair[0].max(rectangle[0]), upair[1].min(rectangle[1]));
710        if u_hi <= u_lo {
711            continue;
712        }
713        for vpair in v_breaks.windows(2) {
714            let (v_lo, v_hi) = (vpair[0].max(rectangle[2]), vpair[1].min(rectangle[3]));
715            if v_hi <= v_lo {
716                continue;
717            }
718            integrate_cell_scaled(face, [u_lo, u_hi, v_lo, v_hi], 1.0, kinds, &mut totals, &mut rules)?;
719        }
720    }
721    Ok(totals)
722}
723
724pub fn integrate_untrimmed(face: &FaceRecord, kind: Integrand) -> Result<f64, String> {
725    Ok(integrate_untrimmed_multi(face, &[kind])?[0])
726}
727
728/// A bi-periodic band face (surface closed in both u and v, exactly two loops
729/// each a full-wrap constant-cross-level rim) whose trim is NOT expressed with a
730/// seam ruling — the fillet-torus bands OCC/STEP emit as two rim circles. Such a
731/// face integrates to ZERO on the trimmed path (both loops are degenerate iso
732/// lines in parameter space), so it is handled analytically over the seam-cut
733/// rectangle instead. See [`biperiodic_band_range`].
734#[derive(Clone, Copy)]
735pub struct BiBand {
736    /// Which parameter is the periodic (full-wrap) one.
737    pub(super) p_is_u: bool,
738    /// The two rim cross-levels, ascending (q_lo <= q_hi) in the cross param.
739    pub q_lo: f64,
740    pub q_hi: f64,
741    /// True when the material band is the CROSS-SEAM COMPLEMENT of [q_lo, q_hi]
742    /// rather than the between-rims strip (mirrors the tessellator's
743    /// `close_periodic_trim_dir` orientation test).
744    pub(super) complement: bool,
745    /// The larger of the two rims' cross-parameter extents, as a fraction of
746    /// the cross domain. Zero (to double noise) for the rim circles OCC/STEP
747    /// emit as exact iso lines; a few 1e-3 for a rim PROJECTED from a vendor
748    /// 3D curve that sits off the carrier, whose pcurve then wanders in the
749    /// cross parameter. Decides between the seam-cut rectangle and the
750    /// rim-following strip — see [`biperiodic_band_integral`].
751    pub rim_wobble: f64,
752}
753
754/// Above this fraction of the cross domain a rim is not an iso line, and the
755/// band between the rims is integrated along the rims' own pcurves instead
756/// of over the rectangle between their mean levels.
757///
758/// The bar is double noise, not a geometric tolerance: a rim that IS an iso
759/// line measures ~1e-15 here, and the two paths agree on it to quadrature
760/// precision, so nothing that reads exactly today moves. Set at 1e-9 rather
761/// than at the noise floor so a level rim of a large-domain surface is never
762/// pushed onto the pcurve walk by rounding alone. `importTestWorking`
763/// SOLID_03 face 90: a torus fillet strip whose upper rim was projected from
764/// an edge 2.2e-3 mm off the torus wanders over v ∈ [0.746903, 0.750195] —
765/// 3.3e-3 of the period — and the rectangle at the mean level 0.748549 read
766/// the strip 9.67e-3 mm² (0.09%) small and its origin flux 0.388 low.
767pub const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;
768
769/// Detect the bi-periodic band configuration of `face` and choose which of the
770/// two regions its rims bound is material. The choice replicates the watertight
771/// tessellator (`watertight_tessellation::close_periodic_trim_dir`): the
772/// material is to the LEFT of the boundary traversal, so the between-rims strip
773/// is kept unless the cross direction wraps AND the rim senses conclusively name
774/// the complement. Returns None for anything that is not a clean two-rim band.
775pub fn biperiodic_band_range(face: &FaceRecord) -> Result<Option<BiBand>, String> {
776    let surface = &face.surface;
777    let (closed_u, closed_v) = surface.closed_directions()?;
778    if !(closed_u && closed_v) {
779        return Ok(None);
780    }
781    let [u0, u1] = surface.domain_u()?;
782    let [v0, v1] = surface.domain_v()?;
783    let u_span = (u1 - u0).abs().max(1e-30);
784    let v_span = (v1 - v0).abs().max(1e-30);
785    // Sample each loop's pcurves (in coedge/traversal order) into (u,v) points.
786    // A DEGENERATE loop — a pole/apex vertex whose whole trace collapses to one
787    // parameter point (a fat fillet torus touches its outer equator at a single
788    // seam point: ABC 00000039 faces 68/70) — is not a band boundary; drop it
789    // and keep the two real rims. Anything else leaves the band ambiguous.
790    let mut loop_points: Vec<Vec<[f64; 2]>> = Vec::with_capacity(2);
791    for loop_record in &face.loops {
792        let mut points = Vec::new();
793        for coedge in &loop_record.coedges {
794            let [d0, d1] = coedge.pcurve.domain()?;
795            // 32 per coedge: enough to see a projected rim wander, which a
796            // 12-sample read of a smooth pcurve could straddle.
797            let samples = 32;
798            for k in 0..=samples {
799                let t = d0 + (d1 - d0) * k as f64 / samples as f64;
800                let p = coedge.pcurve.evaluate(t)?;
801                points.push([p.x, p.y]);
802            }
803        }
804        if points.len() < 2 {
805            return Ok(None);
806        }
807        let (mut umin, mut umax, mut vmin, mut vmax) = (
808            f64::INFINITY,
809            f64::NEG_INFINITY,
810            f64::INFINITY,
811            f64::NEG_INFINITY,
812        );
813        for pt in &points {
814            umin = umin.min(pt[0]);
815            umax = umax.max(pt[0]);
816            vmin = vmin.min(pt[1]);
817            vmax = vmax.max(pt[1]);
818        }
819        if (umax - umin) <= 1e-3 * u_span && (vmax - vmin) <= 1e-3 * v_span {
820            continue; // degenerate pole/apex loop
821        }
822        loop_points.push(points);
823    }
824    if loop_points.len() != 2 {
825        return Ok(None);
826    }
827    for p_is_u in [true, false] {
828        let (period, _p0, _p1) = if p_is_u {
829            (u1 - u0, u0, u1)
830        } else {
831            (v1 - v0, v0, v1)
832        };
833        let (q_dom_lo, q_dom_hi) = if p_is_u { (v0, v1) } else { (u0, u1) };
834        let q_extent = (q_dom_hi - q_dom_lo).abs().max(1e-30);
835        if !(period > 0.0) {
836            continue;
837        }
838        let coord = |pt: &[f64; 2]| -> (f64, f64) {
839            if p_is_u {
840                (pt[0], pt[1])
841            } else {
842                (pt[1], pt[0])
843            }
844        };
845        // (level, winding-direction) for each rim; None if any loop is not a
846        // clean full-wrap constant-cross-level rim in this p direction.
847        let mut rings: Vec<(f64, i32)> = Vec::with_capacity(2);
848        let mut clean = true;
849        let mut rim_wobble = 0.0f64;
850        for points in &loop_points {
851            let (mut pmin, mut pmax, mut qmin, mut qmax) = (
852                f64::INFINITY,
853                f64::NEG_INFINITY,
854                f64::INFINITY,
855                f64::NEG_INFINITY,
856            );
857            for pt in points {
858                let (p, q) = coord(pt);
859                pmin = pmin.min(p);
860                pmax = pmax.max(p);
861                qmin = qmin.min(q);
862                qmax = qmax.max(q);
863            }
864            if (pmax - pmin) < 0.6 * period || (qmax - qmin) > 0.05 * q_extent {
865                clean = false;
866                break;
867            }
868            rim_wobble = rim_wobble.max((qmax - qmin) / q_extent);
869            let mut net = 0.0;
870            for pair in points.windows(2) {
871                let mut delta = coord(&pair[1]).0 - coord(&pair[0]).0;
872                if delta > 0.5 * period {
873                    delta -= period;
874                } else if delta < -0.5 * period {
875                    delta += period;
876                }
877                net += delta;
878            }
879            let direction = if net > 0.25 * period {
880                1
881            } else if net < -0.25 * period {
882                -1
883            } else {
884                0
885            };
886            rings.push((0.5 * (qmin + qmax), direction));
887        }
888        if !clean || rings.len() != 2 {
889            continue;
890        }
891        rings.sort_by(|a, b| a.0.total_cmp(&b.0));
892        let (q_lo, lower_dir) = rings[0];
893        let (q_hi, upper_dir) = rings[1];
894        let inconclusive = lower_dir == 0 || upper_dir == 0 || lower_dir == upper_dir;
895        let between_rims_is_ccw_uv = if p_is_u { lower_dir > 0 } else { lower_dir < 0 };
896        let complement = !inconclusive && between_rims_is_ccw_uv != face.same_sense;
897        return Ok(Some(BiBand {
898            p_is_u,
899            q_lo,
900            q_hi,
901            complement,
902            rim_wobble,
903        }));
904    }
905    Ok(None)
906}
907
908/// A bi-periodic band (two full-wrap rims) pierced by holes: a caster tread's
909/// slots, a signet ring's bore. [`biperiodic_band_range`] reads only a face of
910/// exactly two rims, so such a face fell to the trimmed path, where both rims
911/// are zero-area iso lines and only the holes were integrated (a caster's
912/// band read 680.8 for a numeric 1155.3). Read the band from its two rims as
913/// for a plain band, then take each hole away, integrated over its own
914/// polygon; a hole that straddles a seam is reconnected across it
915/// ([`crate::topology::loop_seam_offsets`]) and integrated through the
916/// domain-wrapping evaluator. None (the previous path) unless exactly two
917/// loops wind and every other loop is closed in parameter space.
918fn band_with_holes_integral(face: &FaceRecord, kinds: &[Integrand]) -> Result<Option<Vec<f64>>, String> {
919    let (closed_u, closed_v) = face.surface.closed_directions()?;
920    if !(closed_u && closed_v) {
921        return Ok(None);
922    }
923    let [u0, u1] = face.surface.domain_u()?;
924    let [v0, v1] = face.surface.domain_v()?;
925    let (u_span, v_span) = (u1 - u0, v1 - v0);
926    let mut rims = Vec::new();
927    let mut holes = Vec::new();
928    for (loop_index, loop_record) in face.loops.iter().enumerate() {
929        let (mut travel_u, mut travel_v) = (0.0, 0.0);
930        for coedge in &loop_record.coedges {
931            let [t0, t1] = coedge.pcurve.domain()?;
932            let (start, end) = (coedge.pcurve.evaluate(t0)?, coedge.pcurve.evaluate(t1)?);
933            travel_u += end.x - start.x;
934            travel_v += end.y - start.y;
935        }
936        let turns = |travel: f64, span: f64| {
937            let turns = (travel / span).round();
938            ((travel - turns * span).abs() <= 1e-3 * span.abs()).then_some(turns)
939        };
940        match (turns(travel_u, u_span), turns(travel_v, v_span)) {
941            (Some(tu), Some(tv)) if tu == 0.0 && tv == 0.0 => holes.push(loop_index),
942            (Some(tu), Some(tv)) if (tu == 0.0) != (tv == 0.0) => rims.push(loop_index),
943            _ => return Ok(None),
944        }
945    }
946    if rims.len() != 2 || holes.is_empty() {
947        return Ok(None);
948    }
949    let mut rim_face = face.clone();
950    rim_face.loops = rims.iter().map(|&index| face.loops[index].clone()).collect();
951    if biperiodic_band_range(&rim_face)?.is_none() {
952        return Ok(None);
953    }
954    let Some(band) = biperiodic_band_integral(&rim_face, kinds)? else {
955        return Ok(None);
956    };
957    let domain = [u0, u1, v0, v1];
958    let mut polygons = Vec::with_capacity(holes.len());
959    for &loop_index in &holes {
960        let coedges = &face.loops[loop_index].coedges;
961        let offsets = crate::topology::loop_seam_offsets(coedges, closed_u, closed_v, u_span, v_span)?;
962        let mut polygon = TrimPolygon::new(domain);
963        for (coedge_index, coedge) in coedges.iter().enumerate() {
964            polygon.push_coedge(loop_index, coedge_index, coedge, offsets[coedge_index])?;
965        }
966        polygon.finish();
967        // All holes one way round, so the integrator's orientation read
968        // (the sign of the summed area) holds for every one of them.
969        if polygon_signed_area(&polygon.points) < 0.0 {
970            polygon.reverse();
971        }
972        polygons.push(polygon);
973    }
974    // Past the domain by more than rounding, relative to each span: an
975    // absolute band would read a whole straddling hole on a tiny domain as
976    // in-domain and clip half of it away.
977    let (du, dv) = (1e-9 * u_span.abs(), 1e-9 * v_span.abs());
978    let extended = polygons.iter().flat_map(|polygon| polygon.points.iter()).any(|point| {
979        point[0] < u0 - du || point[0] > u1 + du || point[1] < v0 - dv || point[1] > v1 + dv
980    });
981    let removed = integrate_trimmed_polys(face, kinds, &polygons, extended, domain)?;
982    Ok(Some(band.iter().zip(removed).map(|(band, hole)| band - hole).collect()))
983}
984
985/// Gauss–Legendre integral of `kind` over the axis-aligned parameter rectangle
986/// \[u_lo,u_hi\]×\[v_lo,v_hi\], subdividing at knot spans clipped to the rectangle.
987pub fn integrate_rectangle(
988    face: &FaceRecord,
989    u_lo: f64,
990    u_hi: f64,
991    v_lo: f64,
992    v_hi: f64,
993    kind: Integrand,
994) -> Result<f64, String> {
995    let (u_full, v_full) = surface_breaks(&face.surface)?;
996    let clamp = |breaks: &[f64], lo: f64, hi: f64| -> Vec<f64> {
997        let eps = 1e-9 * (hi - lo).abs().max(1e-30);
998        let mut out = vec![lo];
999        for &b in breaks {
1000            if b > lo + eps && b < hi - eps {
1001                out.push(b);
1002            }
1003        }
1004        out.push(hi);
1005        out
1006    };
1007    let u_breaks = clamp(&u_full, u_lo, u_hi);
1008    let v_breaks = clamp(&v_full, v_lo, v_hi);
1009    let mut totals = [0.0f64];
1010    let mut rules = rule::SurfaceRules::new(&face.surface)?;
1011    for upair in u_breaks.windows(2) {
1012        for vpair in v_breaks.windows(2) {
1013            integrate_cell_scaled(
1014                face,
1015                [upair[0], upair[1], vpair[0], vpair[1]],
1016                1.0,
1017                &[kind],
1018                &mut totals,
1019                &mut rules,
1020            )?;
1021        }
1022    }
1023    Ok(totals[0])
1024}
1025
1026/// Integrate each of `kinds` over a bi-periodic band face, or return None when
1027/// `face` is not such a band. The between-rims strip integrates over the full
1028/// periodic span × the cross-level strip; the complement is the full-domain
1029/// integral MINUS that strip (the two tile the closed cross period, so no
1030/// domain-extended evaluation is needed).
1031///
1032/// Two readings of the strip. Rims that ARE iso lines (every rim circle a
1033/// kernel-built or exactly exported torus carries) integrate over the
1034/// seam-cut rectangle between their levels. A rim that wanders in the cross
1035/// parameter — a pcurve PROJECTED from a vendor edge that sits off the
1036/// carrier — is not at any one level, and the rectangle at its mean level
1037/// mis-reads the strip by the wander times the rim length; such a band is
1038/// integrated along the rims' own pcurves by the winding boundary integral
1039/// (`∮ −G du`, [`super::winding::winding_loops_integral`]), which reads the
1040/// trim exactly as given. The material choice (`complement`) is the same in
1041/// both readings; only the strip's quadrature differs.
1042pub(super) fn biperiodic_band_integral(
1043    face: &FaceRecord,
1044    kinds: &[Integrand],
1045) -> Result<Option<Vec<f64>>, String> {
1046    if face.loops.len() > 2 && switch!("BREP_MASS_BAND_HOLES", true) {
1047        if let Some(values) = band_with_holes_integral(face, kinds)? {
1048            return Ok(Some(values));
1049        }
1050    }
1051    let Some(band) = biperiodic_band_range(face)? else {
1052        if switch!("BREP_MASS_TORUS_LIFT", true) {
1053            return super::torus::lifted_band_integral(face, kinds);
1054        }
1055        return Ok(None);
1056    };
1057    let [u0, u1] = face.surface.domain_u()?;
1058    let [v0, v1] = face.surface.domain_v()?;
1059    let (u_lo, u_hi, v_lo, v_hi) = if band.p_is_u {
1060        (u0, u1, band.q_lo, band.q_hi)
1061    } else {
1062        (band.q_lo, band.q_hi, v0, v1)
1063    };
1064    let strips: Vec<f64> = if band.rim_wobble <= BAND_RIM_LEVEL_TOLERANCE_REL {
1065        kinds
1066            .iter()
1067            .map(|&kind| integrate_rectangle(face, u_lo, u_hi, v_lo, v_hi, kind))
1068            .collect::<Result<_, _>>()?
1069    } else {
1070        super::winding::winding_loops_integral(face, kinds, band.p_is_u, 1)?
1071    };
1072    let mut out = Vec::with_capacity(kinds.len());
1073    for (&kind, strip) in kinds.iter().zip(strips) {
1074        let value = if band.complement {
1075            integrate_untrimmed(face, kind)? - strip
1076        } else {
1077            strip
1078        };
1079        out.push(value);
1080    }
1081    Ok(Some(out))
1082}