BREP_geometry 0.26.0

Geometry layer of the BREP kernel: vectors, tolerances, diagnostics, NURBS curves and surfaces, projection and intersection.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use crate::curve::interior_knot_count;
use crate::{project_point_to_surface, NurbsCurve, NurbsSurface, Vec3};
use serde::Serialize;

const EPSILON: f64 = crate::tolerance::FP_FLOOR;

use crate::spatial::Aabb as Bounds;


/// The box of the carrier's control points, in their order; the first control
/// point that is not a point is the error. Read without collecting them: it
/// is paid on every call, and a view ray through a fitted carrier of a gear
/// asks it thousands of times.
fn surface_bounds(surface: &NurbsSurface) -> Result<Bounds, String> {
    let mut bounds = Bounds::from_points([]);
    for point in surface.control_points.iter().flatten() {
        let point = point.point()?;
        bounds.minimum.x = bounds.minimum.x.min(point.x);
        bounds.minimum.y = bounds.minimum.y.min(point.y);
        bounds.minimum.z = bounds.minimum.z.min(point.z);
        bounds.maximum.x = bounds.maximum.x.max(point.x);
        bounds.maximum.y = bounds.maximum.y.max(point.y);
        bounds.maximum.z = bounds.maximum.z.max(point.z);
    }
    Ok(bounds)
}


/// The box of each knot-span patch's control points: the surface over span
/// `[u_i, u_i+1) x [v_j, v_j+1)` lies in the convex hull of the
/// `(p + 1) x (q + 1)` control points that support it (positive weights), so
/// a curve segment clear of every span box is clear of the surface.
///
/// The whole-net box cannot say that for a carrier that winds: an eight-turn
/// helical tube's box is the whole coil, every sample segment of a ray through
/// the coil passes it, and every one seeded a Newton that starts from a global
/// projection onto a 1280-point net — 21 of the 26 s the 2026-09-26 coil
/// fillet report's interference check took, for about one hit in forty seeds.
fn span_bounds(surface: &NurbsSurface) -> Result<Vec<Bounds>, String> {
    let (p, q) = (surface.degree_u, surface.degree_v);
    let rows = surface.control_points.len();
    let columns = surface.control_points.first().map_or(0, Vec::len);
    let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
        (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
    };
    let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
    // A malformed net has no span structure to trust: the whole-net box stands.
    if spans_u.is_empty() || spans_v.is_empty() {
        return Ok(vec![surface_bounds(surface)?]);
    }
    let mut boxes = Vec::with_capacity(spans_u.len() * spans_v.len());
    for &i in &spans_u {
        for &j in &spans_v {
            let mut bounds = Bounds::from_points([]);
            for row in &surface.control_points[i - p..=i] {
                for control in &row[j - q..=j] {
                    let point = control.point()?;
                    bounds.minimum.x = bounds.minimum.x.min(point.x);
                    bounds.minimum.y = bounds.minimum.y.min(point.y);
                    bounds.minimum.z = bounds.minimum.z.min(point.z);
                    bounds.maximum.x = bounds.maximum.x.max(point.x);
                    bounds.maximum.y = bounds.maximum.y.max(point.y);
                    bounds.maximum.z = bounds.maximum.z.max(point.z);
                }
            }
            boxes.push(bounds);
        }
    }
    Ok(boxes)
}

fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
    crate::projection::fit_parameter(value, minimum, maximum, closed)
}

