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
29fn 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#[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
66pub 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
80fn open_planar_loops() -> bool {
84 debug_flag!("BREP_OPEN_PLANAR_LOOPS")
85}
86
87pub(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
109pub 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
136const SEAM_COINCIDENCE_REL: f64 = 1e-12;
146
147pub 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 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
256fn 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
266pub const GAUSS_COUNT: usize = GAUSS_X.len();
268
269pub(super) fn tensor_blocks_on() -> bool {
275 switch!("BREP_MASS_TENSOR_BLOCK", true)
276}
277
278pub 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 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 let area = match rules.take_local_area_face(face) {
322 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
342pub fn area_local_frame_on() -> bool {
360 switch!("BREP_MASS_AREA_LOCAL_FRAME", true)
361}
362
363fn 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
372fn 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
378pub(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
430pub(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
462fn 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
481pub fn area_adaptive_on() -> bool {
493 switch!("BREP_MASS_AREA_ADAPTIVE", true)
494}
495
496const AREA_ADAPTIVE_DEPTH: usize = 6;
498
499const AREA_ADAPTIVE_TOLERANCE: f64 = 1e-11;
502
503fn 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
541pub(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 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
664pub 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
690pub 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#[derive(Clone, Copy)]
735pub struct BiBand {
736 pub(super) p_is_u: bool,
738 pub q_lo: f64,
740 pub q_hi: f64,
741 pub(super) complement: bool,
745 pub rim_wobble: f64,
752}
753
754pub const BAND_RIM_LEVEL_TOLERANCE_REL: f64 = 1e-9;
768
769pub 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 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 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; }
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 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
908fn 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 if polygon_signed_area(&polygon.points) < 0.0 {
970 polygon.reverse();
971 }
972 polygons.push(polygon);
973 }
974 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
985pub 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
1026pub(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}