Skip to main content

brep_boolean/meshing/mesh_segment/
segmentation.rs

1use super::*;
2
3struct RegionOutcome {
4    fit: CandidateFit,
5    accepted: bool,
6    area: f64,
7    bbox: (Vec3, Vec3),
8    triangle_count: usize,
9}
10
11/// Try the analytic cascade plane → cylinder → cone → sphere → torus on one
12/// region; the first carrier within tolerance wins.
13fn fit_region(data: &MeshData, tri_ids: &[u32], options: &SegmentOptions) -> RegionOutcome {
14    let vert_ids = region_vertices(data, tri_ids);
15    let bbox = region_bbox(data, &vert_ids);
16    let area: f64 = tri_ids.iter().map(|&t| data.tris[t as usize].area).sum();
17    let scale = {
18        let diag = bbox.1.sub(bbox.0).length();
19        if diag > 0.0 {
20            diag
21        } else {
22            data.diag.max(1e-12)
23        }
24    };
25    let tol_abs = options.fit_tolerance * scale;
26    let mut outcome = RegionOutcome {
27        fit: CandidateFit {
28            carrier: RegionCarrier::Freeform,
29            max_dev: 0.0,
30            rms_dev: 0.0,
31            max_normal_angle_deg: 0.0,
32        },
33        accepted: false,
34        area,
35        bbox,
36        triangle_count: tri_ids.len(),
37    };
38    if tri_ids.len() < options.min_region_triangles || vert_ids.len() < 3 {
39        return outcome;
40    }
41    let candidates = [
42        fit_plane(data, tri_ids, &vert_ids),
43        fit_cylinder(data, tri_ids, &vert_ids),
44        fit_cone(data, tri_ids, &vert_ids, tol_abs),
45        fit_sphere(data, tri_ids, &vert_ids),
46        fit_torus(data, tri_ids, &vert_ids),
47    ];
48    for candidate in candidates {
49        if let Some(fit) = candidate {
50            if std::env::var("BREP_DEBUG_SEG").is_ok() {
51                eprintln!(
52                    "[seg] region tris={} candidate={} max_dev={:.3e} tol_abs={:.3e} max_ang={:.3}",
53                    tri_ids.len(),
54                    fit.carrier.kind(),
55                    fit.max_dev,
56                    tol_abs,
57                    fit.max_normal_angle_deg
58                );
59            }
60            if fit.max_dev.is_finite()
61                && fit.max_dev <= tol_abs
62                && fit.max_normal_angle_deg <= options.normal_tolerance_deg
63            {
64                outcome.fit = fit;
65                outcome.accepted = true;
66                return outcome;
67            }
68        }
69    }
70    outcome
71}
72
73// ---------------------------------------------------------------------------
74// Region growing and refinement
75// ---------------------------------------------------------------------------
76
77fn grow_regions(data: &MeshData, options: &SegmentOptions) -> Vec<Vec<u32>> {
78    let cos_gate = options.deflection_angle_deg.to_radians().cos();
79    let tri_count = data.tris.len();
80    let mut assigned = vec![false; tri_count];
81    let mut regions = Vec::new();
82    let mut stack = Vec::new();
83    for seed in 0..tri_count {
84        if assigned[seed] || data.tris[seed].skip {
85            continue;
86        }
87        assigned[seed] = true;
88        stack.push(seed as u32);
89        let mut region = Vec::new();
90        while let Some(t) = stack.pop() {
91            region.push(t);
92            let tri = &data.tris[t as usize];
93            for corner in 0..3 {
94                let first = tri.verts[corner];
95                let second = tri.verts[(corner + 1) % 3];
96                if first == second {
97                    continue;
98                }
99                let Some(incident) = data.edges.get(&edge_key(first, second)) else {
100                    continue;
101                };
102                // Only manifold (two-sided) edges are smooth crossings.
103                if incident.len() != 2 {
104                    continue;
105                }
106                for &other in incident {
107                    if other == t || assigned[other as usize] {
108                        continue;
109                    }
110                    let neighbor = &data.tris[other as usize];
111                    if neighbor.skip {
112                        continue;
113                    }
114                    if tri.normal.dot(neighbor.normal) >= cos_gate {
115                        assigned[other as usize] = true;
116                        stack.push(other);
117                    }
118                }
119            }
120        }
121        region.sort_unstable();
122        regions.push(region);
123    }
124    regions
125}
126
127/// Regions whose area is below this fraction of the total mesh area are
128/// dissolved into their largest neighboring region before fitting.  Needle
129/// triangles at tessellation poles wall themselves off into 1–2-triangle
130/// islands; the app's minimum-region-size gating served the same purpose.
131const REGION_ABSORB_AREA_FRACTION: f64 = 1e-6;
132
133/// Merge negligible regions into their largest-area neighbor (repeats until
134/// stable so chains of islands resolve).  Regions with no neighbor at all
135/// stay as they are.
136fn absorb_tiny_regions(data: &MeshData, regions: &mut Vec<Vec<u32>>) {
137    let total_area: f64 = data
138        .tris
139        .iter()
140        .filter(|tri| !tri.skip)
141        .map(|tri| tri.area)
142        .sum();
143    let floor = total_area * REGION_ABSORB_AREA_FRACTION;
144    if !(floor > 0.0) {
145        return;
146    }
147    let mut region_of = vec![usize::MAX; data.tris.len()];
148    for (r, list) in regions.iter().enumerate() {
149        for &t in list {
150            region_of[t as usize] = r;
151        }
152    }
153    let mut areas: Vec<f64> = regions
154        .iter()
155        .map(|list| list.iter().map(|&t| data.tris[t as usize].area).sum())
156        .collect();
157    let mut changed = true;
158    while changed {
159        changed = false;
160        for r in 0..regions.len() {
161            if regions[r].is_empty() || areas[r] >= floor {
162                continue;
163            }
164            // Find adjacent regions, traversing THROUGH region-less
165            // (skipped sliver) triangles — pole islands are often fenced
166            // off from the main region by a ring of skipped needles.
167            let mut target: Option<usize> = None;
168            let mut visited: rustc_hash::FxHashSet<u32> = regions[r].iter().copied().collect();
169            let mut frontier: Vec<u32> = regions[r].clone();
170            while let Some(t) = frontier.pop() {
171                let tri = &data.tris[t as usize];
172                for corner in 0..3 {
173                    let first = tri.verts[corner];
174                    let second = tri.verts[(corner + 1) % 3];
175                    if first == second {
176                        continue;
177                    }
178                    if let Some(incident) = data.edges.get(&edge_key(first, second)) {
179                        for &other in incident {
180                            if visited.contains(&other) {
181                                continue;
182                            }
183                            let neighbor = region_of[other as usize];
184                            if neighbor == usize::MAX {
185                                // Skipped triangle: pass through it.
186                                visited.insert(other);
187                                frontier.push(other);
188                                continue;
189                            }
190                            if neighbor == r {
191                                continue;
192                            }
193                            target = match target {
194                                None => Some(neighbor),
195                                Some(current) => Some(if areas[neighbor] > areas[current] {
196                                    neighbor
197                                } else {
198                                    current
199                                }),
200                            };
201                        }
202                    }
203                }
204            }
205            if let Some(target) = target {
206                let moved = std::mem::take(&mut regions[r]);
207                for &t in &moved {
208                    region_of[t as usize] = target;
209                }
210                areas[target] += areas[r];
211                areas[r] = 0.0;
212                regions[target].extend(moved);
213                changed = true;
214            }
215        }
216    }
217    regions.retain(|list| !list.is_empty());
218    for list in regions.iter_mut() {
219        list.sort_unstable();
220    }
221}
222
223/// Connected components of `tri_ids` across shared (welded) edges,
224/// restricted to the given set.
225fn connected_components(data: &MeshData, tri_ids: &[u32]) -> Vec<Vec<u32>> {
226    let member: rustc_hash::FxHashSet<u32> = tri_ids.iter().copied().collect();
227    let mut assigned: rustc_hash::FxHashSet<u32> = rustc_hash::FxHashSet::default();
228    let mut components = Vec::new();
229    let mut stack = Vec::new();
230    for &seed in tri_ids {
231        if assigned.contains(&seed) {
232            continue;
233        }
234        assigned.insert(seed);
235        stack.push(seed);
236        let mut component = Vec::new();
237        while let Some(t) = stack.pop() {
238            component.push(t);
239            let tri = &data.tris[t as usize];
240            for corner in 0..3 {
241                let first = tri.verts[corner];
242                let second = tri.verts[(corner + 1) % 3];
243                if first == second {
244                    continue;
245                }
246                if let Some(incident) = data.edges.get(&edge_key(first, second)) {
247                    for &other in incident {
248                        if other != t && member.contains(&other) && !assigned.contains(&other) {
249                            assigned.insert(other);
250                            stack.push(other);
251                        }
252                    }
253                }
254            }
255        }
256        component.sort_unstable();
257        components.push(component);
258    }
259    components
260}
261
262/// Split a region the cascade could not classify: peel tangent cylinders,
263/// cones and spheres out of it first (the most specific test — a group
264/// must lie on ONE carrier at the mesh's precision), then seed-plane-
265/// anchored coplanar groups (the app's planar extraction) out of what is
266/// left, and re-fit the remaining connected components.  Planes come second
267/// because a coarse strip of a cylinder is a coplanar group too, and one
268/// wide enough to pass the planar area gate would otherwise be peeled as a
269/// plane before the cylinder it belongs to was ever tried.  Returns the
270/// partition with each piece's fit outcome.
271fn refine_region(
272    data: &MeshData,
273    tri_ids: &[u32],
274    options: &SegmentOptions,
275) -> Vec<(Vec<u32>, RegionOutcome)> {
276    let vert_ids = region_vertices(data, tri_ids);
277    let (low, high) = region_bbox(data, &vert_ids);
278    let scale = {
279        let diag = high.sub(low).length();
280        if diag > 0.0 {
281            diag
282        } else {
283            data.diag.max(1e-12)
284        }
285    };
286    let dist_gate = options.fit_tolerance * scale;
287    let cos_gate = options.planar_extraction_angle_deg.to_radians().cos();
288    let region_area: f64 = tri_ids.iter().map(|&t| data.tris[t as usize].area).sum();
289    let min_group_area = region_area * (options.planar_min_area_percent / 100.0).clamp(0.0, 1.0);
290    let min_group_tris = options.min_region_triangles.max(2);
291
292    let (mut pieces, leftover) = peel_carriers(data, tri_ids, options);
293    let member: rustc_hash::FxHashSet<u32> = leftover.iter().copied().collect();
294    let mut order: Vec<u32> = leftover.clone();
295    order.sort_by(|&a, &b| {
296        data.tris[b as usize]
297            .area
298            .total_cmp(&data.tris[a as usize].area)
299            .then(a.cmp(&b))
300    });
301
302    let mut group_of: HashMap<u32, usize> = HashMap::default();
303    let mut planar_groups: Vec<Vec<u32>> = Vec::new();
304    let mut stack = Vec::new();
305    for &seed in &order {
306        if group_of.contains_key(&seed) {
307            continue;
308        }
309        let seed_tri = &data.tris[seed as usize];
310        let seed_normal = seed_tri.normal;
311        let seed_origin = seed_tri.centroid;
312        let coplanar = |t: u32| -> bool {
313            let tri = &data.tris[t as usize];
314            if tri.normal.dot(seed_normal) < cos_gate {
315                return false;
316            }
317            tri.verts
318                .iter()
319                .all(|&v| data.verts[v].sub(seed_origin).dot(seed_normal).abs() <= dist_gate)
320        };
321        if !coplanar(seed) {
322            continue;
323        }
324        // Grow the seed plane over not-yet-grouped region triangles.
325        let mut visited: rustc_hash::FxHashSet<u32> = rustc_hash::FxHashSet::default();
326        visited.insert(seed);
327        stack.push(seed);
328        let mut group = Vec::new();
329        while let Some(t) = stack.pop() {
330            group.push(t);
331            let tri = &data.tris[t as usize];
332            for corner in 0..3 {
333                let first = tri.verts[corner];
334                let second = tri.verts[(corner + 1) % 3];
335                if first == second {
336                    continue;
337                }
338                if let Some(incident) = data.edges.get(&edge_key(first, second)) {
339                    for &other in incident {
340                        if other == t
341                            || !member.contains(&other)
342                            || group_of.contains_key(&other)
343                            || visited.contains(&other)
344                        {
345                            continue;
346                        }
347                        if coplanar(other) {
348                            visited.insert(other);
349                            stack.push(other);
350                        }
351                    }
352                }
353            }
354        }
355        let group_area: f64 = group.iter().map(|&t| data.tris[t as usize].area).sum();
356        if group.len() >= min_group_tris && group_area >= min_group_area {
357            let id = planar_groups.len();
358            for &t in &group {
359                group_of.insert(t, id);
360            }
361            group.sort_unstable();
362            planar_groups.push(group);
363        }
364    }
365
366    let remainder: Vec<u32> = leftover
367        .iter()
368        .copied()
369        .filter(|t| !group_of.contains_key(t))
370        .collect();
371
372    for group in planar_groups {
373        let outcome = fit_region(data, &group, options);
374        pieces.push((group, outcome));
375    }
376    for component in connected_components(data, &remainder) {
377        let outcome = fit_region(data, &component, options);
378        pieces.push((component, outcome));
379    }
380    pieces
381}
382
383/// Precision bar of the cylinder peel as a fraction of the compound
384/// region's scale: far below the acceptance tolerance (so the first strip
385/// past a tangent junction is refused) and far above the vertex noise of an
386/// exact tessellation.
387const CYLINDER_PEEL_PRECISION_FRACTION: f64 = 1e-5;
388/// Floor of that bar from the coordinate magnitude: single-precision
389/// sources quantize at a few ulps of their largest coordinate.
390const CYLINDER_PEEL_COORDINATE_FRACTION: f64 = 1e-6;
391/// Adjacent triangles whose normals agree within this angle are one planar
392/// facet (a tessellated strip) and are peeled together.
393const CYLINDER_PEEL_FACET_ANGLE_RAD: f64 = 1e-4;
394/// Rings of facets gathered around a seed facet before the seed fit: three
395/// rows at least, because two rows of cells lie on two coaxial circles,
396/// which every revolve fits exactly.
397const CYLINDER_PEEL_SEED_RINGS: usize = 3;
398
399/// Carrier kinds the peel tries, in cascade order, with the smallest vertex
400/// support that makes a claim at the precision bar evidence rather than an
401/// interpolation: three times the carrier's degrees of freedom (a cylinder
402/// has five, a cone six, a sphere four).  Each pass works on what the
403/// previous ones left.
404///
405/// The cone pass runs before the cylinder pass: a cone strip one column
406/// wide (its vertices on the two rim circles) reads as a cylinder about its
407/// generatrix at 5.6e-5 against a 7.5e-5 bar, and such strips cut the cone
408/// into patches its own pass could no longer seed; claimed whole first, the
409/// cone leaves no strip to misread. A cylinder offered to the cone pass fits
410/// a cone of zero half-angle that the cascade reads as a cylinder, which the
411/// kind check declines, so the cylinder pass still claims it.
412const PEEL_KINDS: [(&str, usize); 4] =
413    [("cone", 18), ("cylinder", 15), ("sphere", 12), ("torus", 21)];
414
415/// Peel single-carrier groups off a tangent-smooth compound the cascade
416/// could not classify: a rounded outline (arcs of different radii joined on
417/// rulings), a fillet running out into a boss, a dome sitting on a chamfer
418/// ring.
419///
420/// The acceptance tolerance is far too loose to separate tangent surfaces:
421/// at the junction of two arcs the first strip on the far side deviates by
422/// a fraction of the acceptance bar and the normal gate admits several
423/// more.  Growth therefore runs at a precision bar and is judged by the
424/// re-fit residual of the grown group: a wave of neighboring facets is kept
425/// when the joint fit still sits at precision, otherwise each facet is
426/// tried alone.  Facets — coplanar triangle groups, the strips of a
427/// tessellated cylinder — move as a whole so a region boundary never runs
428/// down a strip's diagonal.  Each finished group is then accepted through
429/// the ordinary cascade at the user tolerance.  Cylinders are peeled
430/// first, then cones, then spheres.  Returns the pieces and the triangles
431/// no carrier claimed.
432/// `BREP_SEG_PEEL_DECLINED_SKIP` (default off; PARKED, NOT EXACT): within one
433/// peel pass, a seed facet that lies in a group the pass already grew and
434/// declined (since its last claim) is not grown again; a claim clears the
435/// marks. The premise that such a seed's own growth would be declined too
436/// does not hold: a seed grows its OWN group (its own seed fit and gates), and
437/// on a noisy mesh that group can be claimable. The promotion census
438/// (2026-11-23) found such seeds in check mode on 14 meshes
439/// (jittered and T-junction crossed cylinders, countersunk hole and torus, and
440/// the real fixtures gearbox-keychain and a filleted bracket), the final
441/// conversion changing on 11; marking only groups the cascade accepted as a
442/// plane still missed on the two real fixtures. Do not promote without an
443/// exact formulation. On a gridded fillet band's
444/// compound (30 374 triangles, 15 413 facets) the cone and sphere passes each
445/// regrew the same planar annulus from 438 seeds and declined it every time:
446/// 99 of the segmentation's 103 s. `BREP_SEG_PEEL_DECLINED_SKIP_CHECK` grows
447/// every skipped seed anyway, keeps the full answer, and counts and prints
448/// each skipped seed that would have been claimed ([`PEEL_SKIP_MISSES`]).
449fn peel_declined_skip() -> bool {
450    crate::switch!(live "BREP_SEG_PEEL_DECLINED_SKIP", false)
451}
452
453fn peel_declined_skip_check() -> bool {
454    crate::switch!(live "BREP_SEG_PEEL_DECLINED_SKIP_CHECK", false)
455}
456
457thread_local! {
458    /// Skipped peel seeds whose growth would have been claimed (check mode).
459    pub static PEEL_SKIP_MISSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
460}
461
462fn peel_carriers(
463    data: &MeshData,
464    tri_ids: &[u32],
465    options: &SegmentOptions,
466) -> (Vec<(Vec<u32>, RegionOutcome)>, Vec<u32>) {
467    let debug = std::env::var("BREP_DEBUG_SEG").is_ok();
468    let started = debug.then(web_time::Instant::now);
469    let local: HashMap<u32, usize> = tri_ids
470        .iter()
471        .enumerate()
472        .map(|(index, &t)| (t, index))
473        .collect();
474    let vert_ids = region_vertices(data, tri_ids);
475    let (low, high) = region_bbox(data, &vert_ids);
476    let scale = {
477        let diag = high.sub(low).length();
478        if diag > 0.0 {
479            diag
480        } else {
481            data.diag.max(1e-12)
482        }
483    };
484    let accept_tol = options.fit_tolerance * scale;
485    let coordinate = vert_ids
486        .iter()
487        .map(|&v| {
488            let p = data.verts[v];
489            p.x.abs().max(p.y.abs()).max(p.z.abs())
490        })
491        .fold(0.0_f64, f64::max);
492    let bar = (scale * CYLINDER_PEEL_PRECISION_FRACTION)
493        .max(coordinate * CYLINDER_PEEL_COORDINATE_FRACTION);
494    if bar >= accept_tol {
495        return (Vec::new(), tri_ids.to_vec());
496    }
497    let cos_normal_gate = options.normal_tolerance_deg.to_radians().cos();
498    let cos_facet = CYLINDER_PEEL_FACET_ANGLE_RAD.cos();
499
500    // Facets: union of coplanar edge-adjacent member triangles.
501    let mut parent: Vec<usize> = (0..tri_ids.len()).collect();
502    fn find(parent: &mut [usize], x: usize) -> usize {
503        crate::union_find::find_root(parent, x)
504    }
505    let mut adjacency: Vec<Vec<usize>> = vec![Vec::new(); tri_ids.len()];
506    for (index, &t) in tri_ids.iter().enumerate() {
507        let tri = &data.tris[t as usize];
508        for corner in 0..3 {
509            let first = tri.verts[corner];
510            let second = tri.verts[(corner + 1) % 3];
511            if first == second {
512                continue;
513            }
514            let Some(incident) = data.edges.get(&edge_key(first, second)) else {
515                continue;
516            };
517            for &other in incident {
518                let Some(&other_index) = local.get(&other) else {
519                    continue;
520                };
521                if other_index == index {
522                    continue;
523                }
524                adjacency[index].push(other_index);
525                if tri.normal.dot(data.tris[other as usize].normal) >= cos_facet {
526                    let a = find(&mut parent, index);
527                    let b = find(&mut parent, other_index);
528                    if a != b {
529                        parent[a] = b;
530                    }
531                }
532            }
533        }
534    }
535    let mut facet_of = vec![usize::MAX; tri_ids.len()];
536    let mut facets: Vec<Vec<usize>> = Vec::new();
537    for index in 0..tri_ids.len() {
538        let root = find(&mut parent, index);
539        if facet_of[root] == usize::MAX {
540            facet_of[root] = facets.len();
541            facets.push(Vec::new());
542        }
543        facet_of[index] = facet_of[root];
544        facets[facet_of[index]].push(index);
545    }
546    let mut facet_neighbors: Vec<Vec<usize>> = vec![Vec::new(); facets.len()];
547    for (index, others) in adjacency.iter().enumerate() {
548        for &other in others {
549            let (a, b) = (facet_of[index], facet_of[other]);
550            if a != b && !facet_neighbors[a].contains(&b) {
551                facet_neighbors[a].push(b);
552            }
553        }
554    }
555    let facet_area: Vec<f64> = facets
556        .iter()
557        .map(|facet| {
558            facet
559                .iter()
560                .map(|&index| data.tris[tri_ids[index] as usize].area)
561                .sum()
562        })
563        .collect();
564
565    let facet_tris = |facet_ids: &[usize]| -> Vec<u32> {
566        facet_ids
567            .iter()
568            .flat_map(|&facet| facets[facet].iter().map(|&index| tri_ids[index]))
569            .collect()
570    };
571    let fit_kind = |kind: &str, facet_ids: &[usize]| -> Option<CandidateFit> {
572        let tris = facet_tris(facet_ids);
573        let verts = region_vertices(data, &tris);
574        match kind {
575            "cylinder" => fit_cylinder(data, &tris, &verts),
576            "cone" => fit_cone(data, &tris, &verts, accept_tol),
577            "sphere" => fit_sphere(data, &tris, &verts),
578            "torus" => fit_torus_refined(data, &tris, &verts, 10.0 * accept_tol),
579            _ => None,
580        }
581    };
582    let fit_facets = |kind: &str, facet_ids: &[usize]| -> Option<CandidateFit> {
583        fit_kind(kind, facet_ids).filter(|fit| fit.max_dev.is_finite() && fit.max_dev <= bar)
584    };
585    // A growing torus refits from its own current carrier: the cold fit
586    // (normal-line axis, then a vertex refinement) per wave is what made a
587    // dense fillet band cost a minute.
588    let grow_fit = |kind: &str, facet_ids: &[usize], carrier: &RegionCarrier| -> Option<CandidateFit> {
589        if kind != "torus" {
590            return fit_facets(kind, facet_ids);
591        }
592        let tris = facet_tris(facet_ids);
593        let verts = region_vertices(data, &tris);
594        refine_torus_carrier(data, &tris, &verts, carrier, TORUS_REFINE_ITERATIONS)
595            .filter(|fit| fit.max_dev.is_finite() && fit.max_dev <= bar)
596    };
597    // Every vertex of the facet on the carrier at the precision bar.
598    let held_by = |carrier: &RegionCarrier, facet: usize| -> bool {
599        facets[facet].iter().all(|&index| {
600            data.tris[tri_ids[index] as usize]
601                .verts
602                .iter()
603                .all(|&v| carrier_distance(carrier, data.verts[v]) <= bar)
604        })
605    };
606    // Loose pre-filter against the current carrier: the refit decides.
607    let plausible = |carrier: &RegionCarrier, facet: usize| -> bool {
608        let sense = carrier_sense(carrier);
609        facets[facet].iter().all(|&index| {
610            let tri = &data.tris[tri_ids[index] as usize];
611            let Some(normal) = carrier_normal(carrier, tri.centroid) else {
612                return false;
613            };
614            tri.normal.dot(normal) * sense >= cos_normal_gate
615                && tri
616                    .verts
617                    .iter()
618                    .all(|&v| carrier_distance(carrier, data.verts[v]) <= accept_tol)
619        })
620    };
621
622    // Dihedral between two neighbouring facets (their first triangles'
623    // normals: a facet is coplanar at 1e-4 rad).
624    let facet_dihedral = |a: usize, b: usize| -> f64 {
625        let na = data.tris[tri_ids[facets[a][0]] as usize].normal;
626        let nb = data.tris[tri_ids[facets[b][0]] as usize].normal;
627        na.dot(nb).clamp(-1.0, 1.0).acos()
628    };
629    // Three times the median dihedral of the seed's own in-region edges, or
630    // no gate at all for a seed with fewer than two neighbours.
631    let seed_dihedral_gate = |seed: usize| -> f64 {
632        let mut dihedrals: Vec<f64> = facet_neighbors[seed].iter().map(|&o| facet_dihedral(seed, o)).collect();
633        if dihedrals.len() < 2 {
634            return f64::INFINITY;
635        }
636        dihedrals.sort_by(f64::total_cmp);
637        3.0 * dihedrals[dihedrals.len() / 2]
638    };
639
640    let mut order: Vec<usize> = (0..facets.len()).collect();
641    order.sort_by(|&a, &b| facet_area[b].total_cmp(&facet_area[a]).then(a.cmp(&b)));
642    if let Some(started) = started {
643        eprintln!(
644            "[seg] peel timing: {} facets of {} tris built in {:.1} ms",
645            facets.len(),
646            tri_ids.len(),
647            started.elapsed().as_secs_f64() * 1e3
648        );
649    }
650    let mut assigned = vec![false; facets.len()];
651    let (skip_declined, skip_check) = (peel_declined_skip(), peel_declined_skip_check());
652    let mut pieces: Vec<(Vec<u32>, RegionOutcome)> = Vec::new();
653    // A torus seed is tried once across all rounds: the rounds exist for a
654    // one-strip wall whose seed neighbourhood clears once its dome is
655    // claimed, and a torus band that failed once does not become one.
656    let mut torus_tried = vec![false; facets.len()];
657    // Rounds until nothing new is claimed: a wall one strip tall has its
658    // seed neighborhood polluted by the dome or fillet beyond its rim until
659    // that neighbor has been claimed by its own pass.
660    loop {
661    let claimed = pieces.len();
662    for (kind, min_vertices) in PEEL_KINDS {
663    let mut tried = vec![false; facets.len()];
664    // `BREP_SEG_PEEL_DECLINED_SKIP`: facets of the groups this pass grew and
665    // declined since its last claim ([`peel_declined_skip`]).
666    let mut declined = vec![false; facets.len()];
667    // Seed-stage accounting for the trace: how many seeds the pass tried,
668    // how many seed fits it got at the bar, the best seed residual it saw
669    // refused, and how many grown groups fell under the support floor.
670    let (mut seeds_tried, mut seed_fits, mut small_groups) = (0usize, 0usize, 0usize);
671    let mut best_refused_seed = f64::INFINITY;
672    for &seed in &order {
673        if assigned[seed] || tried[seed] || (kind == "torus" && torus_tried[seed]) {
674            continue;
675        }
676        tried[seed] = true;
677        if kind == "torus" {
678            torus_tried[seed] = true;
679        }
680        let skipped = skip_declined && declined[seed];
681        if skipped && !skip_check {
682            continue;
683        }
684        let mut group = vec![seed];
685        let mut in_group = vec![false; facets.len()];
686        in_group[seed] = true;
687        let mut frontier = vec![seed];
688        // A ring neighbour across a crease is left out: on an anisotropic
689        // tessellation whose columns span a wall's full height, every seed
690        // neighbourhood of the bore touches the countersink cone across a
691        // 26.6-degree crease and no whole-neighbourhood fit can pass the bar.
692        // The crease is an outlier among the seed's own dihedrals (3.6 degrees
693        // between its columns), so a neighbour is admitted only when its
694        // dihedral across the shared edge is at most three times the median
695        // dihedral of the seed facet's own in-region edges.
696        let dihedral_gate = seed_dihedral_gate(seed);
697        for _ in 0..CYLINDER_PEEL_SEED_RINGS {
698            let mut next = Vec::new();
699            for &facet in &frontier {
700                for &other in &facet_neighbors[facet] {
701                    if !assigned[other] && !in_group[other] && facet_dihedral(facet, other) <= dihedral_gate {
702                        in_group[other] = true;
703                        group.push(other);
704                        next.push(other);
705                    }
706                }
707            }
708            frontier = next;
709        }
710        seeds_tried += 1;
711        let Some(seed_fit) = fit_facets(kind, &group) else {
712            if debug {
713                if let Some(fit) = fit_kind(kind, &group) {
714                    best_refused_seed = best_refused_seed.min(fit.max_dev);
715                }
716            }
717            continue;
718        };
719        seed_fits += 1;
720        let mut carrier = seed_fit.carrier;
721        let mut blocked = vec![false; facets.len()];
722        let mut blocked_list: Vec<usize> = Vec::new();
723        // Growth, then a sweep of the facets blocked while the carrier was
724        // still settling on a small support: those on its final estimate at
725        // the bar are admitted in one refit and growth resumes from them.
726        // Without the sweep a densely gridded band leaves hundreds of two-
727        // and four-triangle slivers behind, each re-fitted on its own later.
728        loop {
729        loop {
730            let mut wave = Vec::new();
731            for &facet in &group {
732                for &other in &facet_neighbors[facet] {
733                    if !assigned[other]
734                        && !in_group[other]
735                        && !blocked[other]
736                        && !wave.contains(&other)
737                        && plausible(&carrier, other)
738                    {
739                        wave.push(other);
740                    }
741                }
742            }
743            if wave.is_empty() {
744                break;
745            }
746            let mut trial = group.clone();
747            trial.extend(wave.iter().copied());
748            if let Some(fit) = grow_fit(kind, &trial, &carrier) {
749                for &facet in &wave {
750                    in_group[facet] = true;
751                }
752                group = trial;
753                carrier = fit.carrier;
754                continue;
755            }
756            // The wave crossed a junction: admit its facets one at a time.
757            // A torus admits the facets its current carrier already holds at
758            // the bar, then refits once: a refit per junction facet is what
759            // a dense freeform compound cannot afford.
760            if kind == "torus" {
761                let (inside, outside): (Vec<usize>, Vec<usize>) =
762                    wave.into_iter().partition(|&facet| held_by(&carrier, facet));
763                for facet in outside {
764                    blocked[facet] = true;
765                    blocked_list.push(facet);
766                }
767                if inside.is_empty() {
768                    break;
769                }
770                let mut trial = group.clone();
771                trial.extend(inside.iter().copied());
772                let Some(fit) = grow_fit(kind, &trial, &carrier) else {
773                    for facet in inside {
774                        blocked[facet] = true;
775                        blocked_list.push(facet);
776                    }
777                    break;
778                };
779                for &facet in &inside {
780                    in_group[facet] = true;
781                }
782                group = trial;
783                carrier = fit.carrier;
784                continue;
785            }
786            let mut accepted_any = false;
787            for facet in wave {
788                let mut trial = group.clone();
789                trial.push(facet);
790                if let Some(fit) = grow_fit(kind, &trial, &carrier) {
791                    in_group[facet] = true;
792                    group = trial;
793                    carrier = fit.carrier;
794                    accepted_any = true;
795                } else {
796                    blocked[facet] = true;
797                    blocked_list.push(facet);
798                }
799            }
800            if !accepted_any {
801                break;
802            }
803        }
804        blocked_list.retain(|&facet| blocked[facet] && !in_group[facet]);
805        let held: Vec<usize> = blocked_list
806            .iter()
807            .copied()
808            .filter(|&facet| held_by(&carrier, facet))
809            .collect();
810        if held.is_empty() {
811            break;
812        }
813        let mut trial = group.clone();
814        trial.extend(held.iter().copied());
815        let Some(fit) = grow_fit(kind, &trial, &carrier) else {
816            break;
817        };
818        for &facet in &held {
819            in_group[facet] = true;
820            blocked[facet] = false;
821        }
822        group = trial;
823        carrier = fit.carrier;
824        }
825        let mut tris = facet_tris(&group);
826        if tris.len() < options.min_region_triangles.max(4)
827            || region_vertices(data, &tris).len() < min_vertices
828        {
829            small_groups += 1;
830            if skip_declined {
831                for &facet in &group {
832                    declined[facet] = true;
833                }
834            }
835            continue;
836        }
837        tris.sort_unstable();
838        let outcome = fit_peeled(data, &tris, options);
839        if debug {
840            let size = match outcome.fit.carrier {
841                RegionCarrier::Cylinder { radius, .. } | RegionCarrier::Sphere { radius, .. } => {
842                    format!(" r={radius:.4}")
843                }
844                RegionCarrier::Cone { half_angle_rad, apex, axis_dir, .. } => {
845                    format!(
846                        " ha={:.2}deg apex=({:.3},{:.3},{:.3}) axis=({:+.4},{:+.4},{:+.4})",
847                        half_angle_rad.to_degrees(),
848                        apex.x, apex.y, apex.z,
849                        axis_dir.x, axis_dir.y, axis_dir.z
850                    )
851                }
852                RegionCarrier::Torus { center, axis_dir, major_radius, minor_radius, .. } => {
853                    format!(
854                        " R={major_radius:.4} r={minor_radius:.4} centre=({:.3},{:.3},{:.3}) axis=({:+.4},{:+.4},{:+.4})",
855                        center.x, center.y, center.z, axis_dir.x, axis_dir.y, axis_dir.z
856                    )
857                }
858                _ => String::new(),
859            };
860            let (low, high) = region_bbox(data, &region_vertices(data, &tris));
861            eprintln!(
862                "[seg] peel {kind}: seed facet {seed} grew {} facets / {} tris at {bar:.3e}; cascade {}{size} accepted={} max_dev={:.3e} max_ang={:.2} bbox [{:.2},{:.2},{:.2}]..[{:.2},{:.2},{:.2}]",
863                group.len(),
864                tris.len(),
865                outcome.fit.carrier.kind(),
866                outcome.accepted,
867                outcome.fit.max_dev,
868                outcome.fit.max_normal_angle_deg,
869                low.x, low.y, low.z, high.x, high.y, high.z
870            );
871        }
872        // A torus is claimed only as a FULL band around its axis — the
873        // shape a mesh rebuild can bound by closed rings. A partial torus
874        // (a fillet running along an arc of an outline) stays with the
875        // planar strips it has always been read as.
876        if !outcome.accepted
877            || outcome.fit.carrier.kind() != kind
878            || (kind == "torus" && !covers_full_azimuth(data, &tris, &outcome.fit.carrier))
879        {
880            if skip_declined {
881                for &facet in &group {
882                    declined[facet] = true;
883                }
884            }
885            continue;
886        }
887        if skipped {
888            // Check mode: a seed the skip would have passed over is claimed.
889            PEEL_SKIP_MISSES.with(|count| count.set(count.get() + 1));
890            eprintln!("SEG-PEEL-SKIP MISS {kind}: seed facet {seed} grows a claimed {} of {} tris", outcome.fit.carrier.kind(), tris.len());
891        }
892        for &facet in &group {
893            assigned[facet] = true;
894        }
895        // A claim changes what every later seed can grow into.
896        declined.iter_mut().for_each(|mark| *mark = false);
897        pieces.push((tris, outcome));
898    }
899    if debug {
900        eprintln!(
901            "[seg] peel {kind} seeds: {seeds_tried} tried, {seed_fits} seed fits at {bar:.3e}, best refused seed max_dev={best_refused_seed:.3e}, {small_groups} grown groups under the support floor ({min_vertices} vertices)"
902        );
903    }
904    }
905    if pieces.len() == claimed {
906        break;
907    }
908    }
909    if let Some(started) = started {
910        eprintln!(
911            "[seg] peel timing: seeds done at {:.1} ms, {} pieces",
912            started.elapsed().as_secs_f64() * 1e3,
913            pieces.len()
914        );
915    }
916    if pieces.is_empty() {
917        return (pieces, tri_ids.to_vec());
918    }
919    absorb_held_pieces(data, options, bar, &mut pieces, &facets, &facet_of, &local, &facet_neighbors, debug);
920    if let Some(started) = started {
921        eprintln!(
922            "[seg] peel timing: absorption done at {:.1} ms, {} pieces",
923            started.elapsed().as_secs_f64() * 1e3,
924            pieces.len()
925        );
926    }
927    // A leftover strip whose every peeled neighbor is the same carrier is an
928    // interior gap — a tessellator T-vertex on a rim chord — not a
929    // junction: it rejoins that carrier when the union still passes the
930    // cascade at the user tolerance.  A strip straddling the tangent point
931    // of two different carriers stays out and becomes its own small facet.
932    let mut piece_of_facet = vec![usize::MAX; facets.len()];
933    for (piece, (tris, _)) in pieces.iter().enumerate() {
934        for &t in tris {
935            piece_of_facet[facet_of[local[&t]]] = piece;
936        }
937    }
938    let leftover_tris: Vec<u32> = (0..tri_ids.len())
939        .filter(|&index| !assigned[facet_of[index]])
940        .map(|index| tri_ids[index])
941        .collect();
942    let compat_tol = options.fit_tolerance * data.diag.max(1e-12);
943    let mut remainder = Vec::new();
944    for component in connected_components(data, &leftover_tris) {
945        let mut adjacent_pieces: Vec<usize> = Vec::new();
946        for &t in &component {
947            for &other in &facet_neighbors[facet_of[local[&t]]] {
948                let piece = piece_of_facet[other];
949                if piece != usize::MAX && !adjacent_pieces.contains(&piece) {
950                    adjacent_pieces.push(piece);
951                }
952            }
953        }
954        let Some(&first) = adjacent_pieces.first() else {
955            remainder.extend(component);
956            continue;
957        };
958        let same_carrier = adjacent_pieces.iter().all(|&piece| {
959            carriers_compatible(
960                &pieces[first].1.fit.carrier,
961                &pieces[piece].1.fit.carrier,
962                compat_tol,
963                true,
964            )
965        });
966        if !same_carrier {
967            remainder.extend(straddle_rejoin(data, options, bar, &mut pieces, &adjacent_pieces, component));
968            continue;
969        }
970        let mut union: Vec<u32> = pieces[first].0.iter().chain(component.iter()).copied().collect();
971        union.sort_unstable();
972        let outcome = fit_peeled(data, &union, options);
973        let rejoined = outcome.accepted
974            && outcome.fit.carrier.kind() == pieces[first].1.fit.carrier.kind();
975        if debug {
976            eprintln!(
977                "[seg] peel: leftover of {} tris between {} peeled piece(s): union {} accepted={} max_dev={:.3e}",
978                component.len(),
979                adjacent_pieces.len(),
980                outcome.fit.carrier.kind(),
981                outcome.accepted,
982                outcome.fit.max_dev
983            );
984        }
985        if rejoined {
986            pieces[first] = (union, outcome);
987        } else {
988            remainder.extend(straddle_rejoin(data, options, bar, &mut pieces, &adjacent_pieces, component));
989        }
990    }
991    remainder.sort_unstable();
992    if let Some(started) = started {
993        eprintln!(
994            "[seg] peel timing: leftovers done at {:.1} ms, {} remainder tris",
995            started.elapsed().as_secs_f64() * 1e3,
996            remainder.len()
997        );
998    }
999    (pieces, remainder)
1000}
1001
1002/// A piece every vertex of which lies on a neighbouring, larger piece's
1003/// carrier at the precision bar is a sub-patch of that carrier, not evidence
1004/// of a kind of its own: the cone pass claimed 144 triangles off the plane
1005/// rim of a densely gridded fillet torus at 3.9e-4 against a 4.1e-4 bar
1006/// before the torus pass reached the band, and the rebuild then demoted the
1007/// torus for the cone edge across it. Such a piece rejoins the neighbour
1008/// whose carrier holds it closest when the union still passes the cascade
1009/// as that neighbour's kind; a pair that fails stays apart. Repeats until
1010/// nothing rejoins.
1011#[allow(clippy::too_many_arguments)]
1012fn absorb_held_pieces(
1013    data: &MeshData,
1014    options: &SegmentOptions,
1015    bar: f64,
1016    pieces: &mut Vec<(Vec<u32>, RegionOutcome)>,
1017    facets: &[Vec<usize>],
1018    facet_of: &[usize],
1019    local: &HashMap<u32, usize>,
1020    facet_neighbors: &[Vec<usize>],
1021    debug: bool,
1022) {
1023    let mut refused: Vec<(Vec<u32>, Vec<u32>)> = Vec::new();
1024    loop {
1025        let mut piece_of_facet = vec![usize::MAX; facets.len()];
1026        for (piece, (tris, _)) in pieces.iter().enumerate() {
1027            for &t in tris {
1028                piece_of_facet[facet_of[local[&t]]] = piece;
1029            }
1030        }
1031        let area: Vec<f64> = pieces
1032            .iter()
1033            .map(|(tris, _)| tris.iter().map(|&t| data.tris[t as usize].area).sum())
1034            .collect();
1035        let mut by_area: Vec<usize> = (0..pieces.len()).collect();
1036        by_area.sort_by(|&a, &b| area[a].total_cmp(&area[b]).then(a.cmp(&b)));
1037        let mut merge = None;
1038        for &small in &by_area {
1039            let verts = region_vertices(data, &pieces[small].0);
1040            let mut neighbours: Vec<usize> = Vec::new();
1041            for &t in &pieces[small].0 {
1042                for &other in &facet_neighbors[facet_of[local[&t]]] {
1043                    let piece = piece_of_facet[other];
1044                    if piece != usize::MAX && piece != small && !neighbours.contains(&piece) {
1045                        neighbours.push(piece);
1046                    }
1047                }
1048            }
1049            let best = neighbours
1050                .iter()
1051                .copied()
1052                .filter(|&large| area[large] > area[small])
1053                .filter(|&large| {
1054                    !refused
1055                        .iter()
1056                        .any(|(a, b)| *a == pieces[small].0 && *b == pieces[large].0)
1057                })
1058                .filter_map(|large| {
1059                    let carrier = &pieces[large].1.fit.carrier;
1060                    let worst = verts
1061                        .iter()
1062                        .map(|&v| carrier_distance(carrier, data.verts[v]))
1063                        .fold(0.0_f64, f64::max);
1064                    (worst <= bar).then_some((large, worst))
1065                })
1066                .min_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)));
1067            if let Some((large, worst)) = best {
1068                merge = Some((small, large, worst));
1069                break;
1070            }
1071        }
1072        let Some((small, large, worst)) = merge else {
1073            break;
1074        };
1075        let mut union: Vec<u32> = pieces[large].0.iter().chain(pieces[small].0.iter()).copied().collect();
1076        union.sort_unstable();
1077        let outcome = fit_peeled(data, &union, options);
1078        let rejoined = outcome.accepted
1079            && outcome.fit.carrier.kind() == pieces[large].1.fit.carrier.kind();
1080        if debug {
1081            eprintln!(
1082                "[seg] peel absorb: {} piece of {} tris lies on the {} piece of {} tris at {worst:.3e} (bar {bar:.3e}); union {} accepted={} max_dev={:.3e}",
1083                pieces[small].1.fit.carrier.kind(),
1084                pieces[small].0.len(),
1085                pieces[large].1.fit.carrier.kind(),
1086                pieces[large].0.len(),
1087                outcome.fit.carrier.kind(),
1088                outcome.accepted,
1089                outcome.fit.max_dev
1090            );
1091        }
1092        if rejoined {
1093            pieces[large] = (union, outcome);
1094            pieces.remove(small);
1095        } else {
1096            refused.push((pieces[small].0.clone(), pieces[large].0.clone()));
1097        }
1098    }
1099}
1100
1101/// The cascade's verdict on a peeled piece. The cascade keeps its plain
1102/// torus fit; a torus the peel grew and judged at the precision bar carries
1103/// the vertex-refined carrier instead, so a mesh rebuild gets its true
1104/// axis and radii.
1105fn fit_peeled(data: &MeshData, tris: &[u32], options: &SegmentOptions) -> RegionOutcome {
1106    let mut outcome = fit_region(data, tris, options);
1107    if outcome.accepted && outcome.fit.carrier.kind() == "torus" {
1108        let verts = region_vertices(data, tris);
1109        if let Some(refined) =
1110            refine_torus_carrier(data, tris, &verts, &outcome.fit.carrier, TORUS_REFINE_ITERATIONS)
1111        {
1112            if refined.max_dev < outcome.fit.max_dev {
1113                outcome.fit = refined;
1114            }
1115        }
1116    }
1117    outcome
1118}
1119
1120/// Whether a torus region's vertices surround its axis with no azimuthal gap
1121/// wider than a twelfth of a turn.
1122fn covers_full_azimuth(data: &MeshData, tri_ids: &[u32], carrier: &RegionCarrier) -> bool {
1123    let RegionCarrier::Torus { center, axis_dir, .. } = carrier else {
1124        return false;
1125    };
1126    let Ok(axis) = axis_dir.normalized() else {
1127        return false;
1128    };
1129    let Ok(x_axis) = axis.perpendicular() else {
1130        return false;
1131    };
1132    let y_axis = axis.cross(x_axis);
1133    let mut angles = region_vertices(data, tri_ids)
1134        .into_iter()
1135        .map(|v| {
1136            let d = data.verts[v].sub(*center);
1137            d.dot(y_axis).atan2(d.dot(x_axis))
1138        })
1139        .collect::<Vec<_>>();
1140    if angles.len() < 3 {
1141        return false;
1142    }
1143    angles.sort_by(f64::total_cmp);
1144    let wrap = angles[0] + std::f64::consts::TAU - angles[angles.len() - 1];
1145    let widest = angles
1146        .windows(2)
1147        .map(|pair| pair[1] - pair[0])
1148        .fold(wrap, f64::max);
1149    widest <= std::f64::consts::TAU / 12.0
1150}
1151
1152/// A leftover strip at the tangent junction of DIFFERENT carriers (the
1153/// first row of a fillet torus against its cylinder) is not one carrier's
1154/// gap, but each of its triangles still lies on exactly one side. A triangle
1155/// joins the adjacent piece whose carrier holds all three of its vertices
1156/// within the peel's precision bar (the closest when several do), and a
1157/// piece that took any is re-fitted and must still pass the cascade as the
1158/// same kind, or it keeps its old triangles and they stay out. A triangle
1159/// no adjacent carrier holds at the bar is returned.
1160fn straddle_rejoin(
1161    data: &MeshData,
1162    options: &SegmentOptions,
1163    bar: f64,
1164    pieces: &mut [(Vec<u32>, RegionOutcome)],
1165    adjacent_pieces: &[usize],
1166    component: Vec<u32>,
1167) -> Vec<u32> {
1168    let mut taken: Vec<Vec<u32>> = vec![Vec::new(); adjacent_pieces.len()];
1169    let mut left = Vec::new();
1170    for t in component {
1171        let tri = &data.tris[t as usize];
1172        let best = adjacent_pieces
1173            .iter()
1174            .enumerate()
1175            .filter_map(|(slot, &piece)| {
1176                let carrier = &pieces[piece].1.fit.carrier;
1177                let worst = tri
1178                    .verts
1179                    .iter()
1180                    .map(|&v| carrier_distance(carrier, data.verts[v]))
1181                    .fold(0.0_f64, f64::max);
1182                (worst <= bar).then_some((slot, worst))
1183            })
1184            .min_by(|a, b| a.1.total_cmp(&b.1));
1185        match best {
1186            Some((slot, _)) => taken[slot].push(t),
1187            None => left.push(t),
1188        }
1189    }
1190    for (slot, extra) in taken.into_iter().enumerate() {
1191        if extra.is_empty() {
1192            continue;
1193        }
1194        let piece = adjacent_pieces[slot];
1195        let mut union: Vec<u32> = pieces[piece].0.iter().chain(extra.iter()).copied().collect();
1196        union.sort_unstable();
1197        let outcome = fit_peeled(data, &union, options);
1198        if outcome.accepted && outcome.fit.carrier.kind() == pieces[piece].1.fit.carrier.kind() {
1199            pieces[piece] = (union, outcome);
1200        } else {
1201            left.extend(extra);
1202        }
1203    }
1204    left
1205}
1206
1207// ---------------------------------------------------------------------------
1208// Entry point
1209// ---------------------------------------------------------------------------
1210
1211/// Segment a triangle mesh into smooth regions and recognize each region's
1212/// analytic carrier.  `positions` are xyz triples; `indices` is a triangle
1213/// index buffer, or empty to treat `positions` as a raw soup of consecutive
1214/// triangles (the STL layout of `read_stl`).
1215pub fn segment_mesh_faces(
1216    positions: &[f64],
1217    indices: &[u32],
1218    options: &SegmentOptions,
1219) -> Result<MeshSegmentation, String> {
1220    if !(options.deflection_angle_deg > 0.0) || !options.deflection_angle_deg.is_finite() {
1221        return Err("segment_mesh_faces: deflection angle must be positive".into());
1222    }
1223    if !(options.fit_tolerance > 0.0) || !options.fit_tolerance.is_finite() {
1224        return Err("segment_mesh_faces: fit tolerance must be positive".into());
1225    }
1226    let data = build_mesh_data(positions, indices, options)?;
1227    Ok(segment_prepared(&data, options))
1228}
1229
1230/// Segmentation core on an already-welded mesh: shared by the analysis entry
1231/// (`segment_mesh_faces`) and the BREP rebuild (`mesh_regions_to_brep`), so
1232/// both see identical triangle/vertex indexing.
1233pub(super) fn segment_prepared(data: &MeshData, options: &SegmentOptions) -> MeshSegmentation {
1234    segment_prepared_with(data, options, noisy_polyhedron_enabled())
1235}
1236
1237/// `BREP_MESH_NOISY_POLYHEDRON` (batch 102; promoted ON 2026-11-08,
1238/// promotion 15, `BREP_MESH_NOISY_POLYHEDRON=0` restores the old path): a
1239/// mesh whose every grown region reads as a plane within
1240/// [`NOISY_POLYHEDRON_PLANE_FACTOR`] times the plane bar is taken as a noisy
1241/// polyhedron, every region a plane. Switch grammar: `0|off|false` off,
1242/// `1|on|true` on, anything else the default. Read once per process.
1243pub(super) fn noisy_polyhedron_enabled() -> bool {
1244    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1245    *ENABLED.get_or_init(|| {
1246        match std::env::var("BREP_MESH_NOISY_POLYHEDRON").as_deref().map(str::to_ascii_lowercase).as_deref() {
1247            Ok("1" | "on" | "true") => true,
1248            Ok("0" | "off" | "false") => false,
1249            _ => true,
1250        }
1251    })
1252}
1253
1254/// How far past the cascade's plane bar (`fit_tolerance` times the region's
1255/// diagonal) a region of a noisy polyhedron may sit. The census's 14 jittered
1256/// boxes the plane bar refused read at most 6.6 times the bar, and no other
1257/// census mesh reads as all planes within 20 (`sim199b.py`).
1258const NOISY_POLYHEDRON_PLANE_FACTOR: f64 = 10.0;
1259
1260/// The most vertices a region past the plane bar may have and still be read
1261/// as jitter: the parameter count of the cascade's richest carrier (the
1262/// torus: centre, axis, two radii). With no more vertices than that a curved
1263/// carrier can pass through all of them, so the cascade's curved fit is no
1264/// evidence of curvature (the jittered box's two-triangle sides have four
1265/// vertices, and the sphere through them is exact). A region with more is
1266/// judged by its fit: the 0.25 mm dome of the app's domed-block fixture, 289
1267/// vertices, sits 5.7 times past its plane bar and is a dome, not noise
1268/// (promotion 15 gate, 2026-11-08). No census region past the bar has more
1269/// than four vertices (`sim203.py`).
1270const NOISY_POLYHEDRON_MAX_PAST_BAR_VERTICES: usize = 7;
1271
1272/// Every grown region as a plane, when every one of them fits a plane within
1273/// [`NOISY_POLYHEDRON_PLANE_FACTOR`] times the cascade's plane bar and the
1274/// normal tolerance, at least one of them is past the plane bar itself, and
1275/// every one past the bar has at most [`NOISY_POLYHEDRON_MAX_PAST_BAR_VERTICES`]
1276/// vertices. `None` otherwise, and the cascade decides as before.
1277///
1278/// A jittered box with two triangles per side gives each side four vertices
1279/// off one plane by more than the bar: the cascade then refuses the plane and
1280/// takes the sphere through those four points (exact by construction), or
1281/// leaves the side freeform. Judged one region at a time a wider plane bar
1282/// would also take the two-triangle islands that jitter cuts out of a
1283/// cylinder, so the bar widens only for a mesh that is planes everywhere.
1284fn noisy_polyhedron_regions(
1285    data: &MeshData,
1286    regions: &[Vec<u32>],
1287    options: &SegmentOptions,
1288) -> Option<Vec<(Vec<u32>, RegionOutcome)>> {
1289    let mut any_past_bar = false;
1290    let mut out = Vec::with_capacity(regions.len());
1291    for region in regions {
1292        let vert_ids = region_vertices(data, region);
1293        if region.len() < options.min_region_triangles || vert_ids.len() < 3 {
1294            return None;
1295        }
1296        let bbox = region_bbox(data, &vert_ids);
1297        let diag = bbox.1.sub(bbox.0).length();
1298        let scale = if diag > 0.0 { diag } else { data.diag.max(1e-12) };
1299        let tol_abs = options.fit_tolerance * scale;
1300        let fit = fit_plane(data, region, &vert_ids)?;
1301        if !(fit.max_dev.is_finite()
1302            && fit.max_dev <= NOISY_POLYHEDRON_PLANE_FACTOR * tol_abs
1303            && fit.max_normal_angle_deg <= options.normal_tolerance_deg)
1304        {
1305            return None;
1306        }
1307        if fit.max_dev > tol_abs {
1308            if vert_ids.len() > NOISY_POLYHEDRON_MAX_PAST_BAR_VERTICES {
1309                return None;
1310            }
1311            any_past_bar = true;
1312        }
1313        let area: f64 = region.iter().map(|&t| data.tris[t as usize].area).sum();
1314        out.push((
1315            region.clone(),
1316            RegionOutcome {
1317                fit,
1318                accepted: true,
1319                area,
1320                bbox,
1321                triangle_count: region.len(),
1322            },
1323        ));
1324    }
1325    any_past_bar.then_some(out)
1326}
1327
1328pub fn segment_prepared_with(
1329    data: &MeshData,
1330    options: &SegmentOptions,
1331    noisy_polyhedron: bool,
1332) -> MeshSegmentation {
1333    let mut raw_regions = grow_regions(data, options);
1334    absorb_tiny_regions(data, &mut raw_regions);
1335
1336    let noisy = if noisy_polyhedron {
1337        noisy_polyhedron_regions(data, &raw_regions, options)
1338    } else {
1339        None
1340    };
1341    if std::env::var("BREP_DEBUG_SEG").is_ok() && noisy.is_some() {
1342        eprintln!("[seg] noisy polyhedron: {} regions taken as planes", raw_regions.len());
1343    }
1344    // A noisy polyhedron skips the cascade: its regions are all planes.
1345    let cascade = if noisy.is_some() { Vec::new() } else { raw_regions };
1346    let mut final_regions: Vec<(Vec<u32>, RegionOutcome)> = noisy.unwrap_or_default();
1347    for region in cascade {
1348        let outcome = fit_region(data, &region, options);
1349        if outcome.accepted {
1350            final_regions.push((region, outcome));
1351            continue;
1352        }
1353        // Tangent-smooth compound (or genuinely freeform): try to split it.
1354        let pieces = refine_region(data, &region, options);
1355        if pieces.len() <= 1 {
1356            // Refinement did not split anything; keep the region whole.
1357            final_regions.push((region, outcome));
1358        } else {
1359            final_regions.extend(pieces);
1360        }
1361    }
1362
1363    // Reunite regions the growing/refinement pipeline split although they
1364    // lie on ONE carrier (a cap triangle isolated behind skipped slivers, a
1365    // blend peeled into two coaxial pieces).  Downstream consumers — the
1366    // BREP rebuild above all — rely on "one region per face".
1367    merge_compatible_regions(data, &mut final_regions, options);
1368
1369    let mut triangle_region_ids = vec![UNASSIGNED_REGION; data.tris.len()];
1370    let mut regions = Vec::with_capacity(final_regions.len());
1371    for (id, (tri_ids, outcome)) in final_regions.into_iter().enumerate() {
1372        for &t in &tri_ids {
1373            triangle_region_ids[t as usize] = id as u32;
1374        }
1375        regions.push(MeshRegion {
1376            id: id as u32,
1377            triangle_count: outcome.triangle_count,
1378            area: outcome.area,
1379            bbox_min: outcome.bbox.0,
1380            bbox_max: outcome.bbox.1,
1381            carrier: outcome.fit.carrier,
1382            max_deviation: outcome.fit.max_dev,
1383            rms_deviation: outcome.fit.rms_dev,
1384            max_normal_angle_deg: outcome.fit.max_normal_angle_deg,
1385        });
1386    }
1387
1388    // Attach degenerate/micro triangles to an adjacent region when one
1389    // exists: the neighbor whose carrier the sliver's vertices actually sit
1390    // on (a T-junction needle lies in one of its neighboring planes, not
1391    // on the fillet it happens to touch first).  Multi-pass so chains of
1392    // skipped slivers resolve through their assigned neighbors.
1393    let mut changed = true;
1394    while changed {
1395        changed = false;
1396        for t in 0..data.tris.len() {
1397            if triangle_region_ids[t] != UNASSIGNED_REGION {
1398                continue;
1399            }
1400            let tri = &data.tris[t];
1401            let mut adopted: Option<(f64, u32)> = None;
1402            for corner in 0..3 {
1403                let first = tri.verts[corner];
1404                let second = tri.verts[(corner + 1) % 3];
1405                if first == second {
1406                    continue;
1407                }
1408                if let Some(incident) = data.edges.get(&edge_key(first, second)) {
1409                    for &other in incident {
1410                        let region = triangle_region_ids[other as usize];
1411                        if other as usize == t || region == UNASSIGNED_REGION {
1412                            continue;
1413                        }
1414                        let carrier = &regions[region as usize].carrier;
1415                        let distance = tri
1416                            .verts
1417                            .iter()
1418                            .map(|&v| carrier_distance(carrier, data.verts[v]))
1419                            .fold(0.0_f64, f64::max);
1420                        let candidate = (distance, region);
1421                        adopted = Some(match adopted {
1422                            Some(current)
1423                                if current.0 < candidate.0
1424                                    || (current.0 == candidate.0 && current.1 <= candidate.1) =>
1425                            {
1426                                current
1427                            }
1428                            _ => candidate,
1429                        });
1430                    }
1431                }
1432            }
1433            if let Some((_, region)) = adopted {
1434                triangle_region_ids[t] = region;
1435                changed = true;
1436            }
1437        }
1438    }
1439
1440    MeshSegmentation {
1441        triangle_region_ids,
1442        regions,
1443        triangle_count: data.tris.len(),
1444        welded_vertex_count: data.verts.len(),
1445    }
1446}
1447
1448/// Outward carrier normal at a point (before the region's sense), or `None`
1449/// where the field is singular (on an axis, at a center) or for `Freeform`.
1450fn carrier_normal(carrier: &RegionCarrier, p: Vec3) -> Option<Vec3> {
1451    match carrier {
1452        RegionCarrier::Plane { normal, .. } => Some(*normal),
1453        RegionCarrier::Cylinder {
1454            axis_point,
1455            axis_dir,
1456            ..
1457        } => {
1458            let d = p.sub(*axis_point);
1459            d.sub(axis_dir.scale(d.dot(*axis_dir))).normalized().ok()
1460        }
1461        RegionCarrier::Cone {
1462            apex,
1463            axis_dir,
1464            half_angle_rad,
1465            ..
1466        } => {
1467            let d = p.sub(*apex);
1468            let radial = d.sub(axis_dir.scale(d.dot(*axis_dir))).normalized().ok()?;
1469            let (sin_a, cos_a) = half_angle_rad.sin_cos();
1470            Some(radial.scale(cos_a).sub(axis_dir.scale(sin_a)))
1471        }
1472        RegionCarrier::Sphere { center, .. } => p.sub(*center).normalized().ok(),
1473        RegionCarrier::Torus {
1474            center,
1475            axis_dir,
1476            major_radius,
1477            ..
1478        } => {
1479            let d = p.sub(*center);
1480            let s = d.dot(*axis_dir);
1481            let radial = d.sub(axis_dir.scale(s)).normalized().ok()?;
1482            let tube_center = center.add(radial.scale(*major_radius));
1483            p.sub(tube_center).normalized().ok()
1484        }
1485        RegionCarrier::Freeform => None,
1486    }
1487}
1488
1489/// The region's orientation sense as a sign, `1.0` for planes and freeform.
1490fn carrier_sense(carrier: &RegionCarrier) -> f64 {
1491    match carrier {
1492        RegionCarrier::Cylinder { sense, .. }
1493        | RegionCarrier::Cone { sense, .. }
1494        | RegionCarrier::Sphere { sense, .. }
1495        | RegionCarrier::Torus { sense, .. } => f64::from(*sense),
1496        _ => 1.0,
1497    }
1498}
1499
1500/// Distance of a point from a carrier; `Freeform` is infinitely far.
1501fn carrier_distance(carrier: &RegionCarrier, p: Vec3) -> f64 {
1502    match carrier {
1503        RegionCarrier::Plane { origin, normal } => p.sub(*origin).dot(*normal).abs(),
1504        RegionCarrier::Cylinder {
1505            axis_point,
1506            axis_dir,
1507            radius,
1508            ..
1509        } => {
1510            let d = p.sub(*axis_point);
1511            (d.sub(axis_dir.scale(d.dot(*axis_dir))).length() - radius).abs()
1512        }
1513        RegionCarrier::Cone {
1514            apex,
1515            axis_dir,
1516            half_angle_rad,
1517            ..
1518        } => {
1519            let d = p.sub(*apex);
1520            let s = d.dot(*axis_dir);
1521            let r = d.sub(axis_dir.scale(s)).length();
1522            ((r - s * half_angle_rad.tan()) * half_angle_rad.cos()).abs()
1523        }
1524        RegionCarrier::Sphere { center, radius, .. } => (p.sub(*center).length() - radius).abs(),
1525        RegionCarrier::Torus {
1526            center,
1527            axis_dir,
1528            major_radius,
1529            minor_radius,
1530            ..
1531        } => {
1532            let d = p.sub(*center);
1533            let s = d.dot(*axis_dir);
1534            let rho = d.sub(axis_dir.scale(s)).length();
1535            ((rho - major_radius).hypot(s) - minor_radius).abs()
1536        }
1537        RegionCarrier::Freeform => f64::INFINITY,
1538    }
1539}
1540
1541/// Do two accepted carriers describe the same surface (within `tol` for
1542/// distances, tight angular bands for directions)?  Freeform never matches.
1543/// `adjacent` says the regions share an edge: only then may two cylinder
1544/// fits disagree on their axis by the noise over the axial extent, because
1545/// two disjoint faces of one infinite cylinder (the two ends of a mirrored
1546/// part, the two levels of a slot) must stay two regions.
1547fn carriers_compatible(a: &RegionCarrier, b: &RegionCarrier, tol: f64, adjacent: bool) -> bool {
1548    const ANGULAR: f64 = 1e-6;
1549    match (a, b) {
1550        (
1551            RegionCarrier::Plane {
1552                origin: o1,
1553                normal: n1,
1554            },
1555            RegionCarrier::Plane {
1556                origin: o2,
1557                normal: n2,
1558            },
1559        ) => {
1560            n1.cross(*n2).length() <= ANGULAR
1561                && n1.dot(*n2) > 0.0
1562                && o2.sub(*o1).dot(*n1).abs() <= tol
1563        }
1564        (
1565            RegionCarrier::Cylinder {
1566                axis_point: p1,
1567                axis_dir: a1,
1568                radius: r1,
1569                sense: s1,
1570            },
1571            RegionCarrier::Cylinder {
1572                axis_point: p2,
1573                axis_dir: a2,
1574                radius: r2,
1575                sense: s2,
1576            },
1577        ) => {
1578            // Independent fits of one cylinder from noisy vertices disagree
1579            // on the axis direction by the noise over the axial extent; the
1580            // band is the angle that moves the surface by `tol` at the rim.
1581            // The union re-fit is the real test.
1582            let angular = if adjacent {
1583                ANGULAR.max(tol / r1.max(*r2).max(1e-12))
1584            } else {
1585                ANGULAR
1586            };
1587            let offset = p2.sub(*p1);
1588            s1 == s2
1589                && a1.cross(*a2).length() <= angular
1590                && (r1 - r2).abs() <= tol
1591                && offset.sub(a1.scale(offset.dot(*a1))).length() <= tol
1592        }
1593        (
1594            RegionCarrier::Cone {
1595                apex: p1,
1596                axis_dir: a1,
1597                half_angle_rad: h1,
1598                sense: s1,
1599            },
1600            RegionCarrier::Cone {
1601                apex: p2,
1602                axis_dir: a2,
1603                half_angle_rad: h2,
1604                sense: s2,
1605            },
1606        ) => {
1607            s1 == s2
1608                && a1.cross(*a2).length() <= ANGULAR
1609                && a1.dot(*a2) > 0.0
1610                && (h1 - h2).abs() <= ANGULAR
1611                && p2.sub(*p1).length() <= tol
1612        }
1613        (
1614            RegionCarrier::Sphere {
1615                center: c1,
1616                radius: r1,
1617                sense: s1,
1618            },
1619            RegionCarrier::Sphere {
1620                center: c2,
1621                radius: r2,
1622                sense: s2,
1623            },
1624        ) => s1 == s2 && c2.sub(*c1).length() <= tol && (r1 - r2).abs() <= tol,
1625        (
1626            RegionCarrier::Torus {
1627                center: c1,
1628                axis_dir: a1,
1629                major_radius: mj1,
1630                minor_radius: mn1,
1631                sense: s1,
1632            },
1633            RegionCarrier::Torus {
1634                center: c2,
1635                axis_dir: a2,
1636                major_radius: mj2,
1637                minor_radius: mn2,
1638                sense: s2,
1639            },
1640        ) => {
1641            s1 == s2
1642                && a1.cross(*a2).length() <= ANGULAR
1643                && c2.sub(*c1).length() <= tol
1644                && (mj1 - mj2).abs() <= tol
1645                && (mn1 - mn2).abs() <= tol
1646        }
1647        _ => false,
1648    }
1649}
1650
1651/// Merge edge-adjacent regions whose accepted carriers agree, repeating
1652/// until stable.  Adjacency counts paths THROUGH skipped (degenerate/micro)
1653/// triangles — exactly the fences that isolate cap islands in the first
1654/// place.  A merge is only applied when the union re-fits cleanly on the
1655/// same carrier kind, so this pass can only improve the segmentation.
1656fn merge_compatible_regions(
1657    data: &MeshData,
1658    regions: &mut Vec<(Vec<u32>, RegionOutcome)>,
1659    options: &SegmentOptions,
1660) {
1661    let tol = options.fit_tolerance * data.diag.max(1e-12);
1662    loop {
1663        let mut region_of = vec![usize::MAX; data.tris.len()];
1664        for (index, (tris, _)) in regions.iter().enumerate() {
1665            for &t in tris {
1666                region_of[t as usize] = index;
1667            }
1668        }
1669        // Directly edge-adjacent pairs.
1670        let mut direct: std::collections::BTreeSet<(usize, usize)> =
1671            std::collections::BTreeSet::new();
1672        for incident in data.edges.values() {
1673            if incident.len() != 2 {
1674                continue;
1675            }
1676            let (a, b) = (
1677                region_of[incident[0] as usize],
1678                region_of[incident[1] as usize],
1679            );
1680            if a != b && a != usize::MAX && b != usize::MAX {
1681                direct.insert((a.min(b), a.max(b)));
1682            }
1683        }
1684        let mut pairs = direct.clone();
1685        // Pairs bridged by connected runs of region-less (skipped) triangles.
1686        let mut seen = vec![false; data.tris.len()];
1687        for seed in 0..data.tris.len() {
1688            if seen[seed] || region_of[seed] != usize::MAX {
1689                continue;
1690            }
1691            let mut stack = vec![seed];
1692            let mut touched: Vec<usize> = Vec::new();
1693            seen[seed] = true;
1694            while let Some(t) = stack.pop() {
1695                let tri = &data.tris[t];
1696                for corner in 0..3 {
1697                    let first = tri.verts[corner];
1698                    let second = tri.verts[(corner + 1) % 3];
1699                    if first == second {
1700                        continue;
1701                    }
1702                    if let Some(incident) = data.edges.get(&edge_key(first, second)) {
1703                        for &other in incident {
1704                            let other = other as usize;
1705                            if other == t {
1706                                continue;
1707                            }
1708                            let region = region_of[other];
1709                            if region == usize::MAX {
1710                                if !seen[other] {
1711                                    seen[other] = true;
1712                                    stack.push(other);
1713                                }
1714                            } else if !touched.contains(&region) {
1715                                touched.push(region);
1716                            }
1717                        }
1718                    }
1719                }
1720            }
1721            touched.sort_unstable();
1722            for i in 0..touched.len() {
1723                for j in i + 1..touched.len() {
1724                    pairs.insert((touched[i], touched[j]));
1725                }
1726            }
1727        }
1728
1729        let mut merged_any = false;
1730        'pairs: for (a, b) in pairs {
1731            let (first, second) = (&regions[a], &regions[b]);
1732            if !first.1.accepted || !second.1.accepted {
1733                continue;
1734            }
1735            if !carriers_compatible(
1736                &first.1.fit.carrier,
1737                &second.1.fit.carrier,
1738                tol,
1739                direct.contains(&(a, b)),
1740            ) {
1741                continue;
1742            }
1743            let mut union: Vec<u32> = first.0.iter().chain(second.0.iter()).copied().collect();
1744            union.sort_unstable();
1745            let outcome = fit_region(data, &union, options);
1746            if !outcome.accepted || outcome.fit.carrier.kind() != first.1.fit.carrier.kind() {
1747                continue;
1748            }
1749            regions[a] = (union, outcome);
1750            regions.remove(b);
1751            merged_any = true;
1752            break 'pairs;
1753        }
1754        if !merged_any {
1755            return;
1756        }
1757    }
1758}