brep_geometry/geometry/tolerance.rs
1//! # Tolerance taxonomy — which bands may scale with part size, and which must not
2//!
3//! Every numeric tolerance in this kernel belongs to exactly one of the KINDS
4//! below. The distinction that matters for correctness is whether a band may be
5//! **size-coupled** (widened in proportion to the local part extent) or must stay
6//! a **tight absolute** floor. Getting this wrong is not academic: coupling the
7//! base spatial `model` tolerance to part size was tried and REJECTED because
8//! `model` also feeds the fit-accuracy fields, and scaling it degraded SSI curve
9//! fitting enough to produce invalid boolean topology (see the B1 finding in
10//! `revolve_pole_union_fixture`). The rules:
11//!
12//! * **Identity / coincidence** — "are these two entities the same point / are
13//! these surfaces the same surface?". MAY size-couple: a big part legitimately
14//! needs a proportionally wider identity band. Couple it *at the site* via
15//! [`KernelTolerances::heal_band`] (`max(model, diagonal * k)`), taking the
16//! local `diagonal`/extent explicitly — never by inflating the global `model`.
17//!
18//! * **Fit-accuracy** — `intersection_fit`, the SSI/CSI marcher, curve/surface
19//! fitting. MUST stay TIGHT. Do NOT size-couple: this is "how closely must
20//! committed geometry agree?", and loosening it silently degrades every export.
21//! This is the field that broke `revolve_pole_union` when coupled (B1).
22//!
23//! * **Weld / sew** — the distinct-vertex / weld radius used when knitting
24//! endpoints and edges together (assembler weld, endpoint commit, vertex
25//! merge). A *search* radius answering "which entities might match?", floored
26//! to a small absolute so noise-free models still weld; see the named weld
27//! accessors on [`KernelTolerances`].
28//!
29//! * **Knot-parameter** — knot-vector identity and numerical knot dedup. Two
30//! distinct purposes at two distinct values: knot IDENTITY
31//! (`KNOT_IDENTITY_TOL`, 1e-9) and numerical knot DEDUP (`KNOT_DEDUP_EPS`,
32//! 1e-12), both single-sourced in `curve.rs`. Parameter-space, not spatial;
33//! derived from a spatial band only via [`parametric_tolerance`].
34//!
35//! * **Angular** — direction/normal agreement in radians (`angular`). A fixed
36//! absolute; does not scale with part size.
37//!
38//! * **Strict-interior** — small skip epsilons that keep a parameter off the
39//! exact domain end (so knot insertion / split does not refuse it). Fixed,
40//! derived from the knot-identity band, not size-coupled.
41//!
42//! * **Floating-point floor** — the `1e-12`/`1e-15` guards that keep a division
43//! or a degenerate direction from blowing up. Never a modelling tolerance.
44//!
45//! Bottom line: identity/weld bands couple to size *locally* through
46//! [`KernelTolerances::heal_band`]/`solid_scale`; fit-accuracy, angular, and
47//! the floating-point floors stay tight.
48
49use serde::{Deserialize, Serialize};
50
51/// Ordered accuracy targets plus deliberately separate geometric search radii.
52///
53/// Search tolerances answer "which entities might match?". Accuracy
54/// tolerances answer "how closely must committed geometry agree?". Keeping
55/// those questions separate prevents a generous sewing search radius from
56/// becoming the accuracy of the exported BREP.
57#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
58#[serde(default)]
59pub struct KernelTolerances {
60 /// Iterative projection/refinement convergence target.
61 pub convergence: f64,
62 /// Vertex identity and exact topological coincidence tolerance.
63 pub model: f64,
64 /// Maximum geometric error accepted while fitting SSI curves.
65 pub intersection_fit: f64,
66 /// Maximum edge/pcurve/carrier disagreement in a valid in-memory BREP.
67 pub pcurve_consistency: f64,
68 /// Output edge-to-carrier contract used before STEP serialization.
69 pub export_knit: f64,
70 /// Candidate radius used while looking for endpoints or edges to weld.
71 pub sew_search: f64,
72 /// Features shorter than this are candidates for explicit sliver repair.
73 pub sliver: f64,
74 /// Angular tolerance in radians.
75 pub angular: f64,
76}
77
78impl Default for KernelTolerances {
79 fn default() -> Self {
80 Self::for_scale(1.0, DEFAULT_MODEL)
81 }
82}
83
84impl KernelTolerances {
85 /// Construct a scale-aware policy while preserving the historical model
86 /// identity tolerance used by the public API.
87 ///
88 /// The base spatial identity tolerance `model` is deliberately NOT coupled
89 /// to part size here: coupling it was tried and rejected because `model`
90 /// also feeds fit-accuracy fields (`intersection_fit`, `sew_search`), so
91 /// scaling it degrades SSI curve fitting on ordinary parts and produces
92 /// invalid boolean topology (see `revolve_pole_union_fixture`). Identity
93 /// bands that legitimately scale with size are size-coupled per site via
94 /// [`KernelTolerances::heal_band`] instead, leaving fit accuracy tight.
95 pub fn for_scale(scale: f64, model: f64) -> Self {
96 let scale = scale.abs().max(1.0);
97 let model = model.abs().max(1e-12);
98 Self {
99 convergence: (model * 1e-3).clamp(1e-12, model),
100 model,
101 intersection_fit: (model * 20.0).max(scale * 1e-8),
102 // Existing fitted NURBS intersections can deviate by a few
103 // microns. This remains an explicit contract rather than a
104 // validator-local magic number.
105 pcurve_consistency: (model * 200.0).max(4e-3),
106 export_knit: (model * 100.0).max(4e-3),
107 sew_search: (model * 20.0).max(scale * 1e-8),
108 sliver: (model * 4.0).max(scale * 1e-10),
109 angular: 1e-4,
110 }
111 }
112
113 pub fn for_solid<S: SolidScale + ?Sized>(solid: &S, model: f64) -> Self {
114 Self::for_scale(solid.solid_scale(), model)
115 }
116
117 pub fn for_pair<S: SolidScale + ?Sized>(first: &S, second: &S, model: f64) -> Self {
118 Self::for_scale(first.solid_scale().max(second.solid_scale()), model)
119 }
120
121 /// Reject policies whose accuracy ladder is inverted or whose search
122 /// radii cannot even find model-identical entities.
123 pub fn check(&self) -> Result<(), String> {
124 let positive = [
125 ("convergence", self.convergence),
126 ("model", self.model),
127 ("intersection_fit", self.intersection_fit),
128 ("pcurve_consistency", self.pcurve_consistency),
129 ("export_knit", self.export_knit),
130 ("sew_search", self.sew_search),
131 ("sliver", self.sliver),
132 ("angular", self.angular),
133 ];
134 for (name, value) in positive {
135 if !value.is_finite() || value <= 0.0 {
136 return Err(format!("invalid {name} tolerance {value}"));
137 }
138 }
139 for ((first_name, first), (second_name, second)) in [
140 (("convergence", self.convergence), ("model", self.model)),
141 (
142 ("model", self.model),
143 ("intersection_fit", self.intersection_fit),
144 ),
145 ] {
146 if first > second {
147 return Err(format!(
148 "tolerance ladder violated: {first_name} ({first:.3e}) > \
149 {second_name} ({second:.3e})"
150 ));
151 }
152 }
153 if self.sew_search < self.model {
154 return Err(format!(
155 "sew_search ({:.3e}) is below model tolerance ({:.3e})",
156 self.sew_search, self.model
157 ));
158 }
159 Ok(())
160 }
161
162 /// Canonical accessor for the single spatial tolerance `x` (Golovanov
163 /// §4.13). `model` is that `x`: the base identity/coincidence band from
164 /// which parametric, search, and healing tolerances are derived. Call
165 /// sites should prefer this over reaching for `.model` directly so intent
166 /// (the ONE spatial tolerance) reads clearly and later levers have a single
167 /// seam to evolve.
168 pub fn spatial(&self) -> f64 {
169 self.model
170 }
171
172 /// Size-coupled healing/identity band: the base spatial tolerance floored
173 /// by a fraction `k` of the caller's local `diagonal`. This is the ONE
174 /// charter helper for the `max(model, diagonal * k)` pattern that healing
175 /// and identity sites otherwise hand-roll (e.g. classification's
176 /// near-coincidence probe `(model * 10).max(diagonal * 1e-7)`), so a
177 /// size-relative band is derived from `x` in a single place instead of
178 /// re-hardcoded per call site (Golovanov §4.13). Coupling the band HERE —
179 /// at the identity/weld/heal site, taking `diagonal` explicitly — gives big
180 /// parts a proportionally wider identity band WITHOUT inflating the global
181 /// `model` or the fit-accuracy path (`intersection_fit`, the marcher).
182 /// `k` is a dimensionless part-per-diagonal factor; `diagonal` is the local
183 /// extent the band should scale with.
184 pub fn heal_band(&self, diagonal: f64, k: f64) -> f64 {
185 self.model.max(diagonal.abs() * k.abs())
186 }
187
188 /// Size-coupled acceptance ceiling for the edge-vs-pcurve COINCIDENCE check
189 /// in `BrepSolid::validate`: "does this coedge's curve-on-surface, pushed
190 /// back to 3D, still trace the same locus as the edge's 3D curve?"
191 ///
192 /// This is an IDENTITY/coincidence band (are the two representations the
193 /// SAME edge?), not a fit-accuracy target, so per this module's taxonomy it
194 /// MAY — and, for imported geometry, MUST — size-couple with the part: a
195 /// vendor STEP file routinely commits an edge's 3D curve and its face
196 /// surface as INDEPENDENT approximations that disagree by a small fraction
197 /// of the model, and (like Parasolid/OCC, which absorb the gap in a widened
198 /// per-edge tolerance) a coincidence band floored to a tight ABSOLUTE
199 /// `pcurve_consistency` wrongly rejects such a shared edge on a sub-unit
200 /// part. The gap is intrinsic to the vendor data (it is the closest-point
201 /// residual of the edge against the surface, so no pcurve fit can beat it),
202 /// and the edge is SHARED — snapping it onto one face's surface only pushes
203 /// it off the neighbour's — so accepting the size-relative gap is the
204 /// faithful, non-destructive resolution.
205 ///
206 /// Coupling lives HERE (taking the model `diagonal` explicitly, floored by
207 /// the tight `pcurve_consistency`) exactly like [`KernelTolerances::heal_band`],
208 /// so the fit target and the STEP-import edge-reconcile screen — which read
209 /// the raw `pcurve_consistency` FIELD — stay tight and are NOT relaxed by
210 /// this validator-only ceiling. `PCURVE_ACCEPTANCE_REL` (2.5% of the model
211 /// diagonal) sits above the vendor near-miss this admits (~2% of the
212 /// diagonal on ABC 00000041) yet far below the many-percent excursion a
213 /// genuinely wrong carrier or branch-jumped pcurve produces, so real breakage
214 /// is still refused.
215 pub fn pcurve_acceptance(&self, diagonal: f64) -> f64 {
216 self.pcurve_consistency
217 .max(diagonal.abs() * PCURVE_ACCEPTANCE_REL)
218 }
219}
220
221/// The default spatial identity tolerance, `KernelTolerances::default().model`
222/// (consolidation L9). The modules that hard-coded it as their own
223/// `LINEAR_TOLERANCE` (pcurve, projection, SSI) name it here; they still do not
224/// read a caller's non-default `model` (threading the policy is a separate,
225/// behaviour-changing step).
226pub const DEFAULT_MODEL: f64 = 1e-7;
227
228/// Floating-point floor (consolidation L9): guards a division, a
229/// normalisation or a Newton step against a value indistinguishable from zero.
230/// Never a modelling tolerance.
231pub const FP_FLOOR: f64 = 1e-12;
232
233/// Fraction of the model bounding-box diagonal used as the size-coupled edge/
234/// pcurve coincidence ceiling in [`KernelTolerances::pcurve_acceptance`].
235pub const PCURVE_ACCEPTANCE_REL: f64 = 0.025;
236
237/// Absolute floor (mm) of the edge-endpoint-vs-vertex identity band used by
238/// `BrepSolid::validate`: below this a curve end and its topological vertex
239/// ARE the same point (vendor export precision), above it the model is asked to
240/// state the meeting exactly.
241///
242/// Single-sourced because the STEP importer must heal precisely the misses this
243/// band refuses: healing less leaves an import that cannot validate, healing
244/// more rewrites vendor geometry the kernel already accepts as-is (see
245/// `heal_imported_edge_endpoints`).
246pub const VERTEX_MATCH_FLOOR: f64 = 5e-3;
247
248/// Derive a parametric tolerance from one spatial tolerance and the local
249/// derivative magnitude: `e = x / |c'(t)|`.
250///
251/// The same spatial error corresponds to different parametric errors on
252/// every curve and surface, so parameter-space tolerances must be derived
253/// locally from a single spatial precision, never written as fixed
254/// parameter-space literals (Golovanov, "Geometric Modeling" §4.13). The
255/// derivative floor guards degenerate directions (poles, collapsed edges)
256/// from producing an unbounded band; callers that know their domain span
257/// should additionally cap the result to a fraction of it.
258pub fn parametric_tolerance(spatial: f64, derivative_magnitude: f64) -> f64 {
259 spatial.abs().max(1e-15) / derivative_magnitude.abs().max(1e-9)
260}
261
262/// Scalar UV band for surface queries at a point with derivative magnitudes
263/// `|r_u|`, `|r_v|`: the conservative bound that contains the anisotropic
264/// `(x/|r_u|, x/|r_v|)` box is `x` over the smaller derivative.
265pub fn surface_uv_tolerance(spatial: f64, du_magnitude: f64, dv_magnitude: f64) -> f64 {
266 parametric_tolerance(spatial, du_magnitude.abs().min(dv_magnitude.abs()))
267}
268
269// ---------------------------------------------------------------------------
270// Weld / distinct-vertex radii — one named source per drifting expression.
271//
272// The kernel welds "the same vertex reached by two independent fits" at several
273// sites, and the survey found the SAME concept written three different ways with
274// three different effective values (drift). These accessors name each variant
275// and RETURN its exact prior value, so the drift is visible and single-sourced
276// in ONE place WITHOUT changing behaviour (bit-identical by construction). A
277// future decision to truly unify them becomes a one-line edit here.
278// ---------------------------------------------------------------------------
279
280/// Absolute floor for the assembler/imprint weld radius (see [`assembler_weld`]).
281pub const WELD_FLOOR: f64 = 1e-5;
282
283/// Absolute floor for the endpoint-commit weld radius (see [`commit_weld`]).
284/// Deliberately looser than [`WELD_FLOOR`] (1e-4 vs 1e-5): the commit pass runs
285/// on already-healed solids where the surviving endpoint gaps are larger than
286/// assembly-time vertex noise. This difference is intentional and preserved.
287pub const COMMIT_WELD_FLOOR: f64 = 1e-4;
288
289/// Assembler / imprint weld radius: the model identity tolerance `model` floored
290/// at [`WELD_FLOOR`]. Answers "which independently-fitted endpoints are the
291/// SAME vertex?" — a search radius, floored generously so a noise-free model
292/// (model ~ 1e-7) still welds coincident endpoints into a topological loop.
293/// Used by the boolean assembler (`vertex`/`edge`/triple-junction polish) and
294/// imprint's edge weld/limit sites.
295pub fn assembler_weld(model: f64) -> f64 {
296 model.max(WELD_FLOOR)
297}
298
299/// Endpoint-commit weld radius (`commit_nearby_edge_endpoints`, used by fillet /
300/// heal edge-gap closing): the caller's SEARCH tolerance floored at
301/// [`COMMIT_WELD_FLOOR`]. Same distinct-vertex concept as [`assembler_weld`]
302/// but a looser floor by design — see [`COMMIT_WELD_FLOOR`].
303pub fn commit_weld(search: f64) -> f64 {
304 search.max(COMMIT_WELD_FLOOR)
305}
306
307/// Size factor applied to imprint vertex-merge bands: `1 + extent`, where
308/// `extent` is the operands' bbox extent (`solid_scale`). This replaces the
309/// former `1 + ‖point‖` (distance-from-ORIGIN) coupling, an anti-pattern in
310/// which a part far from the origin got a wrongly-inflated merge band — a
311/// translation-VARIANCE defect (the same fillet at the origin vs translated
312/// far away produced different volumes, and eventually a broken result).
313/// Deriving the factor from the operands' bbox extent instead makes the band
314/// depend on the part's SIZE, not its position, matching the intent of
315/// `solid_scale` / [`KernelTolerances::heal_band`], and makes the imprint
316/// (hence booleans/fillets) translation-INVARIANT.
317pub fn merge_scale(extent: f64) -> f64 {
318 1.0 + extent
319}
320
321/// Absolute floor for the imprint "do these two surfaces COINCIDE?" distance
322/// band, applied under `(tolerance * k).max(COINCIDENCE_DISTANCE_FLOOR)` at each
323/// coincidence decision (`coplanar_pair` perpendicular gap, `cosurface_pair`
324/// projection gap). This is the single named source for that floor.
325///
326/// The survey once found this coincidence question answered with two different
327/// values (a `1e-5` floor at some imprint sites vs `1e-6` elsewhere); that value
328/// drift was already eliminated upstream — the coincidence distance band is now
329/// uniformly floored at `1e-6` — so single-sourcing here is bit-identical and
330/// only removes the remaining duplicated literal. The companion normal-parallel
331/// test (`|n_a·n_b|` vs `1 - 1e-6/1e-9`) is a separate ANGULAR criterion and is
332/// deliberately NOT folded in here.
333pub const COINCIDENCE_DISTANCE_FLOOR: f64 = 1e-6;
334
335// ---------------------------------------------------------------------------
336// Model scale — the ONE characteristic length every size-relative tolerance in
337// this kernel is measured against.
338// ---------------------------------------------------------------------------
339
340/// The kernel's single definition of a model's characteristic length: the
341/// **bounding-box diagonal** of a point set.
342///
343/// Two properties define it, and both are load-bearing:
344///
345/// * **Size-based.** It answers "how big is *this* geometry?", which is the only
346/// question a size-relative tolerance may ask. Note what "this" means: the
347/// answer is the extent of the point set handed in, so the caller chooses the
348/// scope by choosing the points. A local solve should pass its own local
349/// geometry (see [`curve_model_scale`]) rather than the whole solid's
350/// vertices, or a 2 mm feature inherits a 2 m frame's band.
351/// * **Translation-invariant.** Moving the geometry rigidly does not change it,
352/// so the identical feature solves to the identical tolerance wherever the
353/// modeller happened to place it.
354///
355/// # Why the origin-distance form is wrong
356///
357/// The tempting one-liner `points.map(|p| p.length()).fold(1.0, f64::max)` — the
358/// maximum distance from the **world origin** — satisfies neither property:
359///
360/// * It **grows with placement.** A 10 mm part at the origin gets scale ≈ 10; the
361/// same part translated to (5000, 0, 0) gets scale ≈ 5000. Every tolerance
362/// derived from it loosens by 500× for a part that did not change shape, so
363/// coincidence, weld and convergence bands silently absorb real geometric
364/// error the moment a part is placed away from the origin.
365/// * It **ignores size.** Two parts whose bounding boxes differ by three orders
366/// of magnitude get the same scale if they sit the same distance out.
367/// * It is **translation-VARIANT**, so results are not reproducible under a rigid
368/// move: the same fillet at the origin and translated far away produced
369/// different volumes, and eventually a broken result. `merge_scale` records
370/// that exact failure for the imprint vertex-merge band, which was fixed the
371/// same way.
372///
373/// # Degenerate input
374///
375/// An empty set, a single point, coincident points, or non-finite coordinates
376/// all return `1.0`: there is no meaningful extent to scale by, and a zero (or
377/// NaN, or infinite) scale would collapse or explode every derived band.
378///
379/// # Floors are the caller's business
380///
381/// `model_scale` returns the RAW diagonal for any well-formed input — it is not
382/// floored at 1.0. Sub-unit parts are real (see
383/// [`KernelTolerances::pcurve_acceptance`]'s ABC 00000041 case) and flooring
384/// would hand a 0.3 mm part a band larger than itself. Sites that want the
385/// historical `>= 1.0` floor take `solid_scale`, which applies it explicitly.
386pub fn model_scale(points: impl IntoIterator<Item = crate::Vec3>) -> f64 {
387 let mut low = crate::Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
388 let mut high = crate::Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
389 let mut any = false;
390 for point in points {
391 any = true;
392 low.x = low.x.min(point.x);
393 low.y = low.y.min(point.y);
394 low.z = low.z.min(point.z);
395 high.x = high.x.max(point.x);
396 high.y = high.y.max(point.y);
397 high.z = high.z.max(point.z);
398 }
399 if !any {
400 return 1.0;
401 }
402 let diagonal = high.sub(low).length();
403 if diagonal.is_finite() && diagonal > 0.0 {
404 diagonal
405 } else {
406 1.0
407 }
408}
409/// A body whose size sets its tolerance bands; the topology layer implements it for `BrepSolid`.
410pub trait SolidScale {
411 fn solid_scale(&self) -> f64;
412}
413
414impl<T: SolidScale + ?Sized> SolidScale for &T {
415 fn solid_scale(&self) -> f64 {
416 (**self).solid_scale()
417 }
418}
419
420impl<T: SolidScale + ?Sized> SolidScale for Box<T> {
421 fn solid_scale(&self) -> f64 {
422 (**self).solid_scale()
423 }
424}
425
426impl<T: SolidScale + ?Sized> SolidScale for std::rc::Rc<T> {
427 fn solid_scale(&self) -> f64 {
428 (**self).solid_scale()
429 }
430}
431
432impl<T: SolidScale + ?Sized> SolidScale for std::sync::Arc<T> {
433 fn solid_scale(&self) -> f64 {
434 (**self).solid_scale()
435 }
436}
437
438
439/// [`model_scale`] of a curve, sampled uniformly over `[t0, t1]`.
440///
441/// The characteristic length of a *local* solve — one edge and its immediate
442/// neighbourhood — is the extent of the curve being marched, not the extent of
443/// the whole solid it belongs to and emphatically not its distance from the
444/// origin. Sampling is uniform and at a fixed count so the result is
445/// deterministic and cheap next to the solves it scales. Probes are `evaluate`,
446/// which CLAMPS to the knot domain, so an overshot range still measures the
447/// curve's own extent rather than an extrapolation's.
448pub fn curve_model_scale(curve: &crate::NurbsCurve, t0: f64, t1: f64) -> Result<f64, String> {
449 let mut samples = Vec::with_capacity(CURVE_SCALE_SAMPLES + 1);
450 for index in 0..=CURVE_SCALE_SAMPLES {
451 let t = t0 + (t1 - t0) * index as f64 / CURVE_SCALE_SAMPLES as f64;
452 samples.push(curve.evaluate(t)?);
453 }
454 Ok(model_scale(samples))
455}
456
457/// Uniform sample count used by [`curve_model_scale`]. Enough to bound a
458/// closed conic or a wavy spline's extent within a few percent; far too cheap to
459/// matter beside the Newton solve whose tolerance it scales.
460pub const CURVE_SCALE_SAMPLES: usize = 16;
461
462/// Migration diagnostic for the one-[`model_scale`] change (slice 0).
463///
464/// Switching a pipeline's `scale` definition moves EVERY tolerance derived from
465/// it at once, so the corpus must be measurable before and after. Call this at
466/// a site that is changing over, with the old origin-distance value and the new
467/// size-based one, and run the batteries with `BREP_SCALE_DIAG=1` to see which
468/// fixtures actually move and by how much. `ratio > 1` means the old
469/// definition was LOOSER than the new one there (the placement-inflation this
470/// slice removes); `ratio < 1` means it was tighter.
471///
472/// Silent and free unless the variable is set: the lookup happens once and the
473/// superseded `origin_form` closure is never called otherwise, so the retired
474/// definition costs nothing in the shipped path while staying re-measurable.
475pub fn report_scale_migration(site: &str, model_form: f64, origin_form: impl FnOnce() -> f64) {
476 static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
477 if !*ENABLED.get_or_init(|| std::env::var("BREP_SCALE_DIAG").is_ok()) {
478 return;
479 }
480 let origin_form = origin_form();
481 let ratio = if model_form != 0.0 {
482 origin_form / model_form
483 } else {
484 f64::NAN
485 };
486 eprintln!("scale-diag site={site} origin={origin_form:.9} model={model_form:.9} ratio={ratio:.6}");
487}
488
489// ---------------------------------------------------------------------------
490// MEASURED tolerance — the deviation actually OBSERVED at construction
491// ---------------------------------------------------------------------------
492
493/// A deviation **measured** between a constructed entity and the geometry that
494/// entity was built to reproduce, recorded next to the **derived** band it was
495/// judged against.
496///
497/// # Why this type exists
498///
499/// Everything above this line in this module is *derived*: a band predicted
500/// from a size (`model_scale`), a policy field, or a constant, computed
501/// **before** the geometry exists. Nothing above this line ever looks at what
502/// the construction actually produced. A collocation fit, a polyline
503/// interpolation or a marched section can miss its intended locus by far more
504/// (or, far more often, far less) than the derived band assumed, and today that
505/// number is either thrown away or never taken.
506///
507/// This is the other half, and it is the half OCCT has and we did not:
508/// `BRepOffset_SimpleOffset::FillEdgeData` sets an edge's tolerance to the
509/// *measured* maximum distance between its new 3D curve and its pcurve on the
510/// offset surface, over every adjacent face
511/// (`BRepOffset_SimpleOffset.cxx:296-310`), and `UpdateTolerance`
512/// (`BRepOffset_MakeOffset.cxx:4196-4302`) re-measures and raises after the
513/// whole pipeline has run. Their model throughout is *measure, do not
514/// assume*: no tolerance in that pipeline is predicted from a size heuristic,
515/// each is measured off the geometry that was actually built and then
516/// propagated up the entity hierarchy.
517///
518/// # The direction rule — this may never loosen anything
519///
520/// A `MeasuredTolerance` is a **record of what happened, not a budget to
521/// spend.** The measured number may flow into
522///
523/// * a diagnostic,
524/// * a refusal message,
525/// * a comparison against a derived band that *tightens* an existing gate,
526///
527/// and nowhere else. It must never be `max`-ed into an acceptance band, a weld
528/// radius or a search radius, because a construction would then certify its own
529/// error: the sloppier the fit, the wider the band that judges it.
530///
531/// # Where it lives
532///
533/// Alongside the constructed entity, in the transient result struct the
534/// construction already returns — never as a field on `crate::BrepSolid`'s
535/// records. `BrepSolid` is serialized by `io/snapshot.rs`, which is a
536/// documented durable format; a record field would be a format change with a
537/// reader obligation. Persisting per-entity tolerances is a real and planned
538/// piece of work with its own design (slice S3) — this type is the measurement
539/// layer beneath it, and lands with no format churn at all.
540#[derive(Clone, Copy, Debug, PartialEq)]
541pub struct MeasuredTolerance {
542 deviation: f64,
543 band: f64,
544}
545
546impl MeasuredTolerance {
547 /// Record `deviation` against the derived `band` that was in force.
548 ///
549 /// Both arguments are normalised in the FAIL-SAFE direction, so a
550 /// measurement that went wrong reads as "worse than the band", never as
551 /// "fine": a non-finite or negative deviation becomes `+inf`, and a
552 /// non-finite or negative band becomes `0.0`. Either way
553 /// [`Self::exceeds_band`] answers `true`.
554 pub fn new(deviation: f64, band: f64) -> Self {
555 let deviation = if deviation.is_finite() && deviation >= 0.0 {
556 deviation
557 } else {
558 f64::INFINITY
559 };
560 let band = if band.is_finite() && band >= 0.0 {
561 band
562 } else {
563 0.0
564 };
565 Self { deviation, band }
566 }
567
568 /// A construction with no fit to measure — a closed-form analytic result,
569 /// or an affine offset that shifts a control net rigidly. Records `0.0`
570 /// deviation as a *claim*, which is why it is a named constructor: reading
571 /// `MeasuredTolerance::exact(band)` at a call site says "this lane has no
572 /// approximation error by construction", where `new(0.0, band)` would read
573 /// as an unmeasured default.
574 pub fn exact(band: f64) -> Self {
575 Self::new(0.0, band)
576 }
577
578 /// What the construction actually did.
579 pub fn deviation(&self) -> f64 {
580 self.deviation
581 }
582
583 /// What the size-derived policy demanded of it.
584 pub fn band(&self) -> f64 {
585 self.band
586 }
587
588 /// The construction met the band it was judged against.
589 pub fn within_band(&self) -> bool {
590 self.deviation <= self.band
591 }
592
593 /// The construction was WORSE than the derived band assumed — the case
594 /// worth acting on. A site that gates on this refuses; a site that only
595 /// reports names both numbers.
596 pub fn exceeds_band(&self) -> bool {
597 !self.within_band()
598 }
599
600 /// `deviation / band` — how much of the derived band the construction
601 /// spent. `> 1` is [`Self::exceeds_band`]; a value orders of magnitude
602 /// below `1` says the band is loose here, which is worth knowing and is
603 /// exactly what the corpus distribution reports. A zero band answers `0.0`
604 /// for a zero deviation and `+inf` otherwise.
605 pub fn utilisation(&self) -> f64 {
606 if self.band > 0.0 {
607 self.deviation / self.band
608 } else if self.deviation == 0.0 {
609 0.0
610 } else {
611 f64::INFINITY
612 }
613 }
614
615 /// The worse of two records: the larger deviation against the tighter band.
616 ///
617 /// Both halves move in the fail-safe direction, so folding a set of
618 /// per-coedge or per-edge measurements can only ever make the summary
619 /// harder to pass, never easier.
620 pub fn worse_of(self, other: Self) -> Self {
621 Self {
622 deviation: self.deviation.max(other.deviation),
623 band: self.band.min(other.band),
624 }
625 }
626
627 /// Fold a set of measurements into their worst, or `None` when empty.
628 pub fn worst(records: impl IntoIterator<Item = Self>) -> Option<Self> {
629 records.into_iter().reduce(Self::worse_of)
630 }
631
632 /// `measured 1.234e-7 against band 4.000e-3` — the shared wording for
633 /// refusal messages and diagnostics, so every site that reports a measured
634 /// deviation reports both numbers in the same form.
635 pub fn describe(&self) -> String {
636 format!(
637 "measured {:.3e} against band {:.3e}",
638 self.deviation, self.band
639 )
640 }
641}
642
643/// Relative volume drift between two measurements of the same body that is
644/// still the same answer: the case gate's band between a replay and its
645/// baseline (`examples/case_replay.rs`), and the perturbation rescue's bar for
646/// a rung against the exact lane's inclusion–exclusion identity
647/// (`csg::boolean::perturbation_retry`). One number, so the rescue can never
648/// accept a body the gate would call a different one. It only absorbs
649/// last-bit summation noise.
650pub const VOLUME_DRIFT_REL: f64 = 1e-9;
651
652/// Absolute floor of the volume drift band, see [`VOLUME_DRIFT_REL`].
653pub const VOLUME_DRIFT_ABS: f64 = 1e-9;
654
655/// Fraction of the local characteristic length an APPROXIMATE offset
656/// construction may deviate from the exact geometry it approximates — see
657/// [`offset_construction_band`].
658pub const OFFSET_CONSTRUCTION_REL: f64 = 5e-4;
659
660/// Absolute floor of [`offset_construction_band`], so a vanishingly small part
661/// is not held to a band below the arithmetic that builds it.
662pub const OFFSET_CONSTRUCTION_FLOOR: f64 = 5e-6;
663
664/// The band an approximate offset construction is judged against: 0.05% of the
665/// caller's local characteristic length, floored at
666/// [`OFFSET_CONSTRUCTION_FLOOR`].
667///
668/// This is a **fit-accuracy** band in this module's taxonomy — "how closely
669/// must committed geometry agree?" — and it is the offset family's own
670/// established answer, not a new number. Three sites hand-roll exactly this
671/// expression today: the ruled push's rim march
672/// (`edit/direct_edit/face_offset.rs:303`, whose comment names it "the in-tree
673/// precedent for how far an approximate offset result may be off"), the same
674/// file's hole rebuild (`:1343`), and the free-form push's dense residual gate
675/// (`edit/direct_edit/face_offset_freeform.rs:22`). Naming it here gives the
676/// MEASURED half of the tolerance model ([`MeasuredTolerance`]) the same bar the
677/// gated half already uses, so a measurement and a gate on the same construction
678/// cannot silently disagree. The three copies are deliberately NOT converted
679/// yet: two of those files are being rewritten by the general image-curve work
680/// — the planned move to a general `image_curve(surface, pcurve)` transfer for
681/// every pcurve, which retires the four iso-curve refusals at once — and a
682/// drive-by edit there would collide for no behavioural gain; the expressions
683/// are identical, so converting them later is a rename, not a change.
684///
685/// It is deliberately ~50x TIGHTER than
686/// [`KernelTolerances::pcurve_acceptance`], which is where the same edge is
687/// judged later by `crate::BrepSolid::validate`. The two answer different
688/// questions: `pcurve_acceptance` asks "is this edge and this surface the same
689/// entity?" and must absorb a vendor import's independent approximations, while
690/// this asks "did OUR fit reproduce what we asked it to?" and has no vendor to
691/// forgive. A construction that passes here passes validate with two orders of
692/// magnitude to spare; one that fails here is a bad fit even though validate
693/// would still accept it, which is precisely the case a measured tolerance
694/// exists to surface.
695pub fn offset_construction_band(scale: f64) -> f64 {
696 (scale.abs() * OFFSET_CONSTRUCTION_REL).max(OFFSET_CONSTRUCTION_FLOOR)
697}
698
699/// Propagate measured tolerances up one level of the entity hierarchy: from a
700/// vertex's incident edges (and the gaps between their ends and the vertex
701/// point) to the vertex itself.
702///
703/// The vertex's measured tolerance is the largest deviation any representation
704/// meeting there exhibits: the worst endpoint gap `|p_V − c_E(t_end)|` over the
705/// incident edge ends, and the worst measured deviation of those edges
706/// themselves — because a point that sits exactly on a curve which is itself
707/// `d` off its intended locus is `d` off that locus too.
708///
709/// # On OCCT's 1.001 factor — assessed, and deliberately NOT copied
710///
711/// `BRepOffset_SimpleOffset::FillVertexData` sets the vertex tolerance to
712/// `1.001 × max(adjacent edge tolerances, endpoint spread)`
713/// (`BRepOffset_SimpleOffset.cxx:398-424`). That factor is not geometry. OCCT
714/// requires the ordering `Tol(V) ≥ Tol(E) ≥ Tol(F)` to hold as a *validity
715/// invariant* on the persisted shape, re-checked by `BRepCheck_Vertex` /
716/// `BRepCheck_Edge` and re-imposed by `BRepLib::UpdateTolerances` after
717/// operations that recompute either side. A vertex tolerance set exactly equal
718/// to its edge's can be inverted by nothing more than a recomputation's last
719/// bit, so they pad by a tenth of a percent. It is an invariant fudge, and it
720/// is theirs because their tolerances are persisted, grow-only, and re-derived
721/// by checkers that compare them with `>`.
722///
723/// We have no such consumer. Nothing in this kernel stores a per-entity
724/// tolerance (see [`MeasuredTolerance`]'s "where it lives") and therefore
725/// nothing re-derives one and compares it strictly against another. Copying
726/// the factor here would make the record *false* — it would report 0.1% more
727/// deviation than was observed — for a benefit that does not exist. So there is
728/// no factor, and this function returns exactly the worst thing it saw.
729///
730/// If a later slice does persist these values and does enforce an ordering
731/// invariant across a recompute, that slice should reintroduce a named padding
732/// constant *at the invariant it protects*, with the comparison it protects
733/// named — not here, and not silently.
734pub fn vertex_tolerance_from_edges(
735 endpoint_gaps: impl IntoIterator<Item = f64>,
736 incident_edge_deviations: impl IntoIterator<Item = f64>,
737) -> f64 {
738 let sanitise = |value: f64| {
739 if value.is_finite() && value >= 0.0 {
740 value
741 } else {
742 f64::INFINITY
743 }
744 };
745 endpoint_gaps
746 .into_iter()
747 .chain(incident_edge_deviations)
748 .map(sanitise)
749 .fold(0.0f64, f64::max)
750}
751
752
753/// Shared rigidity band for component and STEP placements.
754pub const RIGID_TOL: f64 = 1e-8;