1use crate::{
13 classify_point, project_point_to_curve, project_point_to_surface, BrepSolid, FaceRecord,
14 KernelRefusal, KernelStage, PointClass, PolygonClass, Vec2, Vec3,
15};
16
17#[derive(Clone, Copy, Debug, PartialEq)]
19pub enum BoundaryPlace {
20 Face { face: u64, uv: [f64; 2] },
22 Edge { edge: u64, t: f64 },
24 Vertex { vertex: u64 },
26}
27
28#[derive(Clone, Copy, Debug)]
30pub struct BoundaryFoot {
31 pub point: Vec3,
32 pub distance: f64,
33 pub place: BoundaryPlace,
34}
35
36fn refusal(code: &'static str, message: String) -> KernelRefusal {
37 KernelRefusal::internal(KernelStage::Classify, code, message)
38}
39
40fn parameter_tolerance(face: &FaceRecord, uv: [f64; 2], tolerance: f64) -> f64 {
43 match face.surface.deriv1(uv[0], uv[1]) {
44 Ok((_, su, sv)) => {
45 let speed = su.length().max(sv.length());
46 if speed > 0.0 && speed.is_finite() { tolerance / speed } else { tolerance }
47 }
48 Err(_) => tolerance,
49 }
50}
51
52fn trim_class(face: &FaceRecord, uv: [f64; 2], tolerance: f64) -> Result<PolygonClass, KernelRefusal> {
55 let band = parameter_tolerance(face, uv, tolerance);
56 crate::parameter_point_in_face(face, Vec2 { x: uv[0], y: uv[1] }, band).map_err(|e| refusal("boundary_trim", e))
57}
58
59fn inside_trim(face: &FaceRecord, uv: [f64; 2], tolerance: f64) -> Result<bool, KernelRefusal> {
62 Ok(trim_class(face, uv, tolerance)? != PolygonClass::Outside)
63}
64
65fn is_true_foot(face: &FaceRecord, uv: [f64; 2], foot: Vec3, point: Vec3, tolerance: f64) -> bool {
70 let residual = point.sub(foot);
71 let length = residual.length();
72 if length <= tolerance {
73 return true;
74 }
75 let Some(normal) = outward_normal(face, uv) else { return false };
76 let along = residual.sub(normal.scale(residual.dot(normal))).length();
77 along <= tolerance.max(1e-9 * length)
78}
79
80const TRIM_SEED_GRID: usize = 16;
83
84#[doc(hidden)]
90pub fn face_feet(face: &FaceRecord, point: Vec3, tolerance: f64) -> Result<Vec<(Vec3, f64, [f64; 2], bool)>, KernelRefusal> {
91 let mut feet = Vec::new();
92 let mut take = |foot: crate::SurfaceProjection| -> Result<bool, KernelRefusal> {
93 let uv = [foot.u, foot.v];
94 let class = trim_class(face, uv, tolerance)?;
95 let inside = class != PolygonClass::Outside && is_true_foot(face, uv, foot.point, point, tolerance);
96 if inside {
97 feet.push((foot.point, foot.distance, uv, class == PolygonClass::Boundary));
98 }
99 Ok(inside)
100 };
101 let global = project_point_to_surface(&face.surface, point).map_err(|e| refusal("boundary_face_foot", e))?;
102 if take(global)? || matches!(face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
106 return Ok(feet);
107 }
108 let surface = &face.surface;
109 let ([u0, u1], [v0, v1]) = match (surface.domain_u(), surface.domain_v()) {
110 (Ok(u), Ok(v)) => (u, v),
111 _ => return Ok(feet),
112 };
113 let mut nearest: Option<(f64, [f64; 2])> = None;
114 for i in 0..=TRIM_SEED_GRID {
115 for j in 0..=TRIM_SEED_GRID {
116 let uv = [u0 + (u1 - u0) * i as f64 / TRIM_SEED_GRID as f64, v0 + (v1 - v0) * j as f64 / TRIM_SEED_GRID as f64];
117 if trim_class(face, uv, tolerance)? == PolygonClass::Outside {
118 continue;
119 }
120 let Ok(at) = surface.evaluate(uv[0], uv[1]) else { continue };
121 let distance = at.sub(point).length();
122 if nearest.is_none_or(|(best, _)| distance < best) {
123 nearest = Some((distance, uv));
124 }
125 }
126 }
127 if let Some((_, seed)) = nearest {
128 if let Ok(local) = crate::projection::project_point_to_surface_seeded(surface, point, seed[0], seed[1]) {
131 take(local)?;
132 }
133 }
134 Ok(feet)
135}
136
137fn boundary_feet(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Vec<(BoundaryFoot, bool)>, KernelRefusal> {
141 let mut feet = Vec::new();
142 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
143 for (foot, distance, uv, on_band) in face_feet(face, point, tolerance)? {
144 feet.push((BoundaryFoot { point: foot, distance, place: BoundaryPlace::Face { face: face.id, uv } }, on_band));
145 }
146 }
147 for edge in solid.edges.iter().filter(|edge| !edge.degenerate) {
148 let foot = project_point_to_curve(&edge.curve, point).map_err(|e| refusal("boundary_edge_foot", e))?;
149 let (low, high) = (edge.t0.min(edge.t1), edge.t0.max(edge.t1));
150 if foot.u >= low && foot.u <= high {
151 feet.push((BoundaryFoot { point: foot.point, distance: foot.distance, place: BoundaryPlace::Edge { edge: edge.id, t: foot.u } }, false));
152 }
153 }
154 for vertex in &solid.vertices {
155 feet.push((
156 BoundaryFoot {
157 point: vertex.point,
158 distance: vertex.point.sub(point).length(),
159 place: BoundaryPlace::Vertex { vertex: vertex.id },
160 },
161 false,
162 ));
163 }
164 Ok(feet)
165}
166
167pub fn nearest_boundary_point(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Option<BoundaryFoot>, KernelRefusal> {
174 let feet = boundary_feet(solid, point, tolerance)?;
175 let Some(&(best, on_band)) = feet.iter().min_by(|a, b| a.0.distance.total_cmp(&b.0.distance)) else { return Ok(None) };
176 if on_band {
177 let edge_or_vertex = feet
178 .iter()
179 .filter(|(foot, _)| !matches!(foot.place, BoundaryPlace::Face { .. }))
180 .filter(|(foot, _)| foot.point.sub(best.point).length() <= tolerance)
181 .min_by(|a, b| a.0.distance.total_cmp(&b.0.distance));
182 if let Some(&(foot, _)) = edge_or_vertex {
183 return Ok(Some(foot));
184 }
185 }
186 Ok(Some(best))
187}
188
189pub fn solid_closest_points(solid: &BrepSolid, points: &[Vec3], tolerance: f64) -> Result<Vec<Vec3>, KernelRefusal> {
193 points
194 .iter()
195 .map(|&point| {
196 let class = classify_point(point, solid, tolerance).map_err(|e| refusal("closest_classify", e))?.class;
197 if class != PointClass::Out {
198 return Ok(point);
199 }
200 nearest_boundary_point(solid, point, tolerance)?
201 .map(|foot| foot.point)
202 .ok_or_else(|| refusal("closest_empty", "the solid has no boundary".into()))
203 })
204 .collect()
205}
206
207fn face_by_id(solid: &BrepSolid, id: u64) -> Option<&FaceRecord> {
208 solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == id)
209}
210
211fn outward_normal(face: &FaceRecord, uv: [f64; 2]) -> Option<Vec3> {
215 let surface = &face.surface;
216 let normal = match surface.normal(uv[0], uv[1]) {
217 Ok(normal) => normal,
218 Err(_) => pole_normal(surface, uv)?,
219 };
220 Some(if face.same_sense { normal } else { normal.scale(-1.0) })
221}
222
223fn pole_normal(surface: &crate::NurbsSurface, uv: [f64; 2]) -> Option<Vec3> {
228 let [u0, u1] = surface.domain_u().ok()?;
229 let [v0, v1] = surface.domain_v().ok()?;
230 let inward = |at: f64, low: f64, high: f64| at + (0.5 * (low + high) - at) * 1e-6;
231 let (u, v) = (inward(uv[0], u0, u1), inward(uv[1], v0, v1));
232 let first = surface.normal(u, v).ok()?;
233 let round = [0.2, 0.4, 0.6, 0.8].map(|f| [(u0 + (u1 - u0) * f, v), (u, v0 + (v1 - v0) * f)]);
234 for (ru, rv) in round.into_iter().flatten() {
235 let (Ok(at), Ok(pole)) = (surface.evaluate(ru, rv), surface.evaluate(u, v)) else { continue };
238 if at.sub(pole).length() > 1e-6 * (1.0 + pole.length()) {
239 continue;
240 }
241 let normal = surface.normal(ru, rv).ok()?;
242 if normal.dot(first) < POLE_AGREEMENT {
243 return None;
244 }
245 }
246 Some(first)
247}
248
249const POLE_AGREEMENT: f64 = 0.999_999;
252
253const SMOOTH_ANGLE: f64 = 1e-6;
256
257fn normals_at(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Vec<Vec3>, KernelRefusal> {
260 let mut normals = Vec::new();
261 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
262 let foot = project_point_to_surface(&face.surface, point).map_err(|e| refusal("normal_face_foot", e))?;
263 if foot.distance <= tolerance && inside_trim(face, [foot.u, foot.v], tolerance)? {
264 if let Some(normal) = outward_normal(face, [foot.u, foot.v]) {
265 normals.push(normal);
266 }
267 }
268 }
269 Ok(normals)
270}
271
272pub fn solid_outward_normals(solid: &BrepSolid, points: &[Vec3], tolerance: f64) -> Result<Vec<Option<Vec3>>, KernelRefusal> {
278 points
279 .iter()
280 .map(|&point| {
281 let normals = normals_at(solid, point, tolerance)?;
282 let Some(&first) = normals.first() else { return Ok(None) };
283 let cos = SMOOTH_ANGLE.cos();
284 Ok(normals.iter().all(|normal| normal.dot(first) >= cos).then_some(first))
285 })
286 .collect()
287}
288
289pub fn solid_principal_curvatures(solid: &BrepSolid, points: &[Vec3], tolerance: f64) -> Result<Vec<Option<[f64; 2]>>, KernelRefusal> {
296 points
297 .iter()
298 .map(|&point| {
299 let Some(foot) = nearest_boundary_point(solid, point, tolerance)? else { return Ok(None) };
300 let (face, uv) = match foot.place {
303 BoundaryPlace::Face { face, uv } => match face_by_id(solid, face) {
304 Some(record) => (record, uv),
305 None => return Ok(None),
306 },
307 _ => {
308 let normals = normals_at(solid, foot.point, tolerance)?;
309 let Some(&first) = normals.first() else { return Ok(None) };
310 if !normals.iter().all(|normal| normal.dot(first) >= SMOOTH_ANGLE.cos()) {
311 return Ok(None);
312 }
313 let mut found = None;
314 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
315 let at = project_point_to_surface(&face.surface, foot.point).map_err(|e| refusal("curvature_face_foot", e))?;
316 if at.distance <= tolerance && inside_trim(face, [at.u, at.v], tolerance)? {
317 found = Some((face, [at.u, at.v]));
318 break;
319 }
320 }
321 match found {
322 Some(found) => found,
323 None => return Ok(None),
324 }
325 }
326 };
327 let surface = &face.surface;
332 let curvatures = surface.principal_curvatures(uv[0], uv[1]).or_else(|error| {
333 if let Some(crate::AnalyticSurface::Sphere { frame, radius }) = surface.analytic() {
334 let own = outward_normal(face, uv).map(|n| if face.same_sense { n } else { n.scale(-1.0) });
335 let away = own.is_some_and(|n| n.dot(foot.point.sub(frame.origin)) > 0.0);
336 let k = if away { -1.0 / radius } else { 1.0 / radius };
337 return Ok::<(f64, f64), String>((k, k));
338 }
339 let _ = error;
340 pole_normal(surface, uv).ok_or_else(|| "a degenerate point with no tangent plane".to_string())?;
341 let ([u0, u1], [v0, v1]) = (surface.domain_u()?, surface.domain_v()?);
342 let inward = |at: f64, low: f64, high: f64| at + (0.5 * (low + high) - at) * 1e-6;
343 surface.principal_curvatures(inward(uv[0], u0, u1), inward(uv[1], v0, v1))
344 });
345 let Ok((kappa_min, kappa_max)) = curvatures else { return Ok(None) };
346 let sign = if face.same_sense { -1.0 } else { 1.0 };
350 let (a, b) = (sign * kappa_min, sign * kappa_max);
351 Ok(Some([a.max(b), a.min(b)]))
352 })
353 .collect()
354}
355
356const BOX_EDGE_SAMPLES_PER_SPAN: usize = 8;
359const BOX_EDGE_SAMPLES_MAX: usize = 256;
360const BOX_FACE_SAMPLES_PER_SPAN: usize = 4;
363const BOX_FACE_SAMPLES_MAX: usize = 48;
364const BOX_FACE_SAMPLES_LEAST: usize = 8;
365
366fn span_samples(knots: &[f64], low: f64, high: f64, per: usize, cap: usize, least: usize) -> Vec<f64> {
372 let mut breaks = vec![low];
373 for &knot in knots {
374 if knot > low && knot < high && knot > *breaks.last().unwrap() {
375 breaks.push(knot);
376 }
377 }
378 breaks.push(high);
379 let spans = breaks.len() - 1;
380 if spans * per < least {
381 return (0..=least).map(|i| low + (high - low) * i as f64 / least as f64).collect();
382 }
383 let per = if spans * per > cap { (cap / spans).max(1) } else { per };
384 let mut samples = Vec::with_capacity((breaks.len() - 1) * per + 1);
385 for pair in breaks.windows(2) {
386 for i in 0..per {
387 samples.push(pair[0] + (pair[1] - pair[0]) * i as f64 / per as f64);
388 }
389 }
390 samples.push(high);
391 samples
392}
393
394struct GrowingBox(Option<[Vec3; 2]>);
396
397impl GrowingBox {
398 fn take(&mut self, point: Vec3) {
399 if !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite()) {
400 return;
401 }
402 let [low, high] = self.0.get_or_insert([point, point]);
403 *low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
404 *high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
405 }
406}
407
408fn axis_of(point: Vec3, axis: usize) -> f64 {
409 [point.x, point.y, point.z][axis]
410}
411
412fn golden_peak(f: impl Fn(f64) -> f64, mut a: f64, mut b: f64) -> f64 {
415 const RATIO: f64 = 0.618_033_988_749_894_9;
416 let mut c = b - RATIO * (b - a);
417 let mut d = a + RATIO * (b - a);
418 let (mut fc, mut fd) = (f(c), f(d));
419 for _ in 0..200 {
420 if (b - a).abs() <= 4.0 * f64::EPSILON * (a.abs() + b.abs()).max(f64::MIN_POSITIVE) {
421 break;
422 }
423 if fc >= fd {
424 (b, d, fd) = (d, c, fc);
425 c = b - RATIO * (b - a);
426 fc = f(c);
427 } else {
428 (a, c, fc) = (c, d, fd);
429 d = a + RATIO * (b - a);
430 fd = f(d);
431 }
432 }
433 if fc >= fd { c } else { d }
434}
435
436fn edge_extremes(edge: &crate::topology::EdgeRecord, into: &mut GrowingBox) {
441 let curve = &edge.curve;
442 let (low, high) = (edge.t0.min(edge.t1), edge.t0.max(edge.t1));
443 let ts = span_samples(&curve.knots, low, high, BOX_EDGE_SAMPLES_PER_SPAN, BOX_EDGE_SAMPLES_MAX, BOX_EDGE_SAMPLES_PER_SPAN);
444 let points: Vec<Option<Vec3>> = ts.iter().map(|&t| curve.evaluate(t).ok()).collect();
445 points.iter().flatten().for_each(|&p| into.take(p));
446 for axis in 0..3 {
447 for sign in [1.0, -1.0] {
448 let value = |i: usize| points[i].map(|p| sign * axis_of(p, axis));
449 let last = ts.len().saturating_sub(1);
450 for i in 0..ts.len() {
451 let (before, after) = (i.saturating_sub(1), (i + 1).min(last));
452 let (Some(here), Some(b), Some(a)) = (value(i), value(before), value(after)) else { continue };
453 if here >= b && here >= a && before < after {
454 let f = |t: f64| curve.evaluate(t).map_or(f64::NEG_INFINITY, |p| sign * axis_of(p, axis));
455 let t = golden_peak(f, ts[before], ts[after]);
456 if let Ok(p) = curve.evaluate(t) {
457 into.take(p);
458 }
459 }
460 }
461 }
462 }
463}
464
465fn surface_peak(surface: &crate::NurbsSurface, seed: [f64; 2], axis: usize, sign: f64, domain: [[f64; 2]; 2]) -> Option<[f64; 2]> {
470 let clamp = |uv: [f64; 2]| [uv[0].clamp(domain[0][0], domain[0][1]), uv[1].clamp(domain[1][0], domain[1][1])];
471 let value = |uv: [f64; 2]| surface.evaluate(uv[0], uv[1]).ok().map(|p| sign * axis_of(p, axis));
472 let mut uv = seed;
473 let mut here = value(uv)?;
474 let span = (domain[0][1] - domain[0][0]).abs().max((domain[1][1] - domain[1][0]).abs());
475 for _ in 0..60 {
476 let d = surface.derivatives(uv[0], uv[1], 2).ok()?;
477 let g = [sign * axis_of(d[1][0], axis), sign * axis_of(d[0][1], axis)];
478 let h = [[sign * axis_of(d[2][0], axis), sign * axis_of(d[1][1], axis)], [sign * axis_of(d[1][1], axis), sign * axis_of(d[0][2], axis)]];
479 let scale = g[0].abs().max(g[1].abs()).max(h[0][0].abs()).max(h[1][1].abs()).max(h[0][1].abs());
480 if scale == 0.0 || g[0].abs().max(g[1].abs()) <= 1e-15 * scale {
482 break;
483 }
484 let mean = 0.5 * (h[0][0] + h[1][1]);
487 let largest = mean + (0.25 * (h[0][0] - h[1][1]).powi(2) + h[0][1].powi(2)).sqrt();
488 let mut shift = largest.max(0.0) + 1e-9 * scale;
489 let mut moved = false;
490 for _ in 0..40 {
491 let a = [[h[0][0] - shift, h[0][1]], [h[0][1], h[1][1] - shift]];
492 let det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
493 if det == 0.0 || !det.is_finite() {
494 shift = shift * 4.0 + scale;
495 continue;
496 }
497 let step = [-(a[1][1] * g[0] - a[0][1] * g[1]) / det, -(a[0][0] * g[1] - a[1][0] * g[0]) / det];
498 let next = clamp([uv[0] + step[0], uv[1] + step[1]]);
499 match value(next) {
500 Some(there) if there >= here => {
501 let small = (next[0] - uv[0]).abs().max((next[1] - uv[1]).abs()) <= 1e-15 * span;
502 uv = next;
503 here = there;
504 moved = !small;
505 break;
506 }
507 _ => shift = shift * 4.0 + scale,
508 }
509 }
510 if !moved {
511 break;
512 }
513 }
514 Some(uv)
515}
516
517fn trim_box(face: &FaceRecord, du: [f64; 2], dv: [f64; 2]) -> ([f64; 2], [f64; 2]) {
521 let mut bounds: Option<[f64; 4]> = None;
522 for coedge in face.loops.iter().flat_map(|l| &l.coedges) {
523 for c in &coedge.pcurve.control_points {
524 if c.w == 0.0 {
525 continue;
526 }
527 let (u, v) = (c.x / c.w, c.y / c.w);
528 let b = bounds.get_or_insert([u, u, v, v]);
529 *b = [b[0].min(u), b[1].max(u), b[2].min(v), b[3].max(v)];
530 }
531 }
532 match bounds {
533 Some([u0, u1, v0, v1]) => {
534 let u = [u0.max(du[0]), u1.min(du[1])];
535 let v = [v0.max(dv[0]), v1.min(dv[1])];
536 if u[0] < u[1] && v[0] < v[1] { (u, v) } else { (du, dv) }
537 }
538 None => (du, dv),
539 }
540}
541
542fn face_extremes(face: &FaceRecord, tolerance: f64, into: &mut GrowingBox) -> Result<(), KernelRefusal> {
550 let surface = &face.surface;
551 let (Ok(du), Ok(dv)) = (surface.domain_u(), surface.domain_v()) else { return Ok(()) };
552 let (bu, bv) = trim_box(face, du, dv);
553 let us = span_samples(&surface.knots_u, bu[0], bu[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
554 let vs = span_samples(&surface.knots_v, bv[0], bv[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
555 let mut grid: Vec<Vec<Option<Vec3>>> = vec![vec![None; vs.len()]; us.len()];
556 for (i, &u) in us.iter().enumerate() {
557 for (j, &v) in vs.iter().enumerate() {
558 if trim_class(face, [u, v], tolerance)? != PolygonClass::Outside {
559 grid[i][j] = surface.evaluate(u, v).ok();
560 }
561 }
562 }
563 grid.iter().flatten().flatten().for_each(|&p| into.take(p));
564 for axis in 0..3 {
565 for sign in [1.0, -1.0] {
566 for i in 0..us.len() {
567 for j in 0..vs.len() {
568 let Some(here) = grid[i][j].map(|p| sign * axis_of(p, axis)) else { continue };
569 let mut peak = true;
570 'neighbours: for a in i.saturating_sub(1)..(i + 2).min(us.len()) {
571 for b in j.saturating_sub(1)..(j + 2).min(vs.len()) {
572 if let Some(there) = grid[a][b] {
573 if sign * axis_of(there, axis) > here {
574 peak = false;
575 break 'neighbours;
576 }
577 }
578 }
579 }
580 if !peak {
581 continue;
582 }
583 let Some(uv) = surface_peak(surface, [us[i], vs[j]], axis, sign, [du, dv]) else { continue };
584 if trim_class(face, uv, tolerance)? != PolygonClass::Outside {
585 if let Ok(p) = surface.evaluate(uv[0], uv[1]) {
586 into.take(p);
587 }
588 }
589 }
590 }
591 }
592 }
593 Ok(())
594}
595
596pub fn solid_least_box(solid: &BrepSolid, tolerance: f64) -> Result<[Vec3; 2], KernelRefusal> {
603 let mut boxed = GrowingBox(None);
604 solid.vertices.iter().for_each(|vertex| boxed.take(vertex.point));
605 for edge in solid.edges.iter().filter(|edge| !edge.degenerate) {
606 edge_extremes(edge, &mut boxed);
607 }
608 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
609 face_extremes(face, tolerance, &mut boxed)?;
610 }
611 boxed.0.ok_or_else(|| refusal("least_box_empty", "the solid has no boundary".into()))
612}
613
614fn boundary_distance(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Option<(f64, Option<Vec3>)>, KernelRefusal> {
617 Ok(nearest_boundary_point(solid, point, tolerance)?.map(|foot| {
618 let away = point.sub(foot.point);
619 let length = away.length();
620 (foot.distance, (length > 0.0).then(|| away.scale(1.0 / length)))
621 }))
622}
623
624fn golden_dip(f: impl Fn(f64) -> f64, a: f64, b: f64) -> f64 {
626 golden_peak(|t| -f(t), a, b)
627}
628
629fn surface_dip(face: &FaceRecord, other: &BrepSolid, seed: [f64; 2], domain: [[f64; 2]; 2], tolerance: f64, flat: f64) -> Result<Option<[f64; 2]>, KernelRefusal> {
637 let surface = &face.surface;
638 let clamp = |uv: [f64; 2]| [uv[0].clamp(domain[0][0], domain[0][1]), uv[1].clamp(domain[1][0], domain[1][1])];
639 let span = (domain[0][1] - domain[0][0]).abs().max((domain[1][1] - domain[1][0]).abs());
640 let at = |uv: [f64; 2]| -> Result<Option<(f64, [f64; 2])>, KernelRefusal> {
641 let Ok((p, su, sv)) = surface.deriv1(uv[0], uv[1]) else { return Ok(None) };
642 Ok(boundary_distance(other, p, tolerance)?.map(|(d, n)| (d, n.map_or([0.0, 0.0], |n| [su.dot(n), sv.dot(n)]))))
643 };
644 let mut uv = seed;
645 let Some((mut here, mut g)) = at(uv)? else { return Ok(None) };
646 let h = 1e-6 * span;
647 for _ in 0..40 {
648 if here == 0.0 || g[0].hypot(g[1]) * span <= flat || h == 0.0 {
649 break;
650 }
651 let (Some((_, gu)), Some((_, gv))) = (at(clamp([uv[0] + h, uv[1]]))?, at(clamp([uv[0], uv[1] + h]))?) else { break };
653 let (du, dv) = (clamp([uv[0] + h, uv[1]])[0] - uv[0], clamp([uv[0], uv[1] + h])[1] - uv[1]);
654 if du == 0.0 || dv == 0.0 {
655 break;
656 }
657 let hxx = (gu[0] - g[0]) / du;
658 let hyy = (gv[1] - g[1]) / dv;
659 let hxy = 0.5 * ((gu[1] - g[1]) / du + (gv[0] - g[0]) / dv);
660 let scale = hxx.abs().max(hyy.abs()).max(hxy.abs()).max(g[0].abs()).max(g[1].abs());
661 let mean = 0.5 * (hxx + hyy);
662 let least = mean - (0.25 * (hxx - hyy).powi(2) + hxy * hxy).sqrt();
663 let mut shift = (-least).max(0.0) + 1e-9 * scale;
665 let mut moved = false;
666 for _ in 0..40 {
667 let a = [[hxx + shift, hxy], [hxy, hyy + shift]];
668 let det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
669 if det == 0.0 || !det.is_finite() {
670 shift = shift * 4.0 + scale;
671 continue;
672 }
673 let step = [-(a[1][1] * g[0] - a[0][1] * g[1]) / det, -(a[0][0] * g[1] - a[1][0] * g[0]) / det];
674 let next = clamp([uv[0] + step[0], uv[1] + step[1]]);
675 match at(next)? {
676 Some((there, gn)) if there <= here => {
677 let small = (next[0] - uv[0]).abs().max((next[1] - uv[1]).abs()) <= 1e-15 * span;
678 (uv, here, g) = (next, there, gn);
679 moved = !small;
680 break;
681 }
682 _ => shift = shift * 4.0 + scale,
683 }
684 }
685 if !moved {
686 break;
687 }
688 }
689 Ok(Some(uv))
690}
691
692pub fn solid_gap(a: &BrepSolid, b: &BrepSolid, tolerance: f64) -> Result<f64, KernelRefusal> {
697 let flat = 1e-11 * crate::solid_scale(a).max(crate::solid_scale(b));
698 let there = gap_from(a, b, tolerance, flat)?;
699 if there <= flat {
700 return Ok(there);
701 }
702 Ok(there.min(gap_from(b, a, tolerance, flat)?))
703}
704
705fn gap_from(a: &BrepSolid, b: &BrepSolid, tolerance: f64, flat: f64) -> Result<f64, KernelRefusal> {
715 let mut least = f64::INFINITY;
716 let take = |least: &mut f64, d: Option<(f64, Option<Vec3>)>| {
717 if let Some((d, _)) = d {
718 *least = least.min(d);
719 }
720 };
721 for vertex in &a.vertices {
722 take(&mut least, boundary_distance(b, vertex.point, tolerance)?);
723 }
724 for vertex in &b.vertices {
725 take(&mut least, boundary_distance(a, vertex.point, tolerance)?);
726 }
727 for edge in a.edges.iter().filter(|edge| !edge.degenerate) {
728 if least <= flat {
729 return Ok(least);
730 }
731 let curve = &edge.curve;
732 let (low, high) = (edge.t0.min(edge.t1), edge.t0.max(edge.t1));
733 let ts = span_samples(&curve.knots, low, high, BOX_EDGE_SAMPLES_PER_SPAN, BOX_EDGE_SAMPLES_MAX, BOX_EDGE_SAMPLES_PER_SPAN);
734 let mut values = Vec::with_capacity(ts.len());
735 for &t in &ts {
736 let d = match curve.evaluate(t) {
737 Ok(p) => boundary_distance(b, p, tolerance)?.map(|(d, _)| d),
738 Err(_) => None,
739 };
740 values.push(d);
741 }
742 values.iter().flatten().for_each(|&d| least = least.min(d));
743 let last = ts.len().saturating_sub(1);
744 for i in 0..ts.len() {
745 let (before, after) = (i.saturating_sub(1), (i + 1).min(last));
746 let (Some(here), Some(x), Some(y)) = (values[i], values[before], values[after]) else { continue };
747 if here <= x && here <= y && before < after && here > 0.0 && x.max(y) - here > flat {
748 let f = |t: f64| match curve.evaluate(t) {
749 Ok(p) => nearest_boundary_point(b, p, tolerance).ok().flatten().map_or(f64::INFINITY, |foot| foot.distance),
750 Err(_) => f64::INFINITY,
751 };
752 let t = golden_dip(f, ts[before], ts[after]);
753 least = least.min(f(t));
754 }
755 }
756 }
757 for face in a.shells.iter().flat_map(|shell| &shell.faces) {
758 if least <= flat {
759 return Ok(least);
760 }
761 let surface = &face.surface;
762 let (Ok(du), Ok(dv)) = (surface.domain_u(), surface.domain_v()) else { continue };
763 let (bu, bv) = trim_box(face, du, dv);
764 let us = span_samples(&surface.knots_u, bu[0], bu[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
765 let vs = span_samples(&surface.knots_v, bv[0], bv[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
766 let mut grid: Vec<Vec<Option<f64>>> = vec![vec![None; vs.len()]; us.len()];
767 for (i, &u) in us.iter().enumerate() {
768 for (j, &v) in vs.iter().enumerate() {
769 if trim_class(face, [u, v], tolerance)? == PolygonClass::Outside {
770 continue;
771 }
772 if let Ok(p) = surface.evaluate(u, v) {
773 grid[i][j] = boundary_distance(b, p, tolerance)?.map(|(d, _)| d);
774 }
775 }
776 }
777 grid.iter().flatten().flatten().for_each(|&d| least = least.min(d));
778 for i in 0..us.len() {
779 for j in 0..vs.len() {
780 let Some(here) = grid[i][j] else { continue };
781 if here == 0.0 {
782 continue;
783 }
784 let around: Vec<f64> = (i.saturating_sub(1)..(i + 2).min(us.len()))
785 .flat_map(|x| (j.saturating_sub(1)..(j + 2).min(vs.len())).map(move |y| (x, y)))
786 .filter_map(|(x, y)| grid[x][y])
787 .collect();
788 let dip = around.iter().all(|&there| there >= here) && around.iter().any(|&there| there - here > flat);
789 if !dip {
790 continue;
791 }
792 let Some(uv) = surface_dip(face, b, [us[i], vs[j]], [du, dv], tolerance, flat)? else { continue };
793 if trim_class(face, uv, tolerance)? == PolygonClass::Outside {
794 continue;
795 }
796 if let Ok(p) = surface.evaluate(uv[0], uv[1]) {
797 take(&mut least, boundary_distance(b, p, tolerance)?);
798 }
799 }
800 }
801 }
802 if least.is_finite() { Ok(least) } else { Err(refusal("gap_empty", "a solid has no boundary".into())) }
803}