fn solve_three(matrix: [[f64; 3]; 3], rhs: Vec3) -> Option<[f64; 3]> {
    let a = matrix;
    let determinant = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
        - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
        + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
    let scale: f64 = a.iter().flatten().map(|value| value.abs()).sum();
    if determinant.abs() <= 1e-14 * scale.max(1.0).powi(3) {
        return None;
    }
    let x = (rhs.x * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
        - a[0][1] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
        + a[0][2] * (rhs.y * a[2][1] - a[1][1] * rhs.z))
        / determinant;
    let y = (a[0][0] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
        - rhs.x * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
        + a[0][2] * (a[1][0] * rhs.z - rhs.y * a[2][0]))
        / determinant;
    let z = (a[0][0] * (a[1][1] * rhs.z - rhs.y * a[2][1])
        - a[0][1] * (a[1][0] * rhs.z - rhs.y * a[2][0])
        + rhs.x * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
        / determinant;
    Some([x, y, z])
}

/// `BREP_CS_NEWTON_LOCAL_START` (default on; =0 opens from the global foot): on a classifier's ray
/// ([`intersect_ray_surface`]), each seed's Newton opens from
/// the local foot of its curve point ([`crate::projection::project_point_to_surface_local`]:
/// Newton from the seed grid's nearest sample) instead of the nearest point of
/// the whole surface. The opening foot is only a start: the Newton then solves
/// curve = surface on its own, and the gap filter and duplicate guard read its
/// answer as before. On a ray through a winding carrier the global stage was
/// nine tenths of each Newton's cost.
pub fn newton_local_start_enabled() -> bool {
    switch!("BREP_CS_NEWTON_LOCAL_START", true)
}

/// `BREP_CS_NEWTON_LOCAL_START_CHECK=1` (with the start switch on): solve every
/// call from both starts, return the local one's answer, and count (and print)
/// each opening foot more than the model tolerance from the global one's and
/// each call whose hits differ ([`newton_start_check_counts`]).
fn newton_local_start_check() -> bool {
    switch!("BREP_CS_NEWTON_LOCAL_START_CHECK", false)
}

static START_CHECK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static START_CHECK_FEET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static START_CHECK_FOOT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static START_CHECK_HIT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// What the check mode has compared in this process: `(calls, opening feet,
/// feet apart by more than the model tolerance, calls whose hits differ)`.
pub fn newton_start_check_counts() -> (u64, u64, u64, u64) {
    use std::sync::atomic::Ordering::Relaxed;
    (
        START_CHECK_CALLS.load(Relaxed),
        START_CHECK_FEET.load(Relaxed),
        START_CHECK_FOOT_DISAGREEMENTS.load(Relaxed),
        START_CHECK_HIT_DISAGREEMENTS.load(Relaxed),
    )
}

/// The Newton's opening foot of `point`: local or the whole surface's nearest.
/// In check mode the local start also reads the global foot and counts the two
/// apart by more than the model tolerance.
fn opening_foot(surface: &NurbsSurface, point: Vec3, local: bool, check: bool) -> Result<[f64; 2], String> {
    if !local {
        let projection = project_point_to_surface(surface, point)?;
        return Ok([projection.u, projection.v]);
    }
    let projection = crate::projection::project_point_to_surface_local(surface, point)?;
    if check {
        use std::sync::atomic::Ordering::Relaxed;
        START_CHECK_FEET.fetch_add(1, Relaxed);
        let nearest = project_point_to_surface(surface, point)?;
        let apart = projection.point.sub(nearest.point).length();
        if apart > crate::tolerance::DEFAULT_MODEL {
            START_CHECK_FOOT_DISAGREEMENTS.fetch_add(1, Relaxed);
            eprintln!(
                "cs newton start check: foot apart {apart:.3e} (local {:.3e} at ({:.9},{:.9}), nearest {:.3e} at ({:.9},{:.9}))",
                projection.distance, projection.u, projection.v, nearest.distance, nearest.u, nearest.v
            );
        }
    }
    Ok([projection.u, projection.v])
}

fn newton_curve_surface(
    curve: &NurbsCurve,
    surface: &NurbsSurface,
    seed: f64,
    local_start: bool,
    check: bool,
) -> Result<[f64; 3], String> {
    let [t0, t1] = curve.domain()?;
    let [u0, u1] = surface.domain_u()?;
    let [v0, v1] = surface.domain_v()?;
    let (closed_u, closed_v) = surface.closed_directions()?;
    let mut t = seed;
    let [mut u, mut v] = opening_foot(surface, curve.evaluate(t)?, local_start, check)?;
    for _ in 0..60 {
        let (curve_point, tangent) = curve.deriv1(t)?;
        let (surface_point, du, dv) = surface.deriv1(u, v)?;
        let residual = curve_point.sub(surface_point);
        if residual.length() <= EPSILON {
            return Ok([t, u, v]);
        }
        let Some([mut step_t, mut step_u, mut step_v]) = solve_three(
            [
                [tangent.x, -du.x, -dv.x],
                [tangent.y, -du.y, -dv.y],
                [tangent.z, -du.z, -dv.z],
            ],
            residual.scale(-1.0),
        ) else {
            if tangent.length_squared() <= EPSILON {
                return Ok([t, u, v]);
            }
            let next_t = (t - residual.dot(tangent) / tangent.length_squared()).clamp(t0, t1);
            if (next_t - t).abs() <= 1e-15 * (t1 - t0) {
                return Ok([t, u, v]);
            }
            t = next_t;
            // The next iterate's foot, continued from this one's: the Newton
            // is on ONE sheet, and the nearest point of the whole surface to
            // the stepped curve point can be on another.
            let projection =
                crate::projection::project_point_to_surface_from_seed(surface, curve.evaluate(t)?, [u, v])?;
            u = projection.u;
            v = projection.v;
            continue;
        };
        step_t = step_t.clamp(-(t1 - t0) / 4.0, (t1 - t0) / 4.0);
        step_u = step_u.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
        step_v = step_v.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
        let next_t = (t + step_t).clamp(t0, t1);
        let next_u = fit_parameter(u + step_u, u0, u1, closed_u);
        let next_v = fit_parameter(v + step_v, v0, v1, closed_v);
        let stalled = (next_t - t).abs() <= 1e-15 * (t1 - t0)
            && (next_u - u).abs() <= 1e-15 * (u1 - u0)
            && (next_v - v).abs() <= 1e-15 * (v1 - v0);
        t = next_t;
        u = next_u;
        v = next_v;
        if stalled {
            return Ok([t, u, v]);
        }
    }
    Ok([t, u, v])
}

#[derive(Clone, Copy, Debug, Serialize)]
pub struct CurveSurfaceIntersection {
    pub t: f64,
    pub u: f64,
    pub v: f64,
    pub point: Vec3,
    pub gap: f64,
    pub tangential: bool,
}

/// Whether the duplicate guard's parameter tolerance is capped by the curve's
/// domain. `BREP_CS_DUPLICATE_CAP=0` restores the uncapped tolerance, which at
/// a stationary parameter is 1e6 and swallows every other hit on the curve.
fn duplicate_cap_enabled() -> bool {
    switch!("BREP_CS_DUPLICATE_CAP", true)
}

pub fn intersect_curve_surface(
    curve: &NurbsCurve,
    surface: &NurbsSurface,
    tolerance: f64,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
    let seeds = sampled_seeds(curve, surface, tolerance)?;
    intersect_curve_surface_from_seeds(curve, surface, tolerance, seeds)
}

/// The general search's Newton seeds: the midpoint of every sample segment
/// of the curve whose box meets the surface's box and one of its span boxes.
fn sampled_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64) -> Result<Vec<f64>, String> {
    let [t0, t1] = curve.domain()?;
    let surface_box = surface_bounds(surface)?.expanded(tolerance * 10.0);
    let sample_count =
        32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
    let mut samples = Vec::with_capacity(sample_count + 1);
    for index in 0..=sample_count {
        let t = t0 + (t1 - t0) * index as f64 / sample_count as f64;
        samples.push((t, curve.evaluate(t)?));
    }
    let span_boxes = span_bounds(surface)?;
    let mut seeds = Vec::new();
    for pair in samples.windows(2) {
        let segment_box = Bounds::from_points([pair[0].1, pair[1].1]).expanded(tolerance * 10.0);
        if segment_box.intersects_exact(surface_box)
            && span_boxes.iter().any(|span_box| segment_box.intersects_exact(span_box.expanded(tolerance * 10.0)))
        {
            seeds.push((pair[0].0 + pair[1].0) * 0.5);
        }
    }
    Ok(seeds)
}

