Skip to main content

brep_ransac/
recognize.rs

1use crate::fit::{
2    evaluate_surface, evaluate_surface_from_vertices, fit_profile_clock, fit_profile_note,
3    fit_profile_start, fit_profile_take, fit_surface_from_vertices_with_path, fit_surface_with_path,
4    selection_scale, vertex_selection_scale, FitProfile,
5};
6use crate::numerical::recognition as numerical;
7use crate::{
8    AdaptiveSampling, AnalyticSurface, AnalyzedMesh, ConstraintMask, FitPath, HypothesisPolicy,
9    Mesh, MeshAnalysisOptions, MetadataTrust, RecognitionError, RecognitionOptions,
10    RecognitionResult, SurfaceFitResult, SurfaceHint, SurfaceRegion, SurfaceType,
11    UnresolvedRegionDiagnostic,
12};
13use std::cmp::Ordering;
14use std::collections::{BTreeSet, VecDeque};
15use web_time::Instant;
16
17const TYPES: [SurfaceType; 5] = [
18    SurfaceType::Plane,
19    SurfaceType::Sphere,
20    SurfaceType::Cylinder,
21    SurfaceType::Cone,
22    SurfaceType::Torus,
23];
24
25const MODEL_COMPLEXITY_PENALTY_UNIT: f64 = numerical::MODEL_COMPLEXITY_PENALTY_UNIT;
26
27#[derive(Clone, Copy, Debug)]
28struct ModelRank {
29    numerically_exact: bool,
30    score: f64,
31}
32
33fn compare_model_rank(
34    left: ModelRank,
35    left_kind: SurfaceType,
36    right: ModelRank,
37    right_kind: SurfaceType,
38) -> Ordering {
39    right
40        .numerically_exact
41        .cmp(&left.numerically_exact)
42        .then_with(|| left.score.total_cmp(&right.score))
43        .then(left_kind.cmp(&right_kind))
44}
45
46/// Reconstruct one selected triangle region using an explicit metadata hint.
47///
48/// The selection and options are validated before fitting. Exact candidates
49/// are reused unchanged only after their position, normal, and support gates
50/// pass; weaker hints select the corresponding refinement path.
51pub fn reconstruct_surface(
52    mesh: &Mesh,
53    triangle_indices: &[usize],
54    hint: &SurfaceHint,
55    options: &RecognitionOptions,
56) -> Result<SurfaceFitResult, RecognitionError> {
57    options.validate()?;
58    let analyzed = mesh.analyze(&MeshAnalysisOptions {
59        feature_angle: options.feature_angle,
60        ..Default::default()
61    })?;
62    analyzed.validate_selection(triangle_indices)?;
63    reconstruct_analyzed(&analyzed, triangle_indices, hint, options)
64}
65
66/// Reconstruct one surface from an explicit subset of mesh vertices.
67///
68/// Unlike [`reconstruct_surface`], this entry point fits exactly the requested
69/// vertices; it does not expand them to their incident triangles. Per-vertex
70/// normals are used when supplied, otherwise area-weighted incident triangle
71/// normals are derived. `minimum_support` and `minimum_support_area` continue
72/// to gate the usable incident-triangle support represented by the vertices.
73pub fn reconstruct_surface_from_vertices(
74    mesh: &Mesh,
75    vertex_indices: &[usize],
76    hint: &SurfaceHint,
77    options: &RecognitionOptions,
78) -> Result<SurfaceFitResult, RecognitionError> {
79    options.validate()?;
80    let analyzed = mesh.analyze(&MeshAnalysisOptions {
81        feature_angle: options.feature_angle,
82        ..Default::default()
83    })?;
84    analyzed.validate_vertex_selection(vertex_indices)?;
85    reconstruct_selected(
86        &analyzed,
87        Selection::Vertices(vertex_indices),
88        hint,
89        options,
90    )
91}
92
93#[derive(Clone, Copy)]
94enum Selection<'a> {
95    Triangles(&'a [usize]),
96    Vertices(&'a [usize]),
97}
98
99impl Selection<'_> {
100    fn scale(self, mesh: &AnalyzedMesh) -> f64 {
101        match self {
102            Self::Triangles(ids) => selection_scale(mesh, ids),
103            Self::Vertices(ids) => vertex_selection_scale(mesh, ids),
104        }
105    }
106
107    fn fit(
108        self,
109        mesh: &AnalyzedMesh,
110        kind: SurfaceType,
111        initial: Option<AnalyticSurface>,
112        fixed: ConstraintMask,
113        options: &RecognitionOptions,
114        path: FitPath,
115    ) -> Result<SurfaceFitResult, RecognitionError> {
116        match self {
117            Self::Triangles(ids) => {
118                fit_surface_with_path(mesh, ids, kind, initial, fixed, options, path)
119            }
120            Self::Vertices(ids) => {
121                fit_surface_from_vertices_with_path(mesh, ids, kind, initial, fixed, options, path)
122            }
123        }
124    }
125
126    fn evaluate(
127        self,
128        mesh: &AnalyzedMesh,
129        surface: AnalyticSurface,
130        options: &RecognitionOptions,
131        path: FitPath,
132    ) -> Result<SurfaceFitResult, RecognitionError> {
133        match self {
134            Self::Triangles(ids) => evaluate_surface(mesh, ids, surface, options, path),
135            Self::Vertices(ids) => {
136                evaluate_surface_from_vertices(mesh, ids, surface, options, path)
137            }
138        }
139    }
140
141    fn accepted(self, model: &SurfaceFitResult, options: &RecognitionOptions, scale: f64) -> bool {
142        accepted_impl(
143            model,
144            options,
145            scale,
146            matches!(self, Self::Vertices(_))
147                || matches!(options.sampling, crate::SamplingMode::Vertices),
148        )
149    }
150}
151
152/// Discover and reconstruct analytic regions in an entire mesh.
153///
154/// This convenience entry point returns only accepted regions. Use
155/// [`recognize_surfaces_with_unresolved`] when the unassigned triangle
156/// partition is also required.
157pub fn recognize_surfaces(
158    mesh: &Mesh,
159    options: &RecognitionOptions,
160) -> Result<Vec<SurfaceRegion>, RecognitionError> {
161    Ok(recognize_surfaces_with_unresolved(mesh, options)?.regions)
162}
163
164/// Discover analytic regions and retain triangles that no model accepted.
165///
166/// Metadata sidecars are evaluated before generic connected-component
167/// extraction. Returned regions and unresolved triangle IDs are ordered
168/// deterministically for a fixed mesh, options, and seed.
169pub fn recognize_surfaces_with_unresolved(
170    mesh: &Mesh,
171    options: &RecognitionOptions,
172) -> Result<RecognitionResult, RecognitionError> {
173    recognize_budgeted(mesh, options, &mut AttemptBudget::unlimited(), &[])
174}
175
176/// Work spent by [`recognize_surfaces_with_attempt_budget`].
177///
178/// Non-exhaustive: a later counter is not a breaking change.
179#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
180#[non_exhaustive]
181pub struct RecognitionWork {
182    /// Generic hypotheses drawn, over every extraction round of every
183    /// connected component.
184    pub attempts: usize,
185    /// Regions accepted by generic extraction.
186    pub rounds: usize,
187    /// Whether the budget ran out before extraction finished. The regions
188    /// are then those accepted before the budget ran out (the round in
189    /// progress is dropped), so they are a prefix of the unbudgeted run's.
190    pub exhausted: bool,
191    /// Connected components accepted whole on a supplied
192    /// [`ComponentCandidate`] after their own whole fit was refused.
193    pub seeded_components: usize,
194    /// Generic hypotheses drawn per primitive kind, in the recognizer's kind
195    /// order (plane, sphere, cylinder, cone, torus).
196    pub hypotheses_by_kind: [usize; 5],
197    /// Extraction rounds that stopped because every kind's miss bound fell
198    /// to `1 - confidence` (the classical seed bound, or the adaptive
199    /// policy's product bound).
200    pub stops_at_risk_bound: usize,
201    /// Extraction rounds that stopped at `max_hypotheses` (or at one draw per
202    /// remaining triangle per kind, when that is smaller) with the bound not
203    /// yet met.
204    pub stops_at_hypothesis_cap: usize,
205    /// Extraction rounds of the adaptive policy that stopped because every
206    /// remaining triangle had seeded every kind.
207    pub stops_at_seed_exhaustion: usize,
208    /// Extraction rounds cut short by the attempt budget; the round's
209    /// candidates are dropped and `exhausted` is set.
210    pub stops_at_budget: usize,
211}
212
213impl RecognitionWork {
214    /// Adds the work of a component extracted on its own budget.
215    fn absorb(&mut self, other: &RecognitionWork) {
216        self.attempts += other.attempts;
217        self.rounds += other.rounds;
218        self.exhausted |= other.exhausted;
219        self.seeded_components += other.seeded_components;
220        for (mine, theirs) in self.hypotheses_by_kind.iter_mut().zip(&other.hypotheses_by_kind) {
221            *mine += theirs;
222        }
223        self.stops_at_risk_bound += other.stops_at_risk_bound;
224        self.stops_at_hypothesis_cap += other.stops_at_hypothesis_cap;
225        self.stops_at_seed_exhaustion += other.stops_at_seed_exhaustion;
226        self.stops_at_budget += other.stops_at_budget;
227    }
228}
229
230/// Where generic extraction spent its wall time and its work, returned by
231/// [`recognize_surfaces_with_extraction_profile`]. A measuring aid for the
232/// validation probes, not a stable interface: the fields follow the
233/// extraction loop. Seconds are summed over every hypothesis, so with more
234/// than one worker they exceed the wall time.
235#[doc(hidden)]
236#[derive(Clone, Debug, Default, PartialEq)]
237pub struct ExtractionProfile {
238    /// Wall time of generic extraction over every component (whole fits,
239    /// supplied candidates and the rounds), the denominator of the shares.
240    pub extraction_seconds: f64,
241    /// Whole-component fits and supplied-candidate validation.
242    pub whole_fit_seconds: f64,
243    /// Rebuilding the round's remaining ids and its seed schedules
244    /// (classical: one shuffle per kind; adaptive: the per-round tables).
245    pub seed_order_seconds: f64,
246    /// Adaptive only: the kind bandit and the Boltzmann seed draw.
247    pub seed_choice_seconds: f64,
248    /// Breadth-first probes around the seeds.
249    pub neighborhood_seconds: f64,
250    /// Normal-diverse near-minimal samples.
251    pub sample_seconds: f64,
252    /// Sample fits per kind, in the recognizer's kind order (plane, sphere,
253    /// cylinder, cone, torus).
254    pub fit_seconds: [f64; 5],
255    /// Sample fits per kind.
256    pub fits: [usize; 5],
257    /// Support growth (`support_component`).
258    pub support_seconds: f64,
259    /// Support refits whose support count was at least the round's
260    /// incumbent count when the hypothesis was drawn.
261    pub refit_winning_seconds: f64,
262    /// Support refits whose support count was below that incumbent: they
263    /// cannot replace it.
264    pub refit_dominated_seconds: f64,
265    /// Refit events (a probe chain can refit more than once).
266    pub refits_winning: usize,
267    /// Dominated refit events.
268    pub refits_dominated: usize,
269    /// Dominated refits whose outcome cannot change the probe chain's next
270    /// step (the support did not grow beyond its probe, or the probe was
271    /// exhausted), so skipping them is exact.
272    pub refits_dominated_exact: usize,
273    /// Seconds of those.
274    pub refit_dominated_exact_seconds: f64,
275    /// Ranking refits (`selection_scale`, `model_rank`).
276    pub rank_seconds: f64,
277    /// The share of `rank_seconds` spent on dominated refits.
278    pub rank_dominated_seconds: f64,
279    /// Rounds run, including abandoned ones.
280    pub rounds: usize,
281    /// Hypotheses drawn in those rounds.
282    pub seeds_consumed: usize,
283    /// `remaining × kinds` summed over those rounds: the seeds a full
284    /// schedule offers.
285    pub seed_slots: usize,
286    /// Triangles the support test ran on.
287    pub support_triangles_tested: usize,
288    /// Vertex distance evaluations of the support test.
289    pub distance_evaluations: usize,
290    /// Distinct vertices among those, per hypothesis, summed.
291    pub distinct_vertices_evaluated: usize,
292    /// Rounds that found no candidate and abandoned the rest of the
293    /// component.
294    pub abandoned_rounds: usize,
295    /// Triangles those rounds left unresolved.
296    pub abandoned_triangles: usize,
297    /// Abandoned remainders that still held a connected piece of at least
298    /// `minimum_support` triangles.
299    pub abandoned_with_piece: usize,
300    /// Triangles in such pieces.
301    pub abandoned_piece_triangles: usize,
302    /// Inside the sample fits (lane U row 1).
303    pub sample_fitter: FitProfile,
304    /// Inside the whole-component fits: model selection per kind.
305    pub whole_fitter: FitProfile,
306    /// Inside the support refits.
307    pub refit_fitter: FitProfile,
308    /// Torus sample fits by what came of them: the fit returned an error,
309    /// its support stayed under `minimum_support`, the support refit failed,
310    /// the refit succeeded.
311    pub torus_sample_outcomes: [usize; 4],
312    /// Seconds of those torus sample fits, by the same outcome.
313    pub torus_sample_outcome_seconds: [f64; 4],
314}
315
316impl ExtractionProfile {
317    fn absorb(&mut self, other: &ExtractionProfile) {
318        self.whole_fit_seconds += other.whole_fit_seconds;
319        self.seed_order_seconds += other.seed_order_seconds;
320        self.seed_choice_seconds += other.seed_choice_seconds;
321        self.neighborhood_seconds += other.neighborhood_seconds;
322        self.sample_seconds += other.sample_seconds;
323        for kind in 0..5 {
324            self.fit_seconds[kind] += other.fit_seconds[kind];
325            self.fits[kind] += other.fits[kind];
326        }
327        self.support_seconds += other.support_seconds;
328        self.refit_winning_seconds += other.refit_winning_seconds;
329        self.refit_dominated_seconds += other.refit_dominated_seconds;
330        self.refits_winning += other.refits_winning;
331        self.refits_dominated += other.refits_dominated;
332        self.refits_dominated_exact += other.refits_dominated_exact;
333        self.refit_dominated_exact_seconds += other.refit_dominated_exact_seconds;
334        self.rank_seconds += other.rank_seconds;
335        self.rank_dominated_seconds += other.rank_dominated_seconds;
336        self.rounds += other.rounds;
337        self.seeds_consumed += other.seeds_consumed;
338        self.seed_slots += other.seed_slots;
339        self.support_triangles_tested += other.support_triangles_tested;
340        self.distance_evaluations += other.distance_evaluations;
341        self.distinct_vertices_evaluated += other.distinct_vertices_evaluated;
342        self.abandoned_rounds += other.abandoned_rounds;
343        self.abandoned_triangles += other.abandoned_triangles;
344        self.abandoned_with_piece += other.abandoned_with_piece;
345        self.abandoned_piece_triangles += other.abandoned_piece_triangles;
346        self.sample_fitter.absorb(&other.sample_fitter);
347        self.whole_fitter.absorb(&other.whole_fitter);
348        self.refit_fitter.absorb(&other.refit_fitter);
349        for outcome in 0..4 {
350            self.torus_sample_outcomes[outcome] += other.torus_sample_outcomes[outcome];
351            self.torus_sample_outcome_seconds[outcome] += other.torus_sample_outcome_seconds[outcome];
352        }
353    }
354
355    /// Moves what this thread's fitter collected since [`fit_profile_start`]
356    /// into the bucket `slot` picks.
357    fn take_fitter(profile: &mut Option<Self>, slot: fn(&mut Self) -> &mut FitProfile) {
358        if let (Some(profile), Some(fitter)) = (profile, fit_profile_take()) {
359            slot(profile).absorb(&fitter);
360        }
361    }
362
363    /// One torus sample fit of `seconds` that ended in `outcome` (see
364    /// [`Self::torus_sample_outcomes`]).
365    fn torus_sample(&mut self, outcome: usize, seconds: f64) {
366        self.torus_sample_outcomes[outcome] += 1;
367        self.torus_sample_outcome_seconds[outcome] += seconds;
368    }
369
370    /// Adds the seconds since `started` to the field `slot` picks.
371    fn charge(profile: &mut Option<Self>, started: Option<Instant>, slot: fn(&mut Self) -> &mut f64) {
372        if let (Some(profile), Some(started)) = (profile, started) {
373            *slot(profile) += started.elapsed().as_secs_f64();
374        }
375    }
376
377    /// One support refit of `count` triangles against an incumbent of
378    /// `incumbent`; `exact` when skipping it could not change the chain.
379    fn refit(&mut self, started: Option<Instant>, count: usize, incumbent: usize, exact: bool) {
380        let seconds = started.map_or(0.0, |started| started.elapsed().as_secs_f64());
381        if count < incumbent {
382            self.refits_dominated += 1;
383            self.refit_dominated_seconds += seconds;
384            if exact {
385                self.refits_dominated_exact += 1;
386                self.refit_dominated_exact_seconds += seconds;
387            }
388        } else {
389            self.refits_winning += 1;
390            self.refit_winning_seconds += seconds;
391        }
392    }
393
394    /// An abandoned round: how much of `remaining` was a connected piece the
395    /// next round could still have drawn from.
396    fn abandon(&mut self, mesh: &AnalyzedMesh, remaining: &Remaining, options: &RecognitionOptions) {
397        self.abandoned_rounds += 1;
398        self.abandoned_triangles += remaining.len();
399        let ids: Vec<usize> = remaining.iter().copied().collect();
400        let pieces: usize = mesh
401            .connected_components(&ids, options.respect_features)
402            .iter()
403            .filter(|piece| piece.len() >= options.minimum_support)
404            .map(Vec::len)
405            .sum();
406        if pieces > 0 {
407            self.abandoned_with_piece += 1;
408            self.abandoned_piece_triangles += pieces;
409        }
410    }
411}
412
413/// Distance work of one support growth.
414#[derive(Default)]
415struct SupportTally {
416    triangles: usize,
417    evaluations: usize,
418    vertices: std::collections::HashSet<usize>,
419}
420
421/// [`recognize_surfaces_with_attempt_budget`], also returning where generic
422/// extraction spent its time. The regions and the work are those of the
423/// unprofiled call; only the clock reads differ.
424#[doc(hidden)]
425pub fn recognize_surfaces_with_extraction_profile(
426    mesh: &Mesh,
427    options: &RecognitionOptions,
428    max_attempts: usize,
429    kinds: &[SurfaceType],
430) -> Result<(RecognitionResult, RecognitionWork, ExtractionProfile), RecognitionError> {
431    let kinds: Vec<_> = TYPES.into_iter().filter(|kind| kinds.is_empty() || kinds.contains(kind)).collect();
432    let mut budget = AttemptBudget {
433        limit: Some(max_attempts),
434        kinds,
435        work: RecognitionWork::default(),
436        profile: Some(ExtractionProfile::default()),
437    };
438    let result = recognize_budgeted(mesh, options, &mut budget, &[])?;
439    Ok((result, budget.work, budget.profile.unwrap_or_default()))
440}
441
442fn kind_index(kind: SurfaceType) -> usize {
443    TYPES
444        .iter()
445        .position(|&candidate| candidate == kind)
446        .expect("every primitive kind is in TYPES")
447}
448
449/// A carrier another stage already fitted to exactly the triangles of one
450/// connected component, offered to [`recognize_surfaces_with_candidates`].
451#[derive(Clone, Debug, PartialEq)]
452pub struct ComponentCandidate {
453    /// The component's triangles, in any order.
454    pub triangle_indices: Vec<usize>,
455    /// The carrier to validate on them.
456    pub surface: AnalyticSurface,
457}
458
459/// Roundoff allowance, in units of `f64::EPSILON` times the coordinate
460/// magnitude, for a [`ComponentCandidate`] whose fitting stage measured its
461/// maximum vertex deviation with the same expression (see
462/// [`AnalyticSurface::signed_distance`]) in a different operation order.
463///
464/// Each distance is at most ~30 floating-point operations (the torus: 3
465/// subtractions, a 5-operation dot product, 6 for the axial projection, 6
466/// and a square root for its length, then 5 more and a second square root),
467/// every intermediate bounded by twice the magnitude `M` of the coordinates
468/// and parameters involved. Each operation contributes at most `eps / 2`
469/// relative error, so one evaluation is within `30 * eps * M` of the exact
470/// value and two evaluations differ by at most `60 * eps * M`; 64 rounds that
471/// up. It is not a tolerance on the fit: on the measured near-misses this
472/// path exists for, the refit missed by 1e-6 to 4e-5 relative, and the
473/// allowance is about 1e-14.
474const CANDIDATE_ROUNDOFF_EPSILONS: f64 = 64.0;
475
476/// [`recognize_surfaces_with_unresolved`] with a cap on the generic
477/// hypotheses drawn over the whole call, and optionally fewer primitive
478/// kinds to draw them for.
479///
480/// `max_hypotheses` bounds one extraction round only, and extraction keeps
481/// running rounds while any candidate reaches `minimum_support`; on a mesh
482/// where only small patches fit, the rounds, and the time, are unbounded.
483/// Up to the cap the run is identical to the unbudgeted one: hypotheses are
484/// drawn in the same deterministic order.
485///
486/// `kinds` limits generic hypotheses to those primitive kinds, drawn in the
487/// recognizer's own kind order; empty means every kind, and then the run is
488/// the unbudgeted one up to the cap. A component that one carrier explains
489/// whole is still classified among every kind.
490pub fn recognize_surfaces_with_attempt_budget(
491    mesh: &Mesh,
492    options: &RecognitionOptions,
493    max_attempts: usize,
494    kinds: &[SurfaceType],
495) -> Result<(RecognitionResult, RecognitionWork), RecognitionError> {
496    let kinds: Vec<_> = TYPES.into_iter().filter(|kind| kinds.is_empty() || kinds.contains(kind)).collect();
497    let mut budget = AttemptBudget {
498        limit: Some(max_attempts),
499        kinds,
500        work: RecognitionWork::default(),
501        profile: None,
502    };
503    let result = recognize_budgeted(mesh, options, &mut budget, &[])?;
504    Ok((result, budget.work))
505}
506
507/// [`recognize_surfaces_with_unresolved`], except that a connected component
508/// whose own whole fit is refused is first validated on a supplied candidate
509/// carrier for exactly its triangles before generic extraction divides it.
510///
511/// The candidate is accepted by the ordinary distance, normal and support
512/// gates, with only `CANDIDATE_ROUNDOFF_EPSILONS` added to the distance
513/// tolerance. A component whose whole fit passes, or that has no candidate,
514/// runs exactly as in [`recognize_surfaces_with_unresolved`], so with no
515/// candidates the result is identical. The returned work counts the
516/// generic hypotheses drawn and the components accepted on a candidate.
517pub fn recognize_surfaces_with_candidates(
518    mesh: &Mesh,
519    options: &RecognitionOptions,
520    candidates: &[ComponentCandidate],
521) -> Result<(RecognitionResult, RecognitionWork), RecognitionError> {
522    let mut budget = AttemptBudget::unlimited();
523    // Sorted triangle sets and their candidate carriers.
524    let candidates: Vec<(Vec<usize>, AnalyticSurface)> = candidates
525        .iter()
526        .map(|candidate| {
527            let mut ids = candidate.triangle_indices.clone();
528            ids.sort_unstable();
529            ids.dedup();
530            (ids, candidate.surface)
531        })
532        .collect();
533    let result = recognize_budgeted(mesh, options, &mut budget, &candidates)?;
534    Ok((result, budget.work))
535}
536
537struct AttemptBudget {
538    limit: Option<usize>,
539    /// Kinds generic hypotheses are drawn for, in [`TYPES`] order.
540    kinds: Vec<SurfaceType>,
541    work: RecognitionWork,
542    /// Collected only by [`recognize_surfaces_with_extraction_profile`].
543    profile: Option<ExtractionProfile>,
544}
545
546impl AttemptBudget {
547    fn unlimited() -> Self {
548        Self {
549            limit: None,
550            kinds: TYPES.to_vec(),
551            work: RecognitionWork::default(),
552            profile: None,
553        }
554    }
555
556    /// Takes up to `want` attempts, as many as the limit allows, without
557    /// marking the budget exhausted: the caller knows whether the run would
558    /// have asked for the attempt the limit refuses.
559    fn admit(&mut self, want: usize) -> usize {
560        if self.work.exhausted {
561            return 0;
562        }
563        let admitted = match self.limit {
564            Some(limit) => want.min(limit.saturating_sub(self.work.attempts)),
565            None => want,
566        };
567        self.work.attempts += admitted;
568        admitted
569    }
570
571    /// Returns admitted attempts the run turned out not to draw.
572    fn refund(&mut self, count: usize) {
573        self.work.attempts -= count;
574    }
575
576    /// Takes one attempt, or marks the budget exhausted and refuses.
577    fn take(&mut self) -> bool {
578        if self.work.exhausted || self.limit.is_some_and(|limit| self.work.attempts >= limit) {
579            self.work.exhausted = true;
580            return false;
581        }
582        self.work.attempts += 1;
583        true
584    }
585}
586
587fn recognize_budgeted(
588    mesh: &Mesh,
589    options: &RecognitionOptions,
590    budget: &mut AttemptBudget,
591    candidates: &[(Vec<usize>, AnalyticSurface)],
592) -> Result<RecognitionResult, RecognitionError> {
593    options.validate()?;
594    let analyzed = mesh.analyze(&MeshAnalysisOptions {
595        feature_angle: options.feature_angle,
596        ..Default::default()
597    })?;
598    let mut assigned = vec![false; analyzed.triangles.len()];
599    let mut regions = Vec::new();
600    let mut metadata_failures = Vec::new();
601    // Metadata regions are deliberately inspected before generic extraction.
602    for metadata in &analyzed.source_metadata {
603        let ids: Vec<_> = metadata
604            .triangle_indices
605            .iter()
606            .copied()
607            .filter(|&i| !assigned[i] && analyzed.triangles[i].area > 0.0)
608            .collect();
609        if ids.is_empty() {
610            continue;
611        }
612        let mut metadata_options = options.clone();
613        if let Some(source_tolerance) = metadata.source_tolerance {
614            metadata_options.distance_tolerance =
615                metadata_options.distance_tolerance.max(source_tolerance);
616        }
617        match reconstruct_analyzed(&analyzed, &ids, &metadata.hint, &metadata_options) {
618            Ok(mut fit)
619                if metadata
620                    .orientation
621                    .is_none_or(|orientation| orientation == fit.orientation) =>
622            {
623                if let Some(orientation) = metadata.orientation {
624                    fit.orientation = orientation;
625                }
626                if metadata.source_tolerance.is_some() || metadata.orientation.is_some() {
627                    fit.diagnostics.reason.push_str(
628                        "; source orientation and tolerance metadata validated when supplied",
629                    );
630                }
631                for &i in &ids {
632                    assigned[i] = true;
633                }
634                regions.push(to_region(fit, ids));
635            }
636            Ok(fit) => metadata_failures.push((
637                metadata.clone(),
638                ids,
639                format!(
640                    "supplied metadata orientation {:?} disagrees with reconstructed orientation {}",
641                    metadata.orientation, fit.orientation
642                ),
643            )),
644            Err(error) => metadata_failures.push((metadata.clone(), ids, error.to_string())),
645        }
646    }
647    let remaining: Vec<_> = analyzed
648        .all_non_degenerate()
649        .into_iter()
650        .filter(|&i| !assigned[i])
651        .collect();
652    let components = if options.discover_regions {
653        analyzed.connected_components(&remaining, options.respect_features)
654    } else {
655        vec![remaining]
656    };
657    let extraction_started = budget.profile.is_some().then(Instant::now);
658    extract_components(&analyzed, &components, options, candidates, &mut regions, budget);
659    ExtractionProfile::charge(&mut budget.profile, extraction_started, |p| &mut p.extraction_seconds);
660    if options.allow_disconnected_same_surface {
661        merge_disconnected_regions(&analyzed, options, &mut regions);
662    }
663    regions.sort_by_key(|region| {
664        region
665            .triangle_indices
666            .first()
667            .copied()
668            .unwrap_or(usize::MAX)
669    });
670    let mut covered = vec![false; analyzed.triangles.len()];
671    for region in &regions {
672        for &id in &region.triangle_indices {
673            covered[id] = true;
674        }
675    }
676    let unresolved_triangles = analyzed
677        .all_non_degenerate()
678        .into_iter()
679        .filter(|&id| !covered[id])
680        .collect::<Vec<_>>();
681    let unresolved_set: BTreeSet<_> = unresolved_triangles.iter().copied().collect();
682    let mut unresolved_diagnostics = metadata_failures
683        .into_iter()
684        .filter_map(|(metadata, ids, metadata_error)| {
685            let mut triangle_indices: Vec<_> = ids
686                .into_iter()
687                .filter(|id| unresolved_set.contains(id))
688                .collect();
689            triangle_indices.sort_unstable();
690            triangle_indices.dedup();
691            (!triangle_indices.is_empty()).then(|| UnresolvedRegionDiagnostic {
692                triangle_indices,
693                source_face_id: metadata.source_face_id,
694                source_face_name: metadata.source_face_name,
695                source_surface_id: metadata.source_surface_id,
696                reason: format!(
697                    "source metadata validation or reconstruction failed ({metadata_error}); generic analytic fallback also left this subset unresolved"
698                ),
699            })
700        })
701        .collect::<Vec<_>>();
702    unresolved_diagnostics.sort_by(|left, right| {
703        left.triangle_indices
704            .cmp(&right.triangle_indices)
705            .then_with(|| left.source_face_id.cmp(&right.source_face_id))
706            .then_with(|| left.source_face_name.cmp(&right.source_face_name))
707            .then_with(|| left.source_surface_id.cmp(&right.source_surface_id))
708            .then_with(|| left.reason.cmp(&right.reason))
709    });
710    Ok(RecognitionResult {
711        regions,
712        unresolved_triangles,
713        unresolved_diagnostics,
714    })
715}
716
717/// Reconstruct a selected triangle region from an already analyzed mesh.
718///
719/// Integration crates can use this seam to avoid repeating mesh analysis when
720/// validating many independently owned source faces.
721#[doc(hidden)]
722pub fn reconstruct_analyzed(
723    mesh: &AnalyzedMesh,
724    ids: &[usize],
725    hint: &SurfaceHint,
726    options: &RecognitionOptions,
727) -> Result<SurfaceFitResult, RecognitionError> {
728    // This crate-private entry point is used by STEP validation to reuse mesh
729    // analysis across recognition modes. It must preserve every public-entry
730    // invariant rather than assuming its caller already validated options.
731    options.validate()?;
732    mesh.validate_selection(ids)?;
733    reconstruct_selected(mesh, Selection::Triangles(ids), hint, options)
734}
735
736fn reconstruct_selected(
737    mesh: &AnalyzedMesh,
738    selection: Selection<'_>,
739    hint: &SurfaceHint,
740    options: &RecognitionOptions,
741) -> Result<SurfaceFitResult, RecognitionError> {
742    let scale = selection.scale(mesh);
743    let metadata_started = options.collect_phase_timings.then(Instant::now);
744    let metadata_trust = match hint {
745        SurfaceHint::Unknown => MetadataTrust::Unknown,
746        SurfaceHint::KnownType { .. } => MetadataTrust::TypeOnly,
747        SurfaceHint::InitialGuess { trust, .. } | SurfaceHint::Constrained { trust, .. } => *trust,
748        SurfaceHint::ExactCandidate { .. } => MetadataTrust::Exact,
749    };
750    let metadata_seconds = metadata_started.map(|started| started.elapsed().as_secs_f64());
751    let result = match hint {
752        SurfaceHint::Unknown => best_model(
753            mesh,
754            selection,
755            scale,
756            options,
757            FitPath::GenericRecognition,
758            None,
759            ConstraintMask::default(),
760        ),
761        SurfaceHint::KnownType { surface_type } => fit_result(
762            mesh,
763            selection,
764            *surface_type,
765            None,
766            ConstraintMask::default(),
767            scale,
768            options,
769            FitPath::KnownTypeFit,
770            true,
771            None,
772        ),
773        SurfaceHint::InitialGuess { surface, trust } => {
774            if matches!(
775                trust,
776                crate::MetadataTrust::Exact | crate::MetadataTrust::StrongHint
777            ) {
778                let mut valid = selection.evaluate(mesh, *surface, options, FitPath::HintReused)?;
779                if selection.accepted(&valid, options, scale) {
780                    valid.diagnostics.reason = "supplied parameters validated".into();
781                    valid.diagnostics.metadata_trust = metadata_trust;
782                    valid.diagnostics.phase_timings.metadata_inspection_seconds = metadata_seconds;
783                    return Ok(valid);
784                }
785            }
786            fit_result(
787                mesh,
788                selection,
789                surface.surface_type(),
790                Some(*surface),
791                ConstraintMask::default(),
792                scale,
793                options,
794                FitPath::UnconstrainedRefinement,
795                true,
796                Some(*surface),
797            )
798        }
799        SurfaceHint::Constrained {
800            surface_type,
801            constraints,
802            ..
803        } => {
804            if constraints.initial.is_none() && constraints.fixed != ConstraintMask::default() {
805                return Err(RecognitionError::InvalidSelection(
806                    "fixed constraints require initial parameter values".into(),
807                ));
808            }
809            fit_result(
810                mesh,
811                selection,
812                *surface_type,
813                constraints.initial,
814                constraints.fixed,
815                scale,
816                options,
817                FitPath::ConstrainedRefinement,
818                true,
819                constraints.initial,
820            )
821        }
822        SurfaceHint::ExactCandidate { surface } => {
823            let mut valid =
824                selection.evaluate(mesh, *surface, options, FitPath::ExactCandidateReused)?;
825            if selection.accepted(&valid, options, scale) {
826                valid.diagnostics.fixed_parameters = ConstraintMask {
827                    origin_or_center: true,
828                    axis_or_normal: true,
829                    radius: true,
830                    major_radius: true,
831                    angle: true,
832                };
833                valid.diagnostics.reason =
834                    "exact source parameters validated and were reused unchanged".into();
835                valid.diagnostics.metadata_trust = metadata_trust;
836                valid.diagnostics.phase_timings.metadata_inspection_seconds = metadata_seconds;
837                return Ok(valid);
838            }
839            fit_result(
840                mesh,
841                selection,
842                surface.surface_type(),
843                Some(*surface),
844                ConstraintMask::default(),
845                scale,
846                options,
847                FitPath::HintRejectedFallback,
848                true,
849                Some(*surface),
850            )
851            .or_else(|_| {
852                best_model(
853                    mesh,
854                    selection,
855                    scale,
856                    options,
857                    FitPath::HintRejectedFallback,
858                    Some(*surface),
859                    ConstraintMask::default(),
860                )
861            })
862        }
863    }?;
864    Ok(with_metadata_diagnostics(
865        result,
866        metadata_trust,
867        metadata_seconds,
868    ))
869}
870
871fn with_metadata_diagnostics(
872    mut result: SurfaceFitResult,
873    trust: MetadataTrust,
874    elapsed_seconds: Option<f64>,
875) -> SurfaceFitResult {
876    result.diagnostics.metadata_trust = trust;
877    result.diagnostics.phase_timings.metadata_inspection_seconds = elapsed_seconds;
878    result
879}
880
881#[allow(clippy::too_many_arguments)]
882fn fit_result(
883    mesh: &AnalyzedMesh,
884    selection: Selection<'_>,
885    kind: SurfaceType,
886    initial: Option<AnalyticSurface>,
887    fixed: ConstraintMask,
888    scale: f64,
889    options: &RecognitionOptions,
890    path: FitPath,
891    skipped: bool,
892    supplied: Option<AnalyticSurface>,
893) -> Result<SurfaceFitResult, RecognitionError> {
894    let mut fitted = selection.fit(mesh, kind, initial, fixed, options, path)?;
895    let evaluation_started = options.collect_phase_timings.then(Instant::now);
896    if !selection.accepted(&fitted, options, scale) {
897        return Err(RecognitionError::FitFailed {
898            surface: Some(kind.name()),
899            reason: format!(
900                "residuals exceed tolerance (max {:.3e}, normal {:.3e} rad)",
901                fitted.metrics.max_error, fitted.metrics.max_normal_error
902            ),
903        });
904    }
905    fitted.diagnostics.generic_classification_skipped = skipped;
906    fitted.diagnostics.supplied_surface = supplied;
907    fitted.diagnostics.reason = "requested model fitted and validated".into();
908    fitted
909        .diagnostics
910        .phase_timings
911        .candidate_evaluation_seconds =
912        evaluation_started.map(|started| started.elapsed().as_secs_f64());
913    Ok(fitted)
914}
915
916fn best_model(
917    mesh: &AnalyzedMesh,
918    selection: Selection<'_>,
919    scale: f64,
920    options: &RecognitionOptions,
921    path: FitPath,
922    supplied: Option<AnalyticSurface>,
923    fixed: ConstraintMask,
924) -> Result<SurfaceFitResult, RecognitionError> {
925    best_model_impl(mesh, selection, scale, options, path, supplied, fixed, true)
926}
927
928#[allow(clippy::too_many_arguments)]
929fn best_model_impl(
930    mesh: &AnalyzedMesh,
931    selection: Selection<'_>,
932    scale: f64,
933    options: &RecognitionOptions,
934    path: FitPath,
935    supplied: Option<AnalyticSurface>,
936    fixed: ConstraintMask,
937    use_score_bounds: bool,
938) -> Result<SurfaceFitResult, RecognitionError> {
939    let evaluation_started = options.collect_phase_timings.then(Instant::now);
940    let mut tally = SelectionTally::start(selection);
941    let tolerance = options.distance_tolerance + options.relative_tolerance * scale.max(1.0);
942    let mut candidates = Vec::new();
943    let mut rejected = Vec::new();
944    for kind in TYPES {
945        let fit_started = tally.clock(&candidates);
946        match selection.fit(mesh, kind, None, fixed, options, path) {
947            Ok(model) if selection.accepted(&model, options, scale) => {
948                let rank_started = tally.fitted(fit_started, kind, 0);
949                let rank = model_rank(
950                    mesh,
951                    selection,
952                    kind,
953                    &model,
954                    tolerance,
955                    options.normal_tolerance,
956                );
957                tally.ranked(rank_started);
958                candidates.push((rank, kind, model));
959            }
960            Ok(model) => {
961                tally.fitted(fit_started, kind, 1);
962                rejected.push((
963                    kind,
964                    format!(
965                        "max distance {:.3e}, max normal {:.3e}",
966                        model.metrics.max_error, model.metrics.max_normal_error
967                    ),
968                ))
969            }
970            Err(e) => {
971                tally.fitted(fit_started, kind, 2);
972                rejected.push((kind, e.to_string()))
973            }
974        }
975        if use_score_bounds {
976            if let Some(bound) = unseen_model_score_lower_bound(kind) {
977                if let Some((best_index, rank, best_kind)) = candidates
978                    .iter()
979                    .enumerate()
980                    .min_by(|(_, a), (_, b)| compare_model_rank(a.0, a.1, b.0, b.1))
981                    .map(|(index, candidate)| (index, candidate.0, candidate.1))
982                {
983                    // A merely tolerance-valid simple model cannot rule out a
984                    // more complex carrier that fits at conditioned roundoff.
985                    // Once the current best is itself numerically exact, the
986                    // residual terms are non-negative and the ordinary score
987                    // lower bound is safe within the exact tier.
988                    if rank.numerically_exact && rank.score < bound {
989                        tally.finish(Some(best_kind), true);
990                        let (_, _, model) = candidates.remove(best_index);
991                        record_tolerance_valid_losers(&mut rejected, candidates, best_kind, rank);
992                        rejected.sort_by_key(|(candidate_kind, _)| *candidate_kind);
993                        let reason = format!(
994                            "{} selected after {} candidate(s) from a score below every unseen model's proven lower bound",
995                            best_kind.name(),
996                            kind as usize + 1,
997                        );
998                        return Ok(decorate_best_model(
999                            model,
1000                            supplied,
1001                            fixed,
1002                            kind as usize + 1,
1003                            rejected,
1004                            &reason,
1005                            evaluation_started.as_ref(),
1006                        ));
1007                    }
1008                }
1009            }
1010        }
1011    }
1012    // A sphere is the R = 0 limit of the torus parameterization. Triangle
1013    // centroids from a faceted sphere have latitude-dependent chord error, so
1014    // an unconstrained torus can otherwise absorb that discretization with a
1015    // tiny, numerically meaningless major radius. If both carriers pass every
1016    // geometric gate and R is below the configured spatial resolution, the
1017    // torus's extra axis and radius are not identifiable; retain the simpler
1018    // sphere. This does not suppress a torus when the sphere fails validation.
1019    let filter_started = tally.filter_clock();
1020    let valid_sphere = candidates
1021        .iter()
1022        .any(|(_, kind, _)| *kind == SurfaceType::Sphere);
1023    if valid_sphere {
1024        let mut retained = Vec::with_capacity(candidates.len());
1025        for (rank, kind, model) in candidates {
1026            let sphere_limit_major_radius = match &model.surface {
1027                AnalyticSurface::Torus(torus) if torus.major_radius <= tolerance => {
1028                    Some(torus.major_radius)
1029                }
1030                _ => None,
1031            };
1032            if kind == SurfaceType::Torus {
1033                if let Some(major_radius) = sphere_limit_major_radius {
1034                    rejected.push((
1035                        kind,
1036                        format!(
1037                            "tolerance-valid candidate excluded as a non-identifiable sphere-limit torus: score {:.6e}, numerically_exact={}, major radius {major_radius:.3e} <= spatial tolerance {tolerance:.3e}; rms distance {:.3e}, max distance {:.3e}, rms normal {:.3e}, max normal {:.3e}",
1038                            rank.score,
1039                            rank.numerically_exact,
1040                            model.metrics.rms_error,
1041                            model.metrics.max_error,
1042                            model.metrics.rms_normal_error,
1043                            model.metrics.max_normal_error,
1044                        ),
1045                    ));
1046                    continue;
1047                }
1048            }
1049            retained.push((rank, kind, model));
1050        }
1051        candidates = retained;
1052    }
1053    // A cylinder is the infinite-major-radius limit of a torus.  On a short
1054    // faceted cylindrical patch an unconstrained torus can move its spine far
1055    // away and absorb a few units of coordinate quantization while providing
1056    // no second-curvature evidence in the normal field.  When both candidates
1057    // pass every geometric gate, retain the simpler cylinder if the torus is
1058    // not in a stronger numerical-exactness tier, does not improve RMS normal
1059    // agreement, and its RMS-position gain is below the configured fraction
1060    // of spatial resolution.  A genuine exact torus still outranks an inexact
1061    // cylinder, and a measurably curved torus remains available to the
1062    // observability safeguard or ordinary residual ranking.
1063    if let Some((cylinder_rank, _, cylinder)) = candidates
1064        .iter()
1065        .find(|(_, kind, _)| *kind == SurfaceType::Cylinder)
1066        .cloned()
1067    {
1068        let mut retained = Vec::with_capacity(candidates.len());
1069        for (rank, kind, model) in candidates {
1070            if kind == SurfaceType::Torus
1071                && torus_is_non_identifiable_cylinder_limit(
1072                    rank,
1073                    &model.metrics,
1074                    cylinder_rank,
1075                    &cylinder.metrics,
1076                    tolerance,
1077                )
1078            {
1079                let rms_gain = (cylinder.metrics.rms_error - model.metrics.rms_error).max(0.0);
1080                rejected.push((
1081                    kind,
1082                    format!(
1083                        "tolerance-valid candidate excluded as a non-identifiable cylinder-limit torus: score {:.6e}, numerically_exact={}, RMS-position gain {rms_gain:.3e} <= {:.3e} (1% of spatial tolerance), torus RMS normal {:.3e} >= cylinder RMS normal {:.3e}; rms distance {:.3e}, max distance {:.3e}, max normal {:.3e}",
1084                        rank.score,
1085                        rank.numerically_exact,
1086                        tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION,
1087                        model.metrics.rms_normal_error,
1088                        cylinder.metrics.rms_normal_error,
1089                        model.metrics.rms_error,
1090                        model.metrics.max_error,
1091                        model.metrics.max_normal_error,
1092                    ),
1093                ));
1094                continue;
1095            }
1096            retained.push((rank, kind, model));
1097        }
1098        candidates = retained;
1099    }
1100    // Complexity is a tie-breaker, not authority to discard observed second
1101    // curvature. Apply this only after the non-identifiable cylinder-limit
1102    // filter above: a surviving inexact torus may displace the cylinder when
1103    // it Pareto-improves every reported residual and either resolves position
1104    // at the existing spatial threshold or its oriented carrier-normal field
1105    // is distinguishable on the exact same samples. Exact-tier ordering stays
1106    // authoritative and therefore never enters this override.
1107    if let (Some((torus_rank, _, torus)), Some((cylinder_rank, _, cylinder))) = (
1108        candidates
1109            .iter()
1110            .find(|(_, kind, _)| *kind == SurfaceType::Torus)
1111            .cloned(),
1112        candidates
1113            .iter()
1114            .find(|(_, kind, _)| *kind == SurfaceType::Cylinder)
1115            .cloned(),
1116    ) {
1117        let carrier_normal_disagreement = max_oriented_carrier_normal_disagreement(
1118            mesh,
1119            selection,
1120            options.sampling,
1121            &torus,
1122            &cylinder,
1123        );
1124        if torus_observably_dominates_cylinder(
1125            torus_rank,
1126            &torus.metrics,
1127            cylinder_rank,
1128            &cylinder.metrics,
1129            tolerance,
1130            carrier_normal_disagreement,
1131        ) {
1132            let rms_position_gain = cylinder.metrics.rms_error - torus.metrics.rms_error;
1133            candidates.retain(|(_, kind, _)| *kind != SurfaceType::Cylinder);
1134            rejected.push((
1135                SurfaceType::Cylinder,
1136                format!(
1137                    "tolerance-valid cylinder excluded because the torus observably resolves second curvature: RMS-position gain {rms_position_gain:.3e} (threshold {:.3e}), oriented carrier-normal disagreement {:.3e} (threshold {:.3e}); torus RMS/max distance {:.3e}/{:.3e} versus cylinder {:.3e}/{:.3e}; torus RMS/max normal {:.3e}/{:.3e} versus cylinder {:.3e}/{:.3e}",
1138                    tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION,
1139                    carrier_normal_disagreement.unwrap_or(0.0),
1140                    numerical::EXACT_MODEL_NORMAL_ROUNDOFF_RADIANS,
1141                    torus.metrics.rms_error,
1142                    torus.metrics.max_error,
1143                    cylinder.metrics.rms_error,
1144                    cylinder.metrics.max_error,
1145                    torus.metrics.rms_normal_error,
1146                    torus.metrics.max_normal_error,
1147                    cylinder.metrics.rms_normal_error,
1148                    cylinder.metrics.max_normal_error,
1149                ),
1150            ));
1151        }
1152    }
1153    tally.filtered(filter_started);
1154    candidates.sort_by(|a, b| compare_model_rank(a.0, a.1, b.0, b.1));
1155    tally.finish(candidates.first().map(|candidate| candidate.1), false);
1156    if candidates.is_empty() {
1157        return Err(RecognitionError::FitFailed {
1158            surface: None,
1159            reason: "no analytic model passed distance, normal, and support gates".into(),
1160        });
1161    }
1162    let (selected_rank, selected_kind, model) = candidates.remove(0);
1163    record_tolerance_valid_losers(&mut rejected, candidates, selected_kind, selected_rank);
1164    rejected.sort_by_key(|(candidate_kind, _)| *candidate_kind);
1165    Ok(decorate_best_model(
1166        model,
1167        supplied,
1168        fixed,
1169        TYPES.len(),
1170        rejected,
1171        "best tolerance-valid model selected by numerical-exactness tier, residual score, and simplicity penalty",
1172        evaluation_started.as_ref(),
1173    ))
1174}
1175
1176/// [`FitProfile`] bookkeeping of one `best_model_impl` call, inert unless the
1177/// thread collects a profile.
1178struct SelectionTally {
1179    started: Option<Instant>,
1180    size: usize,
1181    /// Per kind: seconds of its fit, when it ran.
1182    seconds: [Option<f64>; 5],
1183    /// Per kind: 0 accepted, 1 failed the gates, 2 error.
1184    outcome: [u8; 5],
1185    after_exact: [bool; 5],
1186    after_valid: [bool; 5],
1187    rank_seconds: f64,
1188    filter_seconds: f64,
1189}
1190
1191impl SelectionTally {
1192    fn start(selection: Selection<'_>) -> Self {
1193        let size = match selection {
1194            Selection::Triangles(ids) | Selection::Vertices(ids) => ids.len(),
1195        };
1196        Self {
1197            started: fit_profile_clock(),
1198            size,
1199            seconds: [None; 5],
1200            outcome: [0; 5],
1201            after_exact: [false; 5],
1202            after_valid: [false; 5],
1203            rank_seconds: 0.0,
1204            filter_seconds: 0.0,
1205        }
1206    }
1207
1208    /// The clock before a kind's fit, noting what the earlier kinds left.
1209    fn clock(&mut self, candidates: &[(ModelRank, SurfaceType, SurfaceFitResult)]) -> Option<(Instant, bool, bool)> {
1210        self.started?;
1211        let exact = candidates.iter().any(|(rank, ..)| rank.numerically_exact);
1212        Some((Instant::now(), exact, !candidates.is_empty()))
1213    }
1214
1215    fn fitted(&mut self, started: Option<(Instant, bool, bool)>, kind: SurfaceType, outcome: u8) -> Option<Instant> {
1216        let (started, exact, valid) = started?;
1217        let index = kind_index(kind);
1218        self.seconds[index] = Some(started.elapsed().as_secs_f64());
1219        self.outcome[index] = outcome;
1220        self.after_exact[index] = exact;
1221        self.after_valid[index] = valid;
1222        Some(Instant::now())
1223    }
1224
1225    fn ranked(&mut self, started: Option<Instant>) {
1226        if let Some(started) = started {
1227            self.rank_seconds += started.elapsed().as_secs_f64();
1228        }
1229    }
1230
1231    fn filter_clock(&self) -> Option<Instant> {
1232        self.started.map(|_| Instant::now())
1233    }
1234
1235    fn filtered(&mut self, started: Option<Instant>) {
1236        if let Some(started) = started {
1237            self.filter_seconds += started.elapsed().as_secs_f64();
1238        }
1239    }
1240
1241    fn finish(&self, selected: Option<SurfaceType>, bound_exit: bool) {
1242        let tally = self;
1243        fit_profile_note(self.started, |profile, seconds| {
1244            profile.selections += 1;
1245            profile.selection_size += tally.size;
1246            profile.selections_bound_exit += usize::from(bound_exit);
1247            if selected.is_none() {
1248                profile.selections_failed += 1;
1249                profile.selections_failed_seconds += seconds;
1250            }
1251            profile.rank_seconds += tally.rank_seconds;
1252            profile.filter_seconds += tally.filter_seconds;
1253            for index in 0..5 {
1254                let Some(fit_seconds) = tally.seconds[index] else {
1255                    continue;
1256                };
1257                profile.kind_fits[index] += 1;
1258                profile.kind_seconds[index] += fit_seconds;
1259                match tally.outcome[index] {
1260                    1 => profile.kind_rejected[index] += 1,
1261                    2 => profile.kind_errors[index] += 1,
1262                    _ => {}
1263                }
1264                if selected.is_some_and(|kind| kind_index(kind) == index) {
1265                    profile.kind_won[index] += 1;
1266                } else {
1267                    if tally.outcome[index] == 0 {
1268                        profile.kind_valid_lost[index] += 1;
1269                    }
1270                    profile.kind_lost_seconds[index] += fit_seconds;
1271                }
1272                if tally.after_exact[index] {
1273                    profile.kind_after_exact[index] += 1;
1274                    profile.kind_after_exact_seconds[index] += fit_seconds;
1275                }
1276                if tally.after_valid[index] {
1277                    profile.kind_after_valid[index] += 1;
1278                    profile.kind_after_valid_seconds[index] += fit_seconds;
1279                }
1280            }
1281        });
1282    }
1283}
1284
1285fn torus_observably_dominates_cylinder(
1286    torus_rank: ModelRank,
1287    torus: &crate::FitMetrics,
1288    cylinder_rank: ModelRank,
1289    cylinder: &crate::FitMetrics,
1290    spatial_tolerance: f64,
1291    carrier_normal_disagreement: Option<f64>,
1292) -> bool {
1293    !torus_rank.numerically_exact
1294        && !cylinder_rank.numerically_exact
1295        && torus.rms_error <= cylinder.rms_error
1296        && torus.max_error <= cylinder.max_error
1297        && torus.rms_normal_error <= cylinder.rms_normal_error
1298        && torus.max_normal_error <= cylinder.max_normal_error
1299        && ((cylinder.rms_error - torus.rms_error)
1300            > spatial_tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION
1301            || carrier_normal_disagreement.is_some_and(|disagreement| {
1302                disagreement > numerical::EXACT_MODEL_NORMAL_ROUNDOFF_RADIANS
1303                    && torus.rms_normal_error < cylinder.rms_normal_error
1304            }))
1305}
1306
1307fn max_oriented_carrier_normal_disagreement(
1308    mesh: &AnalyzedMesh,
1309    selection: Selection<'_>,
1310    sampling: crate::SamplingMode,
1311    left: &SurfaceFitResult,
1312    right: &SurfaceFitResult,
1313) -> Option<f64> {
1314    let mut max_disagreement = 0.0_f64;
1315    let mut samples = 0_usize;
1316    let mut measure = |point| -> Option<()> {
1317        let left_normal = left.surface.normal_at(point)? * left.orientation as f64;
1318        let right_normal = right.surface.normal_at(point)? * right.orientation as f64;
1319        if !left_normal.is_finite() || !right_normal.is_finite() {
1320            return None;
1321        }
1322        let disagreement = left_normal.dot(right_normal).clamp(-1.0, 1.0).acos();
1323        if !disagreement.is_finite() {
1324            return None;
1325        }
1326        max_disagreement = max_disagreement.max(disagreement);
1327        samples += 1;
1328        Some(())
1329    };
1330
1331    match selection {
1332        Selection::Triangles(ids) => {
1333            if matches!(
1334                sampling,
1335                crate::SamplingMode::TriangleCentroids | crate::SamplingMode::CentroidsAndVertices
1336            ) {
1337                for &id in ids {
1338                    if mesh.triangles[id].area > 0.0 {
1339                        measure(mesh.triangles[id].centroid)?;
1340                    }
1341                }
1342            }
1343            if matches!(
1344                sampling,
1345                crate::SamplingMode::Vertices | crate::SamplingMode::CentroidsAndVertices
1346            ) {
1347                let vertices: BTreeSet<_> = ids
1348                    .iter()
1349                    .filter(|&&id| mesh.triangles[id].area > 0.0)
1350                    .flat_map(|&id| mesh.triangles[id].vertices)
1351                    .collect();
1352                for vertex in vertices {
1353                    measure(mesh.vertices[vertex])?;
1354                }
1355            }
1356        }
1357        Selection::Vertices(vertices) => {
1358            for &vertex in vertices {
1359                measure(mesh.vertices[vertex])?;
1360            }
1361        }
1362    }
1363    (samples > 0).then_some(max_disagreement)
1364}
1365
1366fn torus_is_non_identifiable_cylinder_limit(
1367    torus_rank: ModelRank,
1368    torus: &crate::FitMetrics,
1369    cylinder_rank: ModelRank,
1370    cylinder: &crate::FitMetrics,
1371    spatial_tolerance: f64,
1372) -> bool {
1373    (!torus_rank.numerically_exact || cylinder_rank.numerically_exact)
1374        && torus.rms_normal_error >= cylinder.rms_normal_error
1375        && (cylinder.rms_error - torus.rms_error).max(0.0)
1376            <= spatial_tolerance * numerical::TORUS_CYLINDER_LIMIT_RMS_GAIN_FRACTION
1377}
1378
1379fn record_tolerance_valid_losers(
1380    rejected: &mut Vec<(SurfaceType, String)>,
1381    mut candidates: Vec<(ModelRank, SurfaceType, SurfaceFitResult)>,
1382    selected_kind: SurfaceType,
1383    selected_rank: ModelRank,
1384) {
1385    candidates.sort_by_key(|(_, kind, _)| *kind);
1386    rejected.extend(candidates.into_iter().map(|(rank, kind, model)| {
1387        (
1388            kind,
1389            format!(
1390                "tolerance-valid candidate not selected: score {:.6e}, numerically_exact={} versus selected {} score {:.6e}, numerically_exact={}; rms distance {:.3e}, max distance {:.3e}, rms normal {:.3e}, max normal {:.3e}",
1391                rank.score,
1392                rank.numerically_exact,
1393                selected_kind.name(),
1394                selected_rank.score,
1395                selected_rank.numerically_exact,
1396                model.metrics.rms_error,
1397                model.metrics.max_error,
1398                model.metrics.rms_normal_error,
1399                model.metrics.max_normal_error,
1400            ),
1401        )
1402    }));
1403}
1404
1405
1406fn unseen_model_score_lower_bound(after: SurfaceType) -> Option<f64> {
1407    let degrees = match after {
1408        SurfaceType::Plane => 4.0,
1409        SurfaceType::Sphere => 5.0,
1410        SurfaceType::Cylinder => 6.0,
1411        SurfaceType::Cone => 8.0,
1412        SurfaceType::Torus => return None,
1413    };
1414    Some(degrees * MODEL_COMPLEXITY_PENALTY_UNIT)
1415}
1416
1417fn decorate_best_model(
1418    mut answer: SurfaceFitResult,
1419    supplied: Option<AnalyticSurface>,
1420    fixed: ConstraintMask,
1421    candidates_evaluated: usize,
1422    rejected_competitors: Vec<(SurfaceType, String)>,
1423    reason: &str,
1424    evaluation_started: Option<&Instant>,
1425) -> SurfaceFitResult {
1426    answer.diagnostics.supplied_surface = supplied;
1427    answer.diagnostics.fixed_parameters = fixed;
1428    answer.diagnostics.generic_classification_skipped = false;
1429    answer.diagnostics.reason = reason.into();
1430    answer.diagnostics.candidates_evaluated = candidates_evaluated;
1431    answer.diagnostics.rejected_competitors = rejected_competitors;
1432    answer
1433        .diagnostics
1434        .phase_timings
1435        .candidate_evaluation_seconds =
1436        evaluation_started.map(|started| started.elapsed().as_secs_f64());
1437    answer
1438}
1439
1440fn model_rank(
1441    mesh: &AnalyzedMesh,
1442    selection: Selection<'_>,
1443    kind: SurfaceType,
1444    model: &SurfaceFitResult,
1445    distance_tolerance: f64,
1446    normal_tolerance: f64,
1447) -> ModelRank {
1448    let vertices: BTreeSet<_> = match selection {
1449        Selection::Triangles(ids) => ids
1450            .iter()
1451            .flat_map(|&id| mesh.triangles[id].vertices)
1452            .collect(),
1453        Selection::Vertices(ids) => ids.iter().copied().collect(),
1454    };
1455    let coordinate_scale = vertices
1456        .into_iter()
1457        .map(|vertex| {
1458            let point = mesh.vertices[vertex];
1459            point.x.abs().max(point.y.abs()).max(point.z.abs())
1460        })
1461        .fold(1.0_f64, f64::max);
1462    let position_roundoff =
1463        numerical::EXACT_VERTEX_ROUNDOFF_MULTIPLIER * f64::EPSILON * coordinate_scale;
1464    ModelRank {
1465        numerically_exact: model.metrics.max_error <= position_roundoff
1466            && model.metrics.max_normal_error <= numerical::EXACT_MODEL_NORMAL_ROUNDOFF_RADIANS,
1467        score: model_selection_score(kind, &model.metrics, distance_tolerance, normal_tolerance),
1468    }
1469}
1470
1471fn model_selection_score(
1472    kind: SurfaceType,
1473    metrics: &crate::FitMetrics,
1474    distance_tolerance: f64,
1475    normal_tolerance: f64,
1476) -> f64 {
1477    let complexity = match kind {
1478        SurfaceType::Plane => 3.,
1479        SurfaceType::Sphere => 4.,
1480        SurfaceType::Cylinder => 5.,
1481        SurfaceType::Cone => 6.,
1482        SurfaceType::Torus => 8.,
1483    };
1484    // Complexity regularizes candidates within the same numerical-exactness
1485    // tier. `compare_model_rank` prevents that penalty from allowing a visibly
1486    // worse simple carrier to override a carrier fitted at conditioned
1487    // roundoff. This matters on tiny CAD patches where a sphere can pass a
1488    // loose acceptance tolerance while the source torus fits exactly.
1489    metrics.rms_error / distance_tolerance.max(numerical::SCORE_DISTANCE_DENOMINATOR_FLOOR)
1490        + metrics.rms_normal_error / normal_tolerance.max(numerical::SCORE_NORMAL_DENOMINATOR_FLOOR)
1491        + complexity * MODEL_COMPLEXITY_PENALTY_UNIT
1492}
1493
1494
1495fn accepted_impl(
1496    model: &SurfaceFitResult,
1497    options: &RecognitionOptions,
1498    scale: f64,
1499    vertex_samples_only: bool,
1500) -> bool {
1501    let distance = options.distance_tolerance + options.relative_tolerance * scale.max(1.0);
1502    // A trimmed CAD tessellation can contain pole/seam vertices whose supplied
1503    // derivative normals are singular or locally reversed even though the
1504    // vertices lie exactly on one carrier. In that machine-exact positional
1505    // case, retain the normal field as a global orientation/coherence check:
1506    // its area-weighted RMS must remain in the selected carrier normal's open
1507    // hemisphere. A few zero-area or low-area antipodal samples may therefore
1508    // survive, while a tangential, balanced, or generally incoherent field may
1509    // not. This positional threshold is intentionally far stricter than the
1510    // user tolerance, so ordinary noisy meshes cannot bypass the normal gate.
1511    let numerical_position =
1512        numerical::EXACT_VERTEX_ROUNDOFF_MULTIPLIER * f64::EPSILON * scale.max(1.0);
1513    let exact_vertices_with_coherent_sense = vertex_samples_only
1514        && model.metrics.max_error <= numerical_position
1515        && model.metrics.rms_normal_error < std::f64::consts::FRAC_PI_2;
1516    model.metrics.max_error <= distance
1517        // Pole/seam slivers can have poorly conditioned chord normals even
1518        // when their vertices lie on the exact CAD carrier. Preserve the true
1519        // maximum in diagnostics, but use area-weighted RMS for acceptance.
1520        && (model.metrics.rms_normal_error <= options.normal_tolerance
1521            || exact_vertices_with_coherent_sense)
1522        && model.metrics.support_triangles >= options.minimum_support
1523        && model.metrics.supported_area >= options.minimum_support_area
1524}
1525fn to_region(fit: SurfaceFitResult, ids: Vec<usize>) -> SurfaceRegion {
1526    SurfaceRegion {
1527        surface: fit.surface,
1528        orientation: fit.orientation,
1529        triangle_indices: ids,
1530        metrics: fit.metrics,
1531        confidence: fit.confidence,
1532        diagnostics: fit.diagnostics,
1533    }
1534}
1535
1536fn merge_disconnected_regions(
1537    mesh: &AnalyzedMesh,
1538    options: &RecognitionOptions,
1539    regions: &mut Vec<SurfaceRegion>,
1540) {
1541    let mut left = 0;
1542    while left < regions.len() {
1543        let mut right = left + 1;
1544        while right < regions.len() {
1545            if regions[left].surface.surface_type() != regions[right].surface.surface_type()
1546                || regions[left].orientation != regions[right].orientation
1547            {
1548                right += 1;
1549                continue;
1550            }
1551            let mut ids = regions[left].triangle_indices.clone();
1552            ids.extend_from_slice(&regions[right].triangle_indices);
1553            ids.sort_unstable();
1554            let hint = SurfaceHint::InitialGuess {
1555                surface: regions[left].surface,
1556                trust: crate::MetadataTrust::InitialGuess,
1557            };
1558            let Ok(mut fit) = reconstruct_analyzed(mesh, &ids, &hint, options) else {
1559                right += 1;
1560                continue;
1561            };
1562            if fit.orientation != regions[left].orientation {
1563                right += 1;
1564                continue;
1565            }
1566            fit.diagnostics
1567                .reason
1568                .push_str("; disconnected supports were jointly refitted and merged by request");
1569            regions[left] = to_region(fit, ids);
1570            regions.remove(right);
1571            // The enlarged region may now validate another disconnected patch.
1572            right = left + 1;
1573        }
1574        left += 1;
1575    }
1576}
1577
1578/// Worker threads the options ask for: the cores the process may run on
1579/// when `threads` is 0, else `threads`; one on `wasm32`, which has no
1580/// threads to spawn.
1581fn worker_threads(options: &RecognitionOptions) -> usize {
1582    #[cfg(target_arch = "wasm32")]
1583    {
1584        let _ = options;
1585        1
1586    }
1587    #[cfg(not(target_arch = "wasm32"))]
1588    {
1589        match options.threads {
1590            0 => std::thread::available_parallelism().map_or(1, |cores| cores.get()),
1591            threads => threads,
1592        }
1593    }
1594}
1595
1596/// `f(0)..f(count)` in index order. With more than one worker on a native
1597/// target the indices are handed out dynamically to `workers` scoped
1598/// threads; otherwise they run in order on the caller's thread. A panic in
1599/// a worker is resumed on the caller's thread.
1600fn parallel_map<T: Send>(workers: usize, count: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {
1601    parallel_map_on_workers(workers, count, |_, index| f(index))
1602}
1603
1604/// [`parallel_map`], also passing the worker evaluating each index (below
1605/// `workers`, and 0 on the caller's thread), so each worker can own scratch.
1606fn parallel_map_on_workers<T: Send>(
1607    workers: usize,
1608    count: usize,
1609    f: impl Fn(usize, usize) -> T + Sync,
1610) -> Vec<T> {
1611    #[cfg(target_arch = "wasm32")]
1612    let _ = workers;
1613    #[cfg(not(target_arch = "wasm32"))]
1614    {
1615        let workers = workers.min(count);
1616        if workers > 1 {
1617            let next = std::sync::atomic::AtomicUsize::new(0);
1618            let collected: Vec<Vec<(usize, T)>> = std::thread::scope(|scope| {
1619                let handles: Vec<_> = (0..workers)
1620                    .map(|worker| {
1621                        let (next, f) = (&next, &f);
1622                        scope.spawn(move || {
1623                            let mut mine = Vec::new();
1624                            loop {
1625                                let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1626                                if index >= count {
1627                                    break;
1628                                }
1629                                mine.push((index, f(worker, index)));
1630                            }
1631                            mine
1632                        })
1633                    })
1634                    .collect();
1635                handles
1636                    .into_iter()
1637                    .map(|handle| handle.join().unwrap_or_else(|payload| std::panic::resume_unwind(payload)))
1638                    .collect()
1639            });
1640            let mut slots: Vec<Option<T>> = (0..count).map(|_| None).collect();
1641            for (index, value) in collected.into_iter().flatten() {
1642                slots[index] = Some(value);
1643            }
1644            return slots.into_iter().map(|slot| slot.expect("every index was evaluated once")).collect();
1645        }
1646    }
1647    (0..count).map(|index| f(0, index)).collect()
1648}
1649
1650/// Generic extraction over the connected components. When there are at least
1651/// as many components that can need extraction as workers, the workers take
1652/// the components, largest first, each on a local budget without a limit, and
1653/// the results are merged in component order, which is what the one-at-a-time
1654/// loop produces (also for the merge of disconnected regions that follows).
1655/// Under an attempt limit the one-at-a-time loop charges the components in
1656/// order and stops at the first draw the limit refuses, so the merge replays
1657/// that accounting: a component whose draws fit in what is left is taken as
1658/// computed, the first one that does not is run again on the real budget (it
1659/// is cut inside, and marks the budget exhausted), and the components after
1660/// it contribute nothing, as in the one-at-a-time loop. Otherwise the
1661/// components run in order and the workers go to the rounds' hypothesis
1662/// batches.
1663fn extract_components(
1664    mesh: &AnalyzedMesh,
1665    components: &[Vec<usize>],
1666    options: &RecognitionOptions,
1667    candidates: &[(Vec<usize>, AnalyticSurface)],
1668    out: &mut Vec<SurfaceRegion>,
1669    budget: &mut AttemptBudget,
1670) {
1671    let workers = worker_threads(options);
1672    let eligible = components
1673        .iter()
1674        .filter(|component| component.len() >= options.minimum_support)
1675        .count();
1676    if workers > 1 && eligible >= workers && !budget.work.exhausted {
1677        let mut largest_first: Vec<usize> = (0..components.len()).collect();
1678        largest_first.sort_by_key(|&index| std::cmp::Reverse(components[index].len()));
1679        let kinds = &budget.kinds;
1680        let profiling = budget.profile.is_some();
1681        let mut extracted = parallel_map(workers, components.len(), |slot| {
1682            let index = largest_first[slot];
1683            let mut local = AttemptBudget {
1684                limit: None,
1685                kinds: kinds.clone(),
1686                work: RecognitionWork::default(),
1687                profile: profiling.then(ExtractionProfile::default),
1688            };
1689            let mut regions = Vec::new();
1690            extract_component(mesh, &components[index], options, candidates, &mut regions, &mut local, 1);
1691            (index, regions, local.work, local.profile)
1692        });
1693        extracted.sort_by_key(|(index, ..)| *index);
1694        for (index, regions, work, profile) in extracted {
1695            debug_assert!(!work.exhausted && work.stops_at_budget == 0, "an unlimited budget refuses nothing");
1696            if budget.work.exhausted {
1697                break;
1698            }
1699            let fits = budget
1700                .limit
1701                .is_none_or(|limit| budget.work.attempts.saturating_add(work.attempts) <= limit);
1702            if fits {
1703                out.extend(regions);
1704                budget.work.absorb(&work);
1705                if let (Some(total), Some(profile)) = (&mut budget.profile, &profile) {
1706                    total.absorb(profile);
1707                }
1708            } else {
1709                // The one-at-a-time loop is cut inside this component: run it
1710                // on the real budget, which refuses the draw the limit
1711                // refuses there and marks the budget exhausted.
1712                extract_component(mesh, &components[index], options, candidates, out, budget, 1);
1713                debug_assert!(budget.work.exhausted);
1714            }
1715        }
1716        return;
1717    }
1718    for component in components {
1719        extract_component(mesh, component, options, candidates, out, budget, workers);
1720    }
1721}
1722
1723fn extract_component(
1724    mesh: &AnalyzedMesh,
1725    component: &[usize],
1726    options: &RecognitionOptions,
1727    candidates: &[(Vec<usize>, AnalyticSurface)],
1728    out: &mut Vec<SurfaceRegion>,
1729    budget: &mut AttemptBudget,
1730    workers: usize,
1731) {
1732    if component.len() < options.minimum_support || budget.work.exhausted {
1733        return;
1734    }
1735    let whole_started = budget.profile.is_some().then(Instant::now);
1736    fit_profile_start(budget.profile.is_some());
1737    let whole = reconstruct_analyzed(mesh, component, &SurfaceHint::Unknown, options);
1738    ExtractionProfile::take_fitter(&mut budget.profile, |p| &mut p.whole_fitter);
1739    if let Ok(fit) = whole {
1740        ExtractionProfile::charge(&mut budget.profile, whole_started, |p| &mut p.whole_fit_seconds);
1741        out.push(to_region(fit, component.to_vec()));
1742        return;
1743    }
1744    if let Some(fit) = candidate_fit(mesh, component, options, candidates) {
1745        ExtractionProfile::charge(&mut budget.profile, whole_started, |p| &mut p.whole_fit_seconds);
1746        budget.work.seeded_components += 1;
1747        out.push(to_region(fit, component.to_vec()));
1748        return;
1749    }
1750    ExtractionProfile::charge(&mut budget.profile, whole_started, |p| &mut p.whole_fit_seconds);
1751    if let HypothesisPolicy::Adaptive(policy) = &options.hypothesis_policy {
1752        return extract_component_adaptive(mesh, component, options, out, budget, policy);
1753    }
1754    // CAD-aware hypothesis generation: fit small connected neighborhoods and
1755    // grow their geometric support through adjacency. This is deterministic
1756    // with a supplied seed and lets tangent analytic regions separate.
1757    //
1758    // A round's hypotheses are fixed by its seed permutations, and each one
1759    // reads only the round's remaining triangles, so they are evaluated in
1760    // batches (of one on a single worker) and applied in draw order: the
1761    // regions, their diagnostics and the work are those of the one-at-a-time
1762    // loop, including where an attempt budget cuts the round.
1763    let mut remaining = Remaining::new(mesh, component);
1764    let mut rng = SplitMix(options.deterministic_seed.unwrap_or(0x52414e534143));
1765    let batch_size = if workers > 1 { workers * budget.kinds.len() } else { 1 };
1766    let scratch: Vec<std::sync::Mutex<Scratch>> =
1767        (0..workers.max(1)).map(|_| std::sync::Mutex::new(Scratch::new(mesh))).collect();
1768    let profiling = budget.profile.is_some();
1769    while remaining.len() >= options.minimum_support {
1770        let seed_order_started = profiling.then(Instant::now);
1771        let ids: Vec<_> = remaining.iter().copied().collect();
1772        // One independently shuffled, without-replacement seed schedule per
1773        // primitive. At the full cap every remaining triangle is tried once
1774        // for every carrier; random-with-replacement sampling could waste
1775        // roughly a third of that budget on duplicate seeds.
1776        let kinds = budget.kinds.clone();
1777        let seed_orders: Vec<_> = kinds
1778            .iter()
1779            .map(|_| shuffled_seed_order(&ids, &mut rng))
1780            .collect();
1781        ExtractionProfile::charge(&mut budget.profile, seed_order_started, |p| &mut p.seed_order_seconds);
1782        let mut best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
1783        let attempt_cap = options.max_hypotheses.min(ids.len() * kinds.len());
1784        let mut attempts_required = attempt_cap;
1785        let mut attempt = 0;
1786        let mut region_growth_seconds = options.collect_phase_timings.then_some(0.0);
1787        while attempt < attempts_required {
1788            let want = batch_size.min(attempts_required - attempt);
1789            let admitted = budget.admit(want);
1790            let drawn: Vec<(usize, SurfaceType)> = (attempt..attempt + admitted)
1791                .map(|index| {
1792                    let slot = index % kinds.len();
1793                    (seed_orders[slot][index / kinds.len()], kinds[slot])
1794                })
1795                .collect();
1796            for &(_, kind) in &drawn {
1797                budget.work.hypotheses_by_kind[kind_index(kind)] += 1;
1798            }
1799            let incumbent = best.as_ref().map_or(0, |(count, ..)| *count);
1800            let evaluated = parallel_map_on_workers(workers, admitted, |worker, offset| {
1801                let (seed, kind) = drawn[offset];
1802                // Each worker locks only its own scratch, so this never waits.
1803                let mut scratch = scratch[worker].lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1804                classical_hypothesis(mesh, &remaining, &mut scratch, seed, kind, options, incumbent, profiling)
1805            });
1806            let mut applied = 0;
1807            for (offset, (probe_best, growth_seconds, profile)) in evaluated.into_iter().enumerate() {
1808                let attempt_index = attempt + offset;
1809                if attempt_index >= attempts_required {
1810                    break;
1811                }
1812                applied += 1;
1813                if let (Some(total), Some(seconds)) = (&mut region_growth_seconds, growth_seconds) {
1814                    *total += seconds;
1815                }
1816                if let (Some(total), Some(profile)) = (&mut budget.profile, &profile) {
1817                    total.absorb(profile);
1818                }
1819                let Some((_, rank, mut fit, support)) = probe_best else {
1820                    continue;
1821                };
1822                fit.diagnostics.hypotheses_generated = attempt_index + 1;
1823                let area = fit.metrics.supported_area;
1824                let replace = best.as_ref().is_none_or(|(count, old_rank, old, _)| {
1825                    support.len() > *count
1826                        || (support.len() == *count
1827                            && (area > old.metrics.supported_area
1828                                || (area == old.metrics.supported_area
1829                                    && compare_model_rank(
1830                                        rank,
1831                                        fit.surface.surface_type(),
1832                                        *old_rank,
1833                                        old.surface.surface_type(),
1834                                    ) == Ordering::Less)))
1835                });
1836                if replace {
1837                    let support_fraction = support.len() as f64 / ids.len() as f64;
1838                    attempts_required = attempts_required.min(required_seed_hypotheses(
1839                        options.confidence,
1840                        support_fraction,
1841                        kinds.len(),
1842                        attempt_cap,
1843                    ));
1844                    attempts_required = attempts_required.max(attempt_index + 1);
1845                    best = Some((support.len(), rank, fit, support));
1846                }
1847            }
1848            // Hypotheses past the bound a winner in this batch shrank were
1849            // never drawn by the one-at-a-time loop.
1850            for &(_, kind) in &drawn[applied..] {
1851                budget.work.hypotheses_by_kind[kind_index(kind)] -= 1;
1852            }
1853            budget.refund(admitted - applied);
1854            attempt += applied;
1855            if applied < admitted {
1856                break;
1857            }
1858            if admitted < want {
1859                // The round's next hypothesis is one the limit refuses.
1860                budget.work.exhausted = true;
1861                budget.work.stops_at_budget += 1;
1862                return;
1863            }
1864        }
1865        // The round ran to the classical bound, or to the cap when the bound
1866        // asked for more than the cap allowed.
1867        if attempts_required < attempt_cap {
1868            budget.work.stops_at_risk_bound += 1;
1869        } else {
1870            budget.work.stops_at_hypothesis_cap += 1;
1871        }
1872        if let Some(profile) = &mut budget.profile {
1873            profile.rounds += 1;
1874            profile.seeds_consumed += attempt;
1875            profile.seed_slots += ids.len() * kinds.len();
1876            if best.is_none() {
1877                profile.abandon(mesh, &remaining, options);
1878            }
1879        }
1880        let Some((_, _, mut fit, support)) = best else {
1881            break;
1882        };
1883        fit.diagnostics.phase_timings.region_growth_seconds = region_growth_seconds;
1884        for id in &support {
1885            remaining.remove(id);
1886        }
1887        budget.work.rounds += 1;
1888        out.push(to_region(fit, support));
1889    }
1890}
1891
1892/// One classical hypothesis: the probe chain around `seed` for `kind` over
1893/// `remaining`, returning the best candidate any probe size produced
1894/// (support count, rank, refit, support), the seconds spent growing support
1895/// when phase timings are collected, and its extraction profile when
1896/// `profiling` (refits measured against `incumbent`, the round's best count
1897/// when it was drawn). It reads nothing a round writes, so a round's
1898/// hypotheses can run in any order or at once.
1899#[allow(clippy::type_complexity, clippy::too_many_arguments)]
1900fn classical_hypothesis(
1901    mesh: &AnalyzedMesh,
1902    remaining: &Remaining,
1903    scratch: &mut Scratch,
1904    seed: usize,
1905    kind: SurfaceType,
1906    options: &RecognitionOptions,
1907    incumbent: usize,
1908    profiling: bool,
1909) -> (
1910    Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)>,
1911    Option<f64>,
1912    Option<ExtractionProfile>,
1913) {
1914    let mut region_growth_seconds = options.collect_phase_timings.then_some(0.0);
1915    let mut profile = profiling.then(ExtractionProfile::default);
1916    // Generate each primitive from the smallest diverse triangle set that
1917    // supplies its fitter's required independent observations in every
1918    // public sampling mode. Final support is still grown and validated
1919    // against the complete connected region below. Keeping the fitted sample
1920    // primitive-specific avoids fitting every candidate to the full
1921    // diversity probe while preserving aggressive rank/degeneracy rejection
1922    // in the fitter.
1923    let sample_size = hypothesis_sample_triangles(kind);
1924    // The probe supplies spatial/normal diversity without increasing the
1925    // number of triangles actually passed to a primitive fitter.
1926    let mut probe_limit = options
1927        .hypothesis_probe_triangles
1928        .max(sample_size)
1929        .min(remaining.len());
1930    let mut probe_best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
1931    let mut search = Neighborhood::start(scratch, seed);
1932    loop {
1933        let started = profiling.then(Instant::now);
1934        let probe = search.grow(mesh, remaining, scratch, probe_limit, probe_crease(options));
1935        ExtractionProfile::charge(&mut profile, started, |p| &mut p.neighborhood_seconds);
1936        if probe.len() < sample_size {
1937            break;
1938        }
1939        let started = profiling.then(Instant::now);
1940        let sample = diverse_hypothesis_sample(mesh, seed, &probe, sample_size);
1941        ExtractionProfile::charge(&mut profile, started, |p| &mut p.sample_seconds);
1942        let mut grew_beyond_probe = false;
1943        let mut reconstructed_probe = false;
1944        let started = profiling.then(Instant::now);
1945        fit_profile_start(profiling);
1946        let fitted = fit_surface_with_path(
1947            mesh,
1948            &sample,
1949            kind,
1950            None,
1951            ConstraintMask::default(),
1952            options,
1953            FitPath::GenericRecognition,
1954        );
1955        ExtractionProfile::take_fitter(&mut profile, |p| &mut p.sample_fitter);
1956        let fit_seconds = started.map_or(0.0, |started| started.elapsed().as_secs_f64());
1957        // What came of a torus sample fit (row 1): see `torus_sample_outcomes`.
1958        let mut torus_outcome = 0;
1959        if let Some(profile) = &mut profile {
1960            profile.fit_seconds[kind_index(kind)] += fit_seconds;
1961            profile.fits[kind_index(kind)] += 1;
1962        }
1963        if let Ok(candidate) = fitted {
1964            torus_outcome = 1;
1965            let growth_started = options.collect_phase_timings.then(Instant::now);
1966            let started = profiling.then(Instant::now);
1967            let mut tally = profiling.then(SupportTally::default);
1968            let support = support_component(
1969                mesh,
1970                remaining,
1971                scratch,
1972                seed,
1973                candidate.surface,
1974                options,
1975                tally.as_mut(),
1976            );
1977            ExtractionProfile::charge(&mut profile, started, |p| &mut p.support_seconds);
1978            if let (Some(profile), Some(tally)) = (&mut profile, tally) {
1979                profile.support_triangles_tested += tally.triangles;
1980                profile.distance_evaluations += tally.evaluations;
1981                profile.distinct_vertices_evaluated += tally.vertices.len();
1982            }
1983            if let (Some(total), Some(started)) = (&mut region_growth_seconds, growth_started) {
1984                *total += started.elapsed().as_secs_f64();
1985            }
1986            grew_beyond_probe = support.len() > probe.len();
1987            if support.len() >= options.minimum_support {
1988                let started = profiling.then(Instant::now);
1989                fit_profile_start(profiling);
1990                let refitted = reconstruct_analyzed(
1991                    mesh,
1992                    &support,
1993                    &SurfaceHint::InitialGuess {
1994                        surface: candidate.surface,
1995                        trust: crate::MetadataTrust::InitialGuess,
1996                    },
1997                    options,
1998                );
1999                ExtractionProfile::take_fitter(&mut profile, |p| &mut p.refit_fitter);
2000                torus_outcome = if refitted.is_ok() { 3 } else { 2 };
2001                if let Some(profile) = &mut profile {
2002                    let exhausted = probe.len() == remaining.len() || probe.len() < probe_limit;
2003                    profile.refit(started, support.len(), incumbent, !grew_beyond_probe || exhausted);
2004                }
2005                if let Ok(fit) = refitted {
2006                    reconstructed_probe = true;
2007                    let started = profiling.then(Instant::now);
2008                    let area = fit.metrics.supported_area;
2009                    let support_scale = selection_scale(mesh, &support);
2010                    let support_tolerance = options.distance_tolerance
2011                        + options.relative_tolerance * support_scale.max(1.0);
2012                    let rank = model_rank(
2013                        mesh,
2014                        Selection::Triangles(&support),
2015                        fit.surface.surface_type(),
2016                        &fit,
2017                        support_tolerance,
2018                        options.normal_tolerance,
2019                    );
2020                    let replace = probe_best.as_ref().is_none_or(|(count, old_rank, old, _)| {
2021                        support.len() > *count
2022                            || (support.len() == *count
2023                                && (area > old.metrics.supported_area
2024                                    || (area == old.metrics.supported_area
2025                                        && compare_model_rank(
2026                                            rank,
2027                                            fit.surface.surface_type(),
2028                                            *old_rank,
2029                                            old.surface.surface_type(),
2030                                        ) == Ordering::Less)))
2031                    });
2032                    ExtractionProfile::charge(&mut profile, started, |p| &mut p.rank_seconds);
2033                    if support.len() < incumbent {
2034                        ExtractionProfile::charge(&mut profile, started, |p| &mut p.rank_dominated_seconds);
2035                    }
2036                    if replace {
2037                        probe_best = Some((support.len(), rank, fit, support));
2038                    }
2039                }
2040            }
2041        }
2042        if let (Some(profile), SurfaceType::Torus) = (&mut profile, kind) {
2043            profile.torus_sample(torus_outcome, fit_seconds);
2044        }
2045        let exhausted = probe.len() == remaining.len() || probe.len() < probe_limit;
2046        if (grew_beyond_probe && reconstructed_probe) || exhausted {
2047            break;
2048        }
2049        // A candidate explaining no more triangles than its local probe is
2050        // under-observed (for example one planar strip of a finely faceted
2051        // cylinder). Expand only the diversity probe; every fitter call
2052        // remains primitive-minimal.
2053        probe_limit = probe_limit.saturating_mul(2).min(remaining.len());
2054    }
2055    (probe_best, region_growth_seconds, profile)
2056}
2057
2058/// Relative cost of one generic hypothesis per kind, in units of a plane
2059/// hypothesis, in [`TYPES`] order. The sample fit dominates a losing
2060/// hypothesis, and in a release build (2026-10-27, the jitter-1.0 d0.02
2061/// torus and the jitter-0.3 d0.02 crossing fixtures) it measured 0.01 ms for
2062/// a plane, 0.05 sphere, 0.13 cylinder, 0.27 cone and 9.2 torus. The bandit
2063/// divides a kind's reward by this instead of reading the clock, so a run
2064/// stays reproducible under `deterministic_seed`.
2065const HYPOTHESIS_COST_UNITS: [f64; 5] = [1.0, 5.0, 13.0, 27.0, 920.0];
2066
2067/// Uniform index in `0..n` by rejection, as [`shuffled_seed_order`] draws.
2068fn uniform_index(rng: &mut SplitMix, n: usize) -> usize {
2069    debug_assert!(n > 0);
2070    let n_u64 = n as u64;
2071    let zone = (u64::MAX / n_u64) * n_u64;
2072    loop {
2073        let value = rng.next();
2074        if value < zone {
2075            return (value % n_u64) as usize;
2076        }
2077    }
2078}
2079
2080/// Uniform `f64` in `[0, 1)` from the top 53 bits of one draw.
2081fn unit_interval(rng: &mut SplitMix) -> f64 {
2082    (rng.next() >> 11) as f64 / (1u64 << 53) as f64
2083}
2084
2085/// Standard normal by Box–Muller (one of the pair).
2086fn standard_normal(rng: &mut SplitMix) -> f64 {
2087    let u = loop {
2088        let u = unit_interval(rng);
2089        if u > 0.0 {
2090            break u;
2091        }
2092    };
2093    let v = unit_interval(rng);
2094    (-2.0 * u.ln()).sqrt() * (2.0 * std::f64::consts::PI * v).cos()
2095}
2096
2097/// Gamma(`shape`, 1) for `shape >= 1` by Marsaglia–Tsang.
2098fn gamma_sample(rng: &mut SplitMix, shape: f64) -> f64 {
2099    debug_assert!(shape >= 1.0);
2100    let d = shape - 1.0 / 3.0;
2101    let c = 1.0 / (9.0 * d).sqrt();
2102    loop {
2103        let x = standard_normal(rng);
2104        let v = 1.0 + c * x;
2105        if v <= 0.0 {
2106            continue;
2107        }
2108        let v = v * v * v;
2109        let u = unit_interval(rng);
2110        if u > 0.0 && u.ln() < 0.5 * x * x + d - d * v + d * v.ln() {
2111            return d * v;
2112        }
2113    }
2114}
2115
2116/// Beta(`successes + 1`, `failures + 1`): the posterior of a rate under a
2117/// uniform prior.
2118fn beta_sample(rng: &mut SplitMix, successes: usize, failures: usize) -> f64 {
2119    let x = gamma_sample(rng, successes as f64 + 1.0);
2120    let y = gamma_sample(rng, failures as f64 + 1.0);
2121    x / (x + y)
2122}
2123
2124/// The arm a bandit draws next: first any eligible arm below its floor share
2125/// of the `total` draws so far (the most deficient, lowest index on ties),
2126/// otherwise the eligible arm with the largest `score`. At least one arm must
2127/// be eligible.
2128fn choose_arm(draws: &[usize], scores: &[f64], eligible: &[bool], floor_share: f64, total: usize) -> usize {
2129    let arms = draws.len();
2130    debug_assert!(arms > 0 && scores.len() == arms && eligible.len() == arms);
2131    let minimum = (floor_share * (total + 1) as f64 / arms as f64).ceil() as usize;
2132    let deficient = (0..arms)
2133        .filter(|&i| eligible[i] && draws[i] < minimum)
2134        .min_by(|&a, &b| draws[a].cmp(&draws[b]).then(a.cmp(&b)));
2135    if let Some(arm) = deficient {
2136        return arm;
2137    }
2138    (0..arms)
2139        .filter(|&i| eligible[i])
2140        .fold(None, |best: Option<usize>, i| match best {
2141            Some(b) if scores[i] <= scores[b] => Some(b),
2142            _ => Some(i),
2143        })
2144        .expect("at least one eligible arm")
2145}
2146
2147/// What the adaptive policy has learned about one primitive kind on a
2148/// component, carried from round to round (halved at each round's start, so
2149/// the extracted regions stop weighing on what remains).
2150#[derive(Clone, Copy, Debug, Default)]
2151struct KindPosterior {
2152    /// Hypotheses whose support reached `minimum_support`.
2153    reached: f64,
2154    /// Hypotheses that did the work and did not.
2155    failed: f64,
2156    /// Sum of the reached candidates' support shares of the round's triangles.
2157    support_share: f64,
2158    /// Doubling chains past a hopeless probe that later reached
2159    /// `minimum_support`, and chains that never did.
2160    rescued: f64,
2161    /// See `rescued`.
2162    unrescued: f64,
2163}
2164
2165impl KindPosterior {
2166    fn halve(&mut self) {
2167        self.reached *= 0.5;
2168        self.failed *= 0.5;
2169        self.support_share *= 0.5;
2170        self.rescued *= 0.5;
2171        self.unrescued *= 0.5;
2172    }
2173
2174    /// Posterior mean of the chance that doubling past a hopeless probe is
2175    /// rescued, under a uniform prior.
2176    fn rescue_rate(&self) -> f64 {
2177        (self.rescued + 1.0) / (self.rescued + self.unrescued + 2.0)
2178    }
2179
2180    /// One Thompson draw of the support share a hypothesis of this kind
2181    /// gains: a sampled success rate times the mean support share of its
2182    /// successes (one pseudo-success of `prior_share` while none is seen).
2183    fn sample_value(&self, rng: &mut SplitMix, prior_share: f64) -> f64 {
2184        let success = beta_sample(rng, self.reached.round() as usize, self.failed.round() as usize);
2185        let mean_share = (self.support_share + prior_share) / (self.reached + 1.0);
2186        success * mean_share
2187    }
2188}
2189
2190/// Spatial temperatures of the adaptive policy's Boltzmann seed distribution,
2191/// as multiples of `AdaptiveSampling::seed_temperature`; each is a bandit arm
2192/// ([`TemperatureArm`]). The last, infinite, is uniform over the triangles the
2193/// distribution ranges over, so a controller that has stopped improving at
2194/// the cooler arms reheats by choosing it.
2195const TEMPERATURE_BANK: [f64; 7] = [0.05, 0.1, 0.25, 0.5, 1.0, 2.0, f64::INFINITY];
2196
2197/// Position of the infinite temperature in [`TEMPERATURE_BANK`]; the uniform
2198/// part of the seed mixture reports its outcomes to this arm.
2199const UNIFORM_ARM: usize = TEMPERATURE_BANK.len() - 1;
2200
2201/// What the adaptive policy has learned about one spatial temperature on a
2202/// component (halved at each round's start, like [`KindPosterior`]).
2203#[derive(Clone, Copy, Debug, Default)]
2204struct TemperatureArm {
2205    /// Draws whose seed this arm chose.
2206    tried: f64,
2207    /// Those that replaced the round's incumbent.
2208    improved: f64,
2209    /// Sum of those replacements' gains in share of the round's triangles.
2210    gain: f64,
2211}
2212
2213impl TemperatureArm {
2214    fn halve(&mut self) {
2215        self.tried *= 0.5;
2216        self.improved *= 0.5;
2217        self.gain *= 0.5;
2218    }
2219
2220    /// Mean gain of this arm's replacements, one pseudo-replacement of
2221    /// `prior_gain` while none is seen.
2222    fn mean_gain(&self, prior_gain: f64) -> f64 {
2223        (self.gain + prior_gain) / (self.improved + 1.0)
2224    }
2225
2226    /// One Thompson draw of the improvement a draw at this temperature makes
2227    /// to the incumbent: a sampled improvement rate (uniform prior) times the
2228    /// mean gain.
2229    fn sample_value(&self, rng: &mut SplitMix, prior_gain: f64) -> f64 {
2230        let improved = self.improved.round().max(0.0) as usize;
2231        let failed = (self.tried - self.improved).round().max(0.0) as usize;
2232        beta_sample(rng, improved, failed) * self.mean_gain(prior_gain)
2233    }
2234}
2235
2236/// The temperature arm with the largest Thompson draw (the coolest on a tie).
2237fn choose_temperature(bank: &[TemperatureArm], rng: &mut SplitMix, prior_gain: f64) -> usize {
2238    let mut best = 0;
2239    let mut best_value = f64::NEG_INFINITY;
2240    for (arm, state) in bank.iter().enumerate() {
2241        let value = state.sample_value(rng, prior_gain);
2242        if value > best_value {
2243            best = arm;
2244            best_value = value;
2245        }
2246    }
2247    best
2248}
2249
2250/// The share of the component's error budget `delta_total` a round that
2251/// extracted `extracted` of the component's `component_size` triangles may
2252/// spend: proportional to what it extracted, so that the disjoint extracted
2253/// regions of the certified rounds sum to at most `delta_total`.
2254fn round_error_share(delta_total: f64, extracted: usize, component_size: usize) -> f64 {
2255    delta_total * extracted as f64 / component_size as f64
2256}
2257
2258/// One seed from the Boltzmann part of the adaptive mixture: weight
2259/// `exp(-explored / temperature)` over the positions of `ids` that `kind` has
2260/// not seeded and that are outside the incumbent; `None` when no such
2261/// position remains.
2262fn boltzmann_seed(
2263    rng: &mut SplitMix,
2264    ids: &[usize],
2265    tried: &[bool],
2266    incumbent: &[bool],
2267    explored: &[f64],
2268    temperature: f64,
2269) -> Option<usize> {
2270    let weight = |position: usize| -> f64 {
2271        if tried[position] || incumbent[position] {
2272            0.0
2273        } else {
2274            (-explored[ids[position]] / temperature).exp()
2275        }
2276    };
2277    let total: f64 = (0..ids.len()).map(weight).sum();
2278    if !(total > 0.0) {
2279        return None;
2280    }
2281    let mut target = unit_interval(rng) * total;
2282    let mut last = None;
2283    for position in 0..ids.len() {
2284        let w = weight(position);
2285        if w <= 0.0 {
2286            continue;
2287        }
2288        last = Some(position);
2289        if target < w {
2290            return Some(position);
2291        }
2292        target -= w;
2293    }
2294    last
2295}
2296
2297/// Generic extraction under [`HypothesisPolicy::Adaptive`]. Same component
2298/// partition, fitters, support growth, refit and ranking as the classical
2299/// loop; what changes is how each hypothesis is drawn and when a round stops.
2300///
2301/// Per round over the remaining triangles `R`, `n = |R|`, `n0` the component's
2302/// triangle count, `w` the incumbent's share of `n` (0 before a candidate):
2303/// - the kind is drawn by Thompson sampling on [`KindPosterior`]: the sampled
2304///   support share a hypothesis of the kind gains, divided by its cost
2305///   ([`HYPOTHESIS_COST_UNITS`] plus the mean kind cost, the price of the
2306///   round slot a draw occupies whatever its kind), among the kinds some
2307///   remaining triangle has not seeded yet, every such kind keeping
2308///   `kind_floor` of the draws; the posterior carries across rounds, halved;
2309/// - the seed is uniform over `R` with probability `seed_exploration`,
2310///   otherwise Boltzmann over the unexplored triangles outside the incumbent
2311///   that this kind has not seeded, at a temperature drawn by Thompson
2312///   sampling over [`TEMPERATURE_BANK`] scaled by `seed_temperature`
2313///   ([`TemperatureArm`]); the uniform draws report to the infinite arm;
2314/// - the probe is the classical chain (128 triangles, doubled while the
2315///   candidate reaches `minimum_support` without outgrowing the probe), except
2316///   that at the first probe whose candidate did not reach `minimum_support`
2317///   the chain is kept, once, with probability `max(probe_floor, rescue
2318///   rate)` and otherwise dropped; a kept chain runs on as the classical one
2319///   does. The rescue rate is how often a kept chain of this kind went on to
2320///   reach `minimum_support`, so the chance a rescuable chain is kept equals
2321///   the rate however many doublings the rescue takes;
2322/// - after each draw the round stops for the first of these that holds, each
2323///   counted in [`RecognitionWork`]:
2324///   1. risk bound: every kind's miss bound `(1 - seed_exploration * w)^d_k`
2325///      (`d_k` its draws so far; 0 once every remaining triangle has seeded
2326///      it) is at most the round's share of the component's error budget,
2327///      `(1 - confidence) * |incumbent| / n0` ([`round_error_share`]). The
2328///      best support `B` of the round's triangles has some kind `k*` and
2329///      `|B| >= |incumbent|` from the first draw on, so every uniform draw of
2330///      kind `k*`, whenever it was made, hit a seed of `B` with probability at
2331///      least `w`; the probability that every draw of `k*` missed `B` is at
2332///      most that kind's bound (the classical rule credits its earlier draws
2333///      the same way), and requiring every kind's bound at or below the
2334///      round's share bounds the miss by that share whatever `k*` is. The
2335///      extracted regions are disjoint, so the certified rounds' shares sum
2336///      to at most `1 - confidence` over the component; rounds that stop
2337///      otherwise certify nothing and spend nothing. As in the classical
2338///      rule, this is a seed-visitation bound: a visited seed still has to
2339///      produce a usable hypothesis;
2340///   2. seed exhaustion: every remaining triangle has seeded every kind;
2341///   3. the cap `max_hypotheses` (or one draw per remaining triangle per
2342///      kind, when smaller), reached without any of the above.
2343///   An attempt budget cut ends the round and the component at once.
2344/// A draw that repeats a (seed, kind) pair already tried in the round counts
2345/// toward the bound and the cap and does no fitting.
2346fn extract_component_adaptive(
2347    mesh: &AnalyzedMesh,
2348    component: &[usize],
2349    options: &RecognitionOptions,
2350    out: &mut Vec<SurfaceRegion>,
2351    budget: &mut AttemptBudget,
2352    policy: &AdaptiveSampling,
2353) {
2354    let mut remaining = Remaining::new(mesh, component);
2355    let mut scratch = Scratch::new(mesh);
2356    let mut rng = SplitMix(options.deterministic_seed.unwrap_or(0x52414e534143));
2357    let kinds = budget.kinds.clone();
2358    let kind_count = kinds.len();
2359    let mean_cost =
2360        kinds.iter().map(|&kind| HYPOTHESIS_COST_UNITS[kind_index(kind)]).sum::<f64>() / kind_count as f64;
2361    let kind_cost: Vec<f64> =
2362        kinds.iter().map(|&kind| HYPOTHESIS_COST_UNITS[kind_index(kind)] + mean_cost).collect();
2363    let mut posterior = vec![KindPosterior::default(); kind_count];
2364    let mut bank = [TemperatureArm::default(); TEMPERATURE_BANK.len()];
2365    // Losing supports a triangle has sat in, over every round of this
2366    // component: the seed distribution's history.
2367    let mut explored = vec![0.0f64; mesh.triangles.len()];
2368    let delta_total = 1.0 - options.confidence;
2369    let component_size = component.len();
2370    let profiling = budget.profile.is_some();
2371    while remaining.len() >= options.minimum_support {
2372        let seed_order_started = profiling.then(Instant::now);
2373        let ids: Vec<usize> = remaining.iter().copied().collect();
2374        let n = ids.len();
2375        posterior.iter_mut().for_each(KindPosterior::halve);
2376        bank.iter_mut().for_each(TemperatureArm::halve);
2377        let mut tried: Vec<Vec<bool>> = vec![vec![false; n]; kind_count];
2378        let mut tried_count = vec![0usize; kind_count];
2379        let mut kind_draws = vec![0usize; kind_count];
2380        let mut incumbent = vec![false; n];
2381        let mut best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
2382        let attempt_cap = options.max_hypotheses.min(n * kind_count);
2383        let mut attempt = 0;
2384        let mut region_growth_seconds = options.collect_phase_timings.then_some(0.0);
2385        let mut stopped_early = false;
2386        ExtractionProfile::charge(&mut budget.profile, seed_order_started, |p| &mut p.seed_order_seconds);
2387        while attempt < attempt_cap {
2388            if !budget.take() {
2389                budget.work.stops_at_budget += 1;
2390                return;
2391            }
2392            let attempt_index = attempt;
2393            attempt += 1;
2394            let seed_choice_started = profiling.then(Instant::now);
2395            let incumbent_count = best.as_ref().map_or(0, |(count, ..)| *count);
2396            let w = best.as_ref().map_or(0.0, |(count, ..)| *count as f64 / n as f64);
2397            let prior_gain = if w > 0.0 { w } else { 1.0 / kind_count as f64 };
2398            let eligible: Vec<bool> = tried_count.iter().map(|&tried| tried < n).collect();
2399            debug_assert!(eligible.iter().any(|&open| open), "seed exhaustion leaves a kind to draw");
2400            let scores: Vec<f64> = posterior
2401                .iter()
2402                .zip(&kind_cost)
2403                .map(|(kind, cost)| kind.sample_value(&mut rng, prior_gain) / cost)
2404                .collect();
2405            let kind_slot = choose_arm(&kind_draws, &scores, &eligible, policy.kind_floor, attempt_index);
2406            let kind = kinds[kind_slot];
2407            budget.work.hypotheses_by_kind[kind_index(kind)] += 1;
2408            kind_draws[kind_slot] += 1;
2409            let (arm, position) = if unit_interval(&mut rng) < policy.seed_exploration {
2410                (UNIFORM_ARM, uniform_index(&mut rng, n))
2411            } else {
2412                let arm = choose_temperature(&bank, &mut rng, prior_gain);
2413                let position = boltzmann_seed(
2414                    &mut rng,
2415                    &ids,
2416                    &tried[kind_slot],
2417                    &incumbent,
2418                    &explored,
2419                    TEMPERATURE_BANK[arm] * policy.seed_temperature,
2420                )
2421                .unwrap_or_else(|| uniform_index(&mut rng, n));
2422                (arm, position)
2423            };
2424            ExtractionProfile::charge(&mut budget.profile, seed_choice_started, |p| &mut p.seed_choice_seconds);
2425            // The gain, in share of the round's triangles, when this draw
2426            // replaced the incumbent.
2427            let mut improvement = None;
2428            if !tried[kind_slot][position] {
2429                tried[kind_slot][position] = true;
2430                tried_count[kind_slot] += 1;
2431                let seed = ids[position];
2432                let sample_size = hypothesis_sample_triangles(kind);
2433                let mut probe_limit =
2434                    options.hypothesis_probe_triangles.max(sample_size).min(remaining.len());
2435                let mut probe_best: Option<(usize, ModelRank, SurfaceFitResult, Vec<usize>)> = None;
2436                let mut did_work = false;
2437                let mut reached_any = false;
2438                let mut doubled_past_hopeless = false;
2439                let mut search = Neighborhood::start(&mut scratch, seed);
2440                loop {
2441                    let started = profiling.then(Instant::now);
2442                    let probe = search.grow(mesh, &remaining, &mut scratch, probe_limit, probe_crease(options));
2443                    ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.neighborhood_seconds);
2444                    if probe.len() < sample_size {
2445                        break;
2446                    }
2447                    let started = profiling.then(Instant::now);
2448                    let sample = diverse_hypothesis_sample(mesh, seed, &probe, sample_size);
2449                    ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.sample_seconds);
2450                    let mut grew_beyond_probe = false;
2451                    let mut reconstructed_probe = false;
2452                    let mut reached = false;
2453                    did_work = true;
2454                    let started = profiling.then(Instant::now);
2455                    fit_profile_start(profiling);
2456                    let fitted = fit_surface_with_path(
2457                        mesh,
2458                        &sample,
2459                        kind,
2460                        None,
2461                        ConstraintMask::default(),
2462                        options,
2463                        FitPath::GenericRecognition,
2464                    );
2465                    ExtractionProfile::take_fitter(&mut budget.profile, |p| &mut p.sample_fitter);
2466                    let fit_seconds = started.map_or(0.0, |started| started.elapsed().as_secs_f64());
2467                    // What came of a torus sample fit (row 1): see `torus_sample_outcomes`.
2468                    let mut torus_outcome = 0;
2469                    if let Some(profile) = &mut budget.profile {
2470                        profile.fit_seconds[kind_index(kind)] += fit_seconds;
2471                        profile.fits[kind_index(kind)] += 1;
2472                    }
2473                    if let Ok(candidate) = fitted {
2474                        torus_outcome = 1;
2475                        let growth_started = options.collect_phase_timings.then(Instant::now);
2476                        let started = profiling.then(Instant::now);
2477                        let mut tally = profiling.then(SupportTally::default);
2478                        let support = support_component(
2479                            mesh,
2480                            &remaining,
2481                            &mut scratch,
2482                            seed,
2483                            candidate.surface,
2484                            options,
2485                            tally.as_mut(),
2486                        );
2487                        ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.support_seconds);
2488                        if let (Some(profile), Some(tally)) = (&mut budget.profile, tally) {
2489                            profile.support_triangles_tested += tally.triangles;
2490                            profile.distance_evaluations += tally.evaluations;
2491                            profile.distinct_vertices_evaluated += tally.vertices.len();
2492                        }
2493                        if let (Some(total), Some(started)) =
2494                            (&mut region_growth_seconds, growth_started)
2495                        {
2496                            *total += started.elapsed().as_secs_f64();
2497                        }
2498                        grew_beyond_probe = support.len() > probe.len();
2499                        if support.len() >= options.minimum_support {
2500                            reached = true;
2501                            let started = profiling.then(Instant::now);
2502                            fit_profile_start(profiling);
2503                            let refitted = reconstruct_analyzed(
2504                                mesh,
2505                                &support,
2506                                &SurfaceHint::InitialGuess {
2507                                    surface: candidate.surface,
2508                                    trust: crate::MetadataTrust::InitialGuess,
2509                                },
2510                                options,
2511                            );
2512                            ExtractionProfile::take_fitter(&mut budget.profile, |p| &mut p.refit_fitter);
2513                            torus_outcome = if refitted.is_ok() { 3 } else { 2 };
2514                            if let Some(profile) = &mut budget.profile {
2515                                let exhausted =
2516                                    probe.len() == remaining.len() || probe.len() < probe_limit;
2517                                profile.refit(
2518                                    started,
2519                                    support.len(),
2520                                    incumbent_count,
2521                                    !grew_beyond_probe || exhausted,
2522                                );
2523                            }
2524                            if let Ok(fit) = refitted {
2525                                reconstructed_probe = true;
2526                                let started = profiling.then(Instant::now);
2527                                let area = fit.metrics.supported_area;
2528                                let support_scale = selection_scale(mesh, &support);
2529                                let support_tolerance = options.distance_tolerance
2530                                    + options.relative_tolerance * support_scale.max(1.0);
2531                                let rank = model_rank(
2532                                    mesh,
2533                                    Selection::Triangles(&support),
2534                                    fit.surface.surface_type(),
2535                                    &fit,
2536                                    support_tolerance,
2537                                    options.normal_tolerance,
2538                                );
2539                                let replace =
2540                                    probe_best.as_ref().is_none_or(|(count, old_rank, old, _)| {
2541                                        support.len() > *count
2542                                            || (support.len() == *count
2543                                                && (area > old.metrics.supported_area
2544                                                    || (area == old.metrics.supported_area
2545                                                        && compare_model_rank(
2546                                                            rank,
2547                                                            fit.surface.surface_type(),
2548                                                            *old_rank,
2549                                                            old.surface.surface_type(),
2550                                                        ) == Ordering::Less)))
2551                                    });
2552                                ExtractionProfile::charge(&mut budget.profile, started, |p| &mut p.rank_seconds);
2553                                if support.len() < incumbent_count {
2554                                    ExtractionProfile::charge(&mut budget.profile, started, |p| {
2555                                        &mut p.rank_dominated_seconds
2556                                    });
2557                                }
2558                                if replace {
2559                                    probe_best = Some((support.len(), rank, fit, support));
2560                                }
2561                            }
2562                        }
2563                    }
2564                    if let (Some(profile), SurfaceType::Torus) = (&mut budget.profile, kind) {
2565                        profile.torus_sample(torus_outcome, fit_seconds);
2566                    }
2567                    if reached {
2568                        if doubled_past_hopeless && !reached_any {
2569                            posterior[kind_slot].rescued += 1.0;
2570                        }
2571                        reached_any = true;
2572                    }
2573                    let exhausted = probe.len() == remaining.len() || probe.len() < probe_limit;
2574                    if (grew_beyond_probe && reconstructed_probe) || exhausted {
2575                        break;
2576                    }
2577                    if !reached_any && !doubled_past_hopeless {
2578                        // The chain's first hopeless probe: keep the chain
2579                        // as often as such chains of this kind have been
2580                        // rescued, never below the floor. One coin decides
2581                        // the whole chain, so a rescue two doublings away is
2582                        // as likely to be kept as one a single doubling away.
2583                        let continue_probability =
2584                            policy.probe_floor.max(posterior[kind_slot].rescue_rate());
2585                        if unit_interval(&mut rng) >= continue_probability {
2586                            break;
2587                        }
2588                        doubled_past_hopeless = true;
2589                    }
2590                    probe_limit = probe_limit.saturating_mul(2).min(remaining.len());
2591                }
2592                if doubled_past_hopeless && !reached_any {
2593                    posterior[kind_slot].unrescued += 1.0;
2594                }
2595                if did_work {
2596                    if reached_any {
2597                        posterior[kind_slot].reached += 1.0;
2598                    } else {
2599                        posterior[kind_slot].failed += 1.0;
2600                    }
2601                }
2602                if let Some((count, rank, mut fit, support)) = probe_best {
2603                    posterior[kind_slot].support_share += count as f64 / n as f64;
2604                    let area = fit.metrics.supported_area;
2605                    let replace = best.as_ref().is_none_or(|(best_count, old_rank, old, _)| {
2606                        count > *best_count
2607                            || (count == *best_count
2608                                && (area > old.metrics.supported_area
2609                                    || (area == old.metrics.supported_area
2610                                        && compare_model_rank(
2611                                            rank,
2612                                            fit.surface.surface_type(),
2613                                            *old_rank,
2614                                            old.surface.surface_type(),
2615                                        ) == Ordering::Less)))
2616                    });
2617                    if replace {
2618                        let previous = best.as_ref().map_or(0, |(count, ..)| *count);
2619                        improvement = Some(count.saturating_sub(previous) as f64 / n as f64);
2620                        if let Some((_, _, _, old_support)) = &best {
2621                            for &id in old_support {
2622                                explored[id] += 1.0;
2623                            }
2624                        }
2625                        incumbent.iter_mut().for_each(|flag| *flag = false);
2626                        for &id in &support {
2627                            if let Ok(at) = ids.binary_search(&id) {
2628                                incumbent[at] = true;
2629                            }
2630                        }
2631                        fit.diagnostics.hypotheses_generated = attempt_index + 1;
2632                        best = Some((count, rank, fit, support));
2633                    } else {
2634                        for &id in &support {
2635                            explored[id] += 1.0;
2636                        }
2637                    }
2638                }
2639            }
2640            bank[arm].tried += 1.0;
2641            if let Some(gain) = improvement {
2642                bank[arm].improved += 1.0;
2643                bank[arm].gain += gain;
2644            }
2645            if let Some((count, ..)) = &best {
2646                // Whichever part of the mixture fired, each uniform draw of
2647                // the best support's kind hit it with probability at least
2648                // seed_exploration * w, whenever it was made.
2649                let w = *count as f64 / n as f64;
2650                let round_delta = round_error_share(delta_total, *count, component_size);
2651                let certified = (0..kind_count).all(|slot| {
2652                    tried_count[slot] >= n
2653                        || (1.0 - policy.seed_exploration * w).powi(kind_draws[slot] as i32) <= round_delta
2654                });
2655                if certified {
2656                    budget.work.stops_at_risk_bound += 1;
2657                    stopped_early = true;
2658                    break;
2659                }
2660            }
2661            if tried_count.iter().all(|&count| count >= n) {
2662                budget.work.stops_at_seed_exhaustion += 1;
2663                stopped_early = true;
2664                break;
2665            }
2666        }
2667        if !stopped_early {
2668            budget.work.stops_at_hypothesis_cap += 1;
2669        }
2670        if let Some(profile) = &mut budget.profile {
2671            profile.rounds += 1;
2672            profile.seeds_consumed += attempt;
2673            profile.seed_slots += n * kind_count;
2674            if best.is_none() {
2675                profile.abandon(mesh, &remaining, options);
2676            }
2677        }
2678        let Some((_, _, mut fit, support)) = best else {
2679            break;
2680        };
2681        fit.diagnostics.phase_timings.region_growth_seconds = region_growth_seconds;
2682        for id in &support {
2683            remaining.remove(id);
2684        }
2685        budget.work.rounds += 1;
2686        out.push(to_region(fit, support));
2687    }
2688}
2689
2690/// The supplied candidate for exactly `component`'s non-degenerate
2691/// triangles, validated by the ordinary gates plus the roundoff allowance.
2692fn candidate_fit(
2693    mesh: &AnalyzedMesh,
2694    component: &[usize],
2695    options: &RecognitionOptions,
2696    candidates: &[(Vec<usize>, AnalyticSurface)],
2697) -> Option<SurfaceFitResult> {
2698    if candidates.is_empty() {
2699        return None;
2700    }
2701    let mut ids = component.to_vec();
2702    ids.sort_unstable();
2703    let surface = candidates.iter().find_map(|(candidate, surface)| {
2704        let mut usable = candidate
2705            .iter()
2706            .copied()
2707            .filter(|&id| id < mesh.triangles.len() && mesh.triangles[id].area > 0.0);
2708        usable.by_ref().eq(ids.iter().copied()).then_some(*surface)
2709    })?;
2710    let magnitude = ids
2711        .iter()
2712        .flat_map(|&tid| mesh.triangles[tid].vertices)
2713        .map(|vid| {
2714            let p = mesh.vertices[vid];
2715            p.x.abs().max(p.y.abs()).max(p.z.abs())
2716        })
2717        .fold(1.0_f64, f64::max);
2718    let mut seeded = options.clone();
2719    seeded.distance_tolerance += CANDIDATE_ROUNDOFF_EPSILONS * f64::EPSILON * magnitude;
2720    let scale = selection_scale(mesh, &ids);
2721    let mut fit = evaluate_surface(mesh, &ids, surface, &seeded, FitPath::ExactCandidateReused).ok()?;
2722    let vertex_samples_only = matches!(seeded.sampling, crate::SamplingMode::Vertices);
2723    if !accepted_impl(&fit, &seeded, scale, vertex_samples_only) {
2724        return None;
2725    }
2726    fit.diagnostics.reason = "a supplied component carrier validated whole after the component's own whole fit was refused".into();
2727    Some(fit)
2728}
2729
2730fn shuffled_seed_order(ids: &[usize], rng: &mut SplitMix) -> Vec<usize> {
2731    let mut order = ids.to_vec();
2732    for upper in (2..=order.len()).rev() {
2733        let upper_u64 = upper as u64;
2734        // Rejection avoids modulo bias, retaining the stated without-
2735        // replacement sampling probability for any practical mesh size.
2736        let zone = (u64::MAX / upper_u64) * upper_u64;
2737        let index = loop {
2738            let value = rng.next();
2739            if value < zone {
2740                break (value % upper_u64) as usize;
2741            }
2742        };
2743        order.swap(upper - 1, index);
2744    }
2745    order
2746}
2747
2748/// Near-minimal triangle counts for generic primitive hypotheses.
2749///
2750/// `TriangleCentroids` yields exactly one observation per triangle, so these
2751/// counts match the primitive fitter's mathematical observation minima.
2752/// Vertex-containing sampling modes provide additional point/normal evidence
2753/// from the same compact connected patch.  Degenerate configurations are not
2754/// padded with arbitrary extra triangles: the fitter rejects them and RANSAC
2755/// tries another deterministic seed.
2756const fn hypothesis_sample_triangles(kind: SurfaceType) -> usize {
2757    match kind {
2758        SurfaceType::Plane => 3,
2759        SurfaceType::Sphere => 4,
2760        // Three centroid/normal observations are algebraically minimal, but
2761        // six are the near-minimal stable set on finely faceted CAD cylinders:
2762        // three can all lie in one numerically under-observed angular strip.
2763        SurfaceType::Cylinder => 6,
2764        SurfaceType::Cone => 4,
2765        SurfaceType::Torus => 6,
2766    }
2767}
2768
2769/// Select a deterministic, normal-diverse near-minimal subset from a compact
2770/// connected probe.  Merely taking adjacent triangles would let one planar
2771/// facet strip of a tessellated cylinder masquerade as a supported plane.
2772/// Normal diversity is therefore the primary farthest-point criterion;
2773/// centroid separation breaks ties and spans genuinely planar patches.
2774fn diverse_hypothesis_sample(
2775    mesh: &AnalyzedMesh,
2776    seed: usize,
2777    probe: &[usize],
2778    count: usize,
2779) -> Vec<usize> {
2780    debug_assert!(probe.contains(&seed));
2781    debug_assert!(count > 0 && probe.len() >= count);
2782    let mut selected = Vec::with_capacity(count);
2783    selected.push(seed);
2784    while selected.len() < count {
2785        let mut best: Option<(f64, f64, usize)> = None;
2786        for &candidate in probe {
2787            if selected.contains(&candidate) {
2788                continue;
2789            }
2790            let triangle = &mesh.triangles[candidate];
2791            let (normal_gap, spatial_gap) = selected.iter().fold(
2792                (f64::INFINITY, f64::INFINITY),
2793                |(normal_gap, spatial_gap), &chosen| {
2794                    let other = &mesh.triangles[chosen];
2795                    (
2796                        normal_gap
2797                            .min(1.0 - triangle.normal.dot(other.normal).abs().clamp(0.0, 1.0)),
2798                        spatial_gap.min((triangle.centroid - other.centroid).length_squared()),
2799                    )
2800                },
2801            );
2802            let key = (normal_gap, spatial_gap, std::cmp::Reverse(candidate));
2803            if best
2804                .as_ref()
2805                .is_none_or(|&(best_normal, best_spatial, best_id)| {
2806                    (normal_gap, spatial_gap, std::cmp::Reverse(candidate))
2807                        > (best_normal, best_spatial, std::cmp::Reverse(best_id))
2808                })
2809            {
2810                best = Some((key.0, key.1, candidate));
2811            }
2812        }
2813        selected.push(best.expect("probe has enough distinct triangles").2);
2814    }
2815    selected.sort_unstable();
2816    selected
2817}
2818
2819/// Conservative RANSAC stopping bound for round-robin primitive hypotheses.
2820/// Each primitive visits a separate without-replacement seed permutation.
2821/// For a region occupying fraction `w`, its exact hypergeometric miss
2822/// probability is no greater than the with-replacement bound `(1-w)^rounds`
2823/// used here. This controls the chance of visiting that support; candidate
2824/// rank and degeneracy checks still decide whether a visited seed is usable.
2825fn required_seed_hypotheses(
2826    confidence: f64,
2827    support_fraction: f64,
2828    kinds: usize,
2829    cap: usize,
2830) -> usize {
2831    let minimum = kinds.min(cap).max(1);
2832    if confidence <= 0.0 || support_fraction >= 1.0 {
2833        return minimum;
2834    }
2835    if support_fraction <= 0.0 || cap <= minimum {
2836        return cap.max(1);
2837    }
2838    let rounds = ((1.0 - confidence).ln() / (1.0 - support_fraction).ln())
2839        .ceil()
2840        .max(1.0) as usize;
2841    rounds.saturating_mul(kinds).clamp(minimum, cap)
2842}
2843
2844/// A component's triangles not yet extracted: ordered, for the rounds' seed
2845/// tables, and flat over the mesh's triangles, for the membership tests of
2846/// the probes and of support growth.
2847struct Remaining {
2848    ordered: BTreeSet<usize>,
2849    member: Vec<bool>,
2850}
2851
2852impl Remaining {
2853    fn new(mesh: &AnalyzedMesh, ids: &[usize]) -> Self {
2854        let mut member = vec![false; mesh.triangles.len()];
2855        for &id in ids {
2856            member[id] = true;
2857        }
2858        Self {
2859            ordered: ids.iter().copied().collect(),
2860            member,
2861        }
2862    }
2863
2864    fn len(&self) -> usize {
2865        self.ordered.len()
2866    }
2867
2868    fn iter(&self) -> std::collections::btree_set::Iter<'_, usize> {
2869        self.ordered.iter()
2870    }
2871
2872    fn contains(&self, id: usize) -> bool {
2873        self.member[id]
2874    }
2875
2876    fn remove(&mut self, id: &usize) {
2877        self.ordered.remove(id);
2878        self.member[*id] = false;
2879    }
2880}
2881
2882/// Per-worker scratch for the probes and support growth: epoch stamps over
2883/// the mesh's triangles, so a hypothesis neither allocates nor clears a set.
2884struct Scratch {
2885    probe: Vec<u32>,
2886    probe_epoch: u32,
2887    support: Vec<u32>,
2888    support_epoch: u32,
2889}
2890
2891impl Scratch {
2892    fn new(mesh: &AnalyzedMesh) -> Self {
2893        Self {
2894            probe: vec![0; mesh.triangles.len()],
2895            probe_epoch: 0,
2896            support: vec![0; mesh.triangles.len()],
2897            support_epoch: 0,
2898        }
2899    }
2900
2901    /// A stamp no probe triangle carries yet.
2902    fn probe_stamp(&mut self) -> u32 {
2903        if self.probe_epoch == u32::MAX {
2904            self.probe.fill(0);
2905            self.probe_epoch = 0;
2906        }
2907        self.probe_epoch += 1;
2908        self.probe_epoch
2909    }
2910
2911    /// Two stamps no support triangle carries yet: rejected, then accepted.
2912    fn support_stamps(&mut self) -> (u32, u32) {
2913        if self.support_epoch >= u32::MAX - 1 {
2914            self.support.fill(0);
2915            self.support_epoch = 0;
2916        }
2917        self.support_epoch += 2;
2918        (self.support_epoch - 1, self.support_epoch)
2919    }
2920}
2921
2922/// The breadth-first probe around a seed over the remaining triangles,
2923/// stopping once it holds `limit` triangles. A probe chain only raises the
2924/// limit, so the search resumes where it stopped instead of starting again:
2925/// a search to the larger limit passes through the stopped state (it pops the
2926/// same triangles in the same order until then), so the probe is the one a
2927/// fresh search returns.
2928struct Neighborhood {
2929    stamp: u32,
2930    visited: Vec<usize>,
2931    queue: VecDeque<usize>,
2932}
2933
2934impl Neighborhood {
2935    fn start(scratch: &mut Scratch, seed: usize) -> Self {
2936        let stamp = scratch.probe_stamp();
2937        scratch.probe[seed] = stamp;
2938        Self {
2939            stamp,
2940            visited: vec![seed],
2941            queue: VecDeque::from([seed]),
2942        }
2943    }
2944
2945    /// The probe at `limit` (no smaller than the last one asked for),
2946    /// sorted; with `crease` (a cosine), across no edge whose triangle
2947    /// normals are further apart ([`RecognitionOptions::probe_crease_gate`]).
2948    fn grow(
2949        &mut self,
2950        mesh: &AnalyzedMesh,
2951        allowed: &Remaining,
2952        scratch: &mut Scratch,
2953        limit: usize,
2954        crease: Option<f64>,
2955    ) -> Vec<usize> {
2956        while let Some(id) = self.queue.pop_front() {
2957            if self.visited.len() >= limit {
2958                // A fresh search to a larger limit expands this triangle next.
2959                self.queue.push_front(id);
2960                break;
2961            }
2962            for &n in mesh.triangles[id].neighbors.iter().flatten() {
2963                if crease.is_some_and(|cos| mesh.triangles[id].normal.dot(mesh.triangles[n].normal) < cos) {
2964                    continue;
2965                }
2966                if allowed.contains(n) && scratch.probe[n] != self.stamp {
2967                    scratch.probe[n] = self.stamp;
2968                    self.visited.push(n);
2969                    self.queue.push_back(n);
2970                }
2971            }
2972        }
2973        let mut probe = self.visited.clone();
2974        probe.sort_unstable();
2975        probe
2976    }
2977}
2978
2979/// [`RecognitionOptions::probe_crease_gate`]: the cosine a probe's edge
2980/// normals must reach.
2981fn probe_crease(options: &RecognitionOptions) -> Option<f64> {
2982    options.probe_crease_gate.then(|| options.normal_tolerance.cos())
2983}
2984
2985fn triangle_support(
2986    mesh: &AnalyzedMesh,
2987    id: usize,
2988    surface: AnalyticSurface,
2989    options: &RecognitionOptions,
2990    mut tally: Option<&mut SupportTally>,
2991) -> bool {
2992    let t = &mesh.triangles[id];
2993    let tolerance =
2994        options.distance_tolerance + options.relative_tolerance * mesh.diagonal.max(1.0);
2995    if let Some(tally) = tally.as_deref_mut() {
2996        tally.triangles += 1;
2997    }
2998    if t.vertices.iter().any(|&v| {
2999        if let Some(tally) = tally.as_deref_mut() {
3000            tally.evaluations += 1;
3001            tally.vertices.insert(v);
3002        }
3003        surface.signed_distance(mesh.vertices[v]).abs() > tolerance
3004    }) {
3005        return false;
3006    }
3007    let Some(normal) = surface.normal_at(t.centroid) else {
3008        return false;
3009    };
3010    t.normal.dot(normal).abs().clamp(-1.0, 1.0).acos() <= options.normal_tolerance
3011}
3012/// The connected component of `candidates` that `surface` supports and that
3013/// contains `seed`, grown through adjacency. Each candidate's support test
3014/// runs when the growth first reaches it, so the scan costs the component
3015/// and its boundary rather than every remaining triangle; the set is the
3016/// one a scan of every candidate followed by the same growth would return.
3017/// `tally`, when given, counts the distance work.
3018#[allow(clippy::too_many_arguments)]
3019fn support_component(
3020    mesh: &AnalyzedMesh,
3021    candidates: &Remaining,
3022    scratch: &mut Scratch,
3023    seed: usize,
3024    surface: AnalyticSurface,
3025    options: &RecognitionOptions,
3026    mut tally: Option<&mut SupportTally>,
3027) -> Vec<usize> {
3028    if !candidates.contains(seed)
3029        || !triangle_support(mesh, seed, surface, options, tally.as_deref_mut())
3030    {
3031        return Vec::new();
3032    }
3033    let (rejected, accepted) = scratch.support_stamps();
3034    let stamps = &mut scratch.support;
3035    stamps[seed] = accepted;
3036    let mut seen = vec![seed];
3037    let mut queue = VecDeque::from([seed]);
3038    while let Some(id) = queue.pop_front() {
3039        for &n in mesh.triangles[id].neighbors.iter().flatten() {
3040            if !candidates.contains(n) || stamps[n] == accepted || stamps[n] == rejected {
3041                continue;
3042            }
3043            if triangle_support(mesh, n, surface, options, tally.as_deref_mut()) {
3044                stamps[n] = accepted;
3045                seen.push(n);
3046                queue.push_back(n);
3047            } else {
3048                stamps[n] = rejected;
3049            }
3050        }
3051    }
3052    seen.sort_unstable();
3053    seen
3054}
3055struct SplitMix(u64);
3056impl SplitMix {
3057    fn next(&mut self) -> u64 {
3058        self.0 = self.0.wrapping_add(0x9e3779b97f4a7c15);
3059        let mut z = self.0;
3060        z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
3061        z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
3062        z ^ (z >> 31)
3063    }
3064}
3065