/// [`intersect_curve_surface`] from the caller's own Newton seeds (curve
/// parameters): the same Newton, gap filter, duplicate guard and tangency
/// reading as the general search, only the seeds differ. The classifier's
/// exact ray lane (`crate::exact_line_surface`) seeds it with the closed-form
/// roots of a straight segment against an analytic carrier.
pub fn intersect_curve_surface_from_seeds(
    curve: &NurbsCurve,
    surface: &NurbsSurface,
    tolerance: f64,
    seeds: Vec<f64>,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
    solve_counted(curve, surface, tolerance, &seeds, false)
}

/// [`intersect_curve_surface`] for a point classifier's ray: the same search,
/// with each Newton opened from the local foot when
/// `BREP_CS_NEWTON_LOCAL_START` is on. Only a ray caller may take it: it reads
/// the parity of transversal crossings and casts another direction on a
/// grazing hit, so a cluster of roots where a curve runs along the surface (an
/// edge on a face, where the two starts can keep different members of the
/// cluster) never decides its answer.
pub fn intersect_ray_surface(
    curve: &NurbsCurve,
    surface: &NurbsSurface,
    tolerance: f64,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
    let seeds = sampled_seeds(curve, surface, tolerance)?;
    solve_counted(curve, surface, tolerance, &seeds, true)
}

fn solve_counted(
    curve: &NurbsCurve,
    surface: &NurbsSurface,
    tolerance: f64,
    seeds: &[f64],
    ray: bool,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
    if !ray || !newton_local_start_enabled() {
        return solve_from_seeds(curve, surface, tolerance, seeds, false, false);
    }
    if !newton_local_start_check() {
        return solve_from_seeds(curve, surface, tolerance, seeds, true, false);
    }
    let local = solve_from_seeds(curve, surface, tolerance, seeds, true, true)?;
    let global = solve_from_seeds(curve, surface, tolerance, seeds, false, false)?;
    START_CHECK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    if !same_hits(&local, &global, tolerance) {
        START_CHECK_HIT_DISAGREEMENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let read = |hits: &[CurveSurfaceIntersection]| hits.iter().map(|hit| hit.t).collect::<Vec<_>>();
        eprintln!(
            "cs newton start check: hits differ: local t {:?} global t {:?}",
            read(&local),
            read(&global)
        );
    }
    Ok(local)
}

/// The two starts read the same hits: as many, each at the same place within
/// the duplicate guard's chord (`tolerance * 10`), with the same tangency.
fn same_hits(first: &[CurveSurfaceIntersection], second: &[CurveSurfaceIntersection], tolerance: f64) -> bool {
    first.len() == second.len()
        && first.iter().zip(second).all(|(a, b)| {
            a.point.sub(b.point).length() <= tolerance * 10.0 && a.tangential == b.tangential
        })
}

fn solve_from_seeds(
    curve: &NurbsCurve,
    surface: &NurbsSurface,
    tolerance: f64,
    seeds: &[f64],
    local_start: bool,
    check: bool,
) -> Result<Vec<CurveSurfaceIntersection>, String> {
    let [t0, t1] = curve.domain()?;
    let mut results: Vec<CurveSurfaceIntersection> = Vec::new();
    for &seed in seeds {
        let [t, u, v] = newton_curve_surface(curve, surface, seed, local_start, check)?;
        let on_curve = curve.evaluate(t)?;
        let on_surface = surface.evaluate(u, v)?;
        let gap = on_curve.sub(on_surface).length();
        if gap > tolerance {
            continue;
        }
        let tangent = curve.deriv1(t)?.1;
        // Two hits are the SAME hit when they are at the same PLACE, and the
        // chord test below is what measures that. This parameter test only has
        // to absorb two seeds landing on one root a few ulps apart — and it
        // converts the caller's 3D tolerance into a parameter tolerance by
        // dividing by the curve's speed, a quotient that is unbounded where the
        // speed is not. At a stationary parameter the `EPSILON` floor makes it
        // `1e-7 / 1e-12 * 10 = 1e6`, wider than any curve's domain, so every
        // earlier hit on the curve reads as a duplicate and a legitimate
        // intersection AT a cusp is discarded unless it happens to be first.
        // An involute flank's speed is `r_base * t`, so a gear profile carries
        // one such cusp per flank per tooth: this is the 2026-09-14 herringbone
        // report's root cause one lane over, where it is silent rather than
        // loud.
        //
        // The cap is the curve's OWN domain, which is the only scale this test
        // has: 1e-6 of it keeps the ulp-absorbing job (nine orders above the
        // `1e-15 * (t1 - t0)` stall the Newton above exits on, three above the
        // 1e-9 floor this rule already had) and drops the unbounded one. Two
        // seeds on the same cusp root can land further apart than that in
        // parameter, but not in space, and the chord test catches them.
        // Escape hatch for tamper-verification:
        // BREP_CS_DUPLICATE_CAP=0 restores the uncapped tolerance.
        let uncapped = ((tolerance / tangent.length().max(EPSILON)) * 10.0).max((t1 - t0) * 1e-9);
        let capped = uncapped.min((t1 - t0) * 1e-6);
        let parameter_tolerance = if duplicate_cap_enabled() { capped } else { uncapped };
        if let Some(result) = results.iter().find(|result| {
            (result.t - t).abs() <= parameter_tolerance
                || result.point.sub(on_curve).length() <= tolerance * 10.0
        }) {
            // The only drops the cap changes: a PARAMETER-only match (the two
            // hits are apart in space) that the capped tolerance would keep. A
            // hit dropped here leaves no trace anywhere else, so name it when
            // asked: `BREP_DEBUG_CS_DUPLICATE=1`. With the cap on this prints
            // nothing by construction; under `BREP_CS_DUPLICATE_CAP=0` it counts
            // what the cap recovers.
            let chord = result.point.sub(on_curve).length();
            let gap = (result.t - t).abs();
            if chord > tolerance * 10.0
                && gap > capped
                && std::env::var("BREP_DEBUG_CS_DUPLICATE").is_ok()
            {
                eprintln!(
                    "cs-duplicate: dropped t={t:.12} against t={:.12} gap={gap:.6e} ptol={parameter_tolerance:.6e} \
                     chord={chord:.6e} |tangent|={:.6e} domain=[{t0:.6},{t1:.6}] tolerance={tolerance:.3e}",
                    result.t,
                    tangent.length(),
                );
            }
            continue;
        }
        let normal = surface.normal(u, v).ok();
        let tangential = normal
            .and_then(|normal| {
                tangent
                    .normalized()
                    .ok()
                    .map(|unit| normal.dot(unit).abs() <= 1e-3)
            })
            .unwrap_or(false);
        results.push(CurveSurfaceIntersection {
            t,
            u,
            v,
            point: on_curve.add(on_surface).scale(0.5),
            gap,
            tangential,
        });
    }
    results.sort_by(|a, b| a.t.total_cmp(&b.t));
    Ok(results)
}