1use crate::curve::interior_knot_count;
2use crate::{project_point_to_surface, NurbsCurve, NurbsSurface, Vec3};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6
7use crate::spatial::Aabb as Bounds;
8
9
10fn surface_bounds(surface: &NurbsSurface) -> Result<Bounds, String> {
15 let mut bounds = Bounds::from_points([]);
16 for point in surface.control_points.iter().flatten() {
17 let point = point.point()?;
18 bounds.minimum.x = bounds.minimum.x.min(point.x);
19 bounds.minimum.y = bounds.minimum.y.min(point.y);
20 bounds.minimum.z = bounds.minimum.z.min(point.z);
21 bounds.maximum.x = bounds.maximum.x.max(point.x);
22 bounds.maximum.y = bounds.maximum.y.max(point.y);
23 bounds.maximum.z = bounds.maximum.z.max(point.z);
24 }
25 Ok(bounds)
26}
27
28
29fn span_bounds(surface: &NurbsSurface) -> Result<Vec<Bounds>, String> {
40 let (p, q) = (surface.degree_u, surface.degree_v);
41 let rows = surface.control_points.len();
42 let columns = surface.control_points.first().map_or(0, Vec::len);
43 let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
44 (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
45 };
46 let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
47 if spans_u.is_empty() || spans_v.is_empty() {
49 return Ok(vec![surface_bounds(surface)?]);
50 }
51 let mut boxes = Vec::with_capacity(spans_u.len() * spans_v.len());
52 for &i in &spans_u {
53 for &j in &spans_v {
54 let mut bounds = Bounds::from_points([]);
55 for row in &surface.control_points[i - p..=i] {
56 for control in &row[j - q..=j] {
57 let point = control.point()?;
58 bounds.minimum.x = bounds.minimum.x.min(point.x);
59 bounds.minimum.y = bounds.minimum.y.min(point.y);
60 bounds.minimum.z = bounds.minimum.z.min(point.z);
61 bounds.maximum.x = bounds.maximum.x.max(point.x);
62 bounds.maximum.y = bounds.maximum.y.max(point.y);
63 bounds.maximum.z = bounds.maximum.z.max(point.z);
64 }
65 }
66 boxes.push(bounds);
67 }
68 }
69 Ok(boxes)
70}
71
72fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
73 crate::projection::fit_parameter(value, minimum, maximum, closed)
74}
75
76fn solve_three(matrix: [[f64; 3]; 3], rhs: Vec3) -> Option<[f64; 3]> {
77 let a = matrix;
78 let determinant = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
79 - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
80 + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
81 let scale: f64 = a.iter().flatten().map(|value| value.abs()).sum();
82 if determinant.abs() <= 1e-14 * scale.max(1.0).powi(3) {
83 return None;
84 }
85 let x = (rhs.x * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
86 - a[0][1] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
87 + a[0][2] * (rhs.y * a[2][1] - a[1][1] * rhs.z))
88 / determinant;
89 let y = (a[0][0] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
90 - rhs.x * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
91 + a[0][2] * (a[1][0] * rhs.z - rhs.y * a[2][0]))
92 / determinant;
93 let z = (a[0][0] * (a[1][1] * rhs.z - rhs.y * a[2][1])
94 - a[0][1] * (a[1][0] * rhs.z - rhs.y * a[2][0])
95 + rhs.x * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
96 / determinant;
97 Some([x, y, z])
98}
99
100pub fn newton_local_start_enabled() -> bool {
109 switch!("BREP_CS_NEWTON_LOCAL_START", true)
110}
111
112fn newton_local_start_check() -> bool {
117 switch!("BREP_CS_NEWTON_LOCAL_START_CHECK", false)
118}
119
120static START_CHECK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
121static START_CHECK_FEET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
122static START_CHECK_FOOT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
123static START_CHECK_HIT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
124
125pub fn newton_start_check_counts() -> (u64, u64, u64, u64) {
128 use std::sync::atomic::Ordering::Relaxed;
129 (
130 START_CHECK_CALLS.load(Relaxed),
131 START_CHECK_FEET.load(Relaxed),
132 START_CHECK_FOOT_DISAGREEMENTS.load(Relaxed),
133 START_CHECK_HIT_DISAGREEMENTS.load(Relaxed),
134 )
135}
136
137fn opening_foot(surface: &NurbsSurface, point: Vec3, local: bool, check: bool) -> Result<[f64; 2], String> {
141 if !local {
142 let projection = project_point_to_surface(surface, point)?;
143 return Ok([projection.u, projection.v]);
144 }
145 let projection = crate::projection::project_point_to_surface_local(surface, point)?;
146 if check {
147 use std::sync::atomic::Ordering::Relaxed;
148 START_CHECK_FEET.fetch_add(1, Relaxed);
149 let nearest = project_point_to_surface(surface, point)?;
150 let apart = projection.point.sub(nearest.point).length();
151 if apart > crate::tolerance::DEFAULT_MODEL {
152 START_CHECK_FOOT_DISAGREEMENTS.fetch_add(1, Relaxed);
153 eprintln!(
154 "cs newton start check: foot apart {apart:.3e} (local {:.3e} at ({:.9},{:.9}), nearest {:.3e} at ({:.9},{:.9}))",
155 projection.distance, projection.u, projection.v, nearest.distance, nearest.u, nearest.v
156 );
157 }
158 }
159 Ok([projection.u, projection.v])
160}
161
162fn newton_curve_surface(
163 curve: &NurbsCurve,
164 surface: &NurbsSurface,
165 seed: f64,
166 local_start: bool,
167 check: bool,
168) -> Result<[f64; 3], String> {
169 let [t0, t1] = curve.domain()?;
170 let [u0, u1] = surface.domain_u()?;
171 let [v0, v1] = surface.domain_v()?;
172 let (closed_u, closed_v) = surface.closed_directions()?;
173 let mut t = seed;
174 let [mut u, mut v] = opening_foot(surface, curve.evaluate(t)?, local_start, check)?;
175 for _ in 0..60 {
176 let (curve_point, tangent) = curve.deriv1(t)?;
177 let (surface_point, du, dv) = surface.deriv1(u, v)?;
178 let residual = curve_point.sub(surface_point);
179 if residual.length() <= EPSILON {
180 return Ok([t, u, v]);
181 }
182 let Some([mut step_t, mut step_u, mut step_v]) = solve_three(
183 [
184 [tangent.x, -du.x, -dv.x],
185 [tangent.y, -du.y, -dv.y],
186 [tangent.z, -du.z, -dv.z],
187 ],
188 residual.scale(-1.0),
189 ) else {
190 if tangent.length_squared() <= EPSILON {
191 return Ok([t, u, v]);
192 }
193 let next_t = (t - residual.dot(tangent) / tangent.length_squared()).clamp(t0, t1);
194 if (next_t - t).abs() <= 1e-15 * (t1 - t0) {
195 return Ok([t, u, v]);
196 }
197 t = next_t;
198 let projection =
202 crate::projection::project_point_to_surface_from_seed(surface, curve.evaluate(t)?, [u, v])?;
203 u = projection.u;
204 v = projection.v;
205 continue;
206 };
207 step_t = step_t.clamp(-(t1 - t0) / 4.0, (t1 - t0) / 4.0);
208 step_u = step_u.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
209 step_v = step_v.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
210 let next_t = (t + step_t).clamp(t0, t1);
211 let next_u = fit_parameter(u + step_u, u0, u1, closed_u);
212 let next_v = fit_parameter(v + step_v, v0, v1, closed_v);
213 let stalled = (next_t - t).abs() <= 1e-15 * (t1 - t0)
214 && (next_u - u).abs() <= 1e-15 * (u1 - u0)
215 && (next_v - v).abs() <= 1e-15 * (v1 - v0);
216 t = next_t;
217 u = next_u;
218 v = next_v;
219 if stalled {
220 return Ok([t, u, v]);
221 }
222 }
223 Ok([t, u, v])
224}
225
226#[derive(Clone, Copy, Debug, Serialize)]
227pub struct CurveSurfaceIntersection {
228 pub t: f64,
229 pub u: f64,
230 pub v: f64,
231 pub point: Vec3,
232 pub gap: f64,
233 pub tangential: bool,
234}
235
236fn duplicate_cap_enabled() -> bool {
240 switch!("BREP_CS_DUPLICATE_CAP", true)
241}
242
243pub fn intersect_curve_surface(
244 curve: &NurbsCurve,
245 surface: &NurbsSurface,
246 tolerance: f64,
247) -> Result<Vec<CurveSurfaceIntersection>, String> {
248 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
249 let seeds = sampled_seeds(curve, surface, tolerance)?;
250 intersect_curve_surface_from_seeds(curve, surface, tolerance, seeds)
251}
252
253fn sampled_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64) -> Result<Vec<f64>, String> {
256 let [t0, t1] = curve.domain()?;
257 let surface_box = surface_bounds(surface)?.expanded(tolerance * 10.0);
258 let sample_count =
259 32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
260 let mut samples = Vec::with_capacity(sample_count + 1);
261 for index in 0..=sample_count {
262 let t = t0 + (t1 - t0) * index as f64 / sample_count as f64;
263 samples.push((t, curve.evaluate(t)?));
264 }
265 let span_boxes = span_bounds(surface)?;
266 let mut seeds = Vec::new();
267 for pair in samples.windows(2) {
268 let segment_box = Bounds::from_points([pair[0].1, pair[1].1]).expanded(tolerance * 10.0);
269 if segment_box.intersects_exact(surface_box)
270 && span_boxes.iter().any(|span_box| segment_box.intersects_exact(span_box.expanded(tolerance * 10.0)))
271 {
272 seeds.push((pair[0].0 + pair[1].0) * 0.5);
273 }
274 }
275 Ok(seeds)
276}
277
278pub fn intersect_curve_surface_from_seeds(
284 curve: &NurbsCurve,
285 surface: &NurbsSurface,
286 tolerance: f64,
287 seeds: Vec<f64>,
288) -> Result<Vec<CurveSurfaceIntersection>, String> {
289 solve_counted(curve, surface, tolerance, &seeds, false)
290}
291
292pub fn intersect_ray_surface(
300 curve: &NurbsCurve,
301 surface: &NurbsSurface,
302 tolerance: f64,
303) -> Result<Vec<CurveSurfaceIntersection>, String> {
304 let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
305 let seeds = sampled_seeds(curve, surface, tolerance)?;
306 solve_counted(curve, surface, tolerance, &seeds, true)
307}
308
309fn solve_counted(
310 curve: &NurbsCurve,
311 surface: &NurbsSurface,
312 tolerance: f64,
313 seeds: &[f64],
314 ray: bool,
315) -> Result<Vec<CurveSurfaceIntersection>, String> {
316 if !ray || !newton_local_start_enabled() {
317 return solve_from_seeds(curve, surface, tolerance, seeds, false, false);
318 }
319 if !newton_local_start_check() {
320 return solve_from_seeds(curve, surface, tolerance, seeds, true, false);
321 }
322 let local = solve_from_seeds(curve, surface, tolerance, seeds, true, true)?;
323 let global = solve_from_seeds(curve, surface, tolerance, seeds, false, false)?;
324 START_CHECK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
325 if !same_hits(&local, &global, tolerance) {
326 START_CHECK_HIT_DISAGREEMENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
327 let read = |hits: &[CurveSurfaceIntersection]| hits.iter().map(|hit| hit.t).collect::<Vec<_>>();
328 eprintln!(
329 "cs newton start check: hits differ: local t {:?} global t {:?}",
330 read(&local),
331 read(&global)
332 );
333 }
334 Ok(local)
335}
336
337fn same_hits(first: &[CurveSurfaceIntersection], second: &[CurveSurfaceIntersection], tolerance: f64) -> bool {
340 first.len() == second.len()
341 && first.iter().zip(second).all(|(a, b)| {
342 a.point.sub(b.point).length() <= tolerance * 10.0 && a.tangential == b.tangential
343 })
344}
345
346fn solve_from_seeds(
347 curve: &NurbsCurve,
348 surface: &NurbsSurface,
349 tolerance: f64,
350 seeds: &[f64],
351 local_start: bool,
352 check: bool,
353) -> Result<Vec<CurveSurfaceIntersection>, String> {
354 let [t0, t1] = curve.domain()?;
355 let mut results: Vec<CurveSurfaceIntersection> = Vec::new();
356 for &seed in seeds {
357 let [t, u, v] = newton_curve_surface(curve, surface, seed, local_start, check)?;
358 let on_curve = curve.evaluate(t)?;
359 let on_surface = surface.evaluate(u, v)?;
360 let gap = on_curve.sub(on_surface).length();
361 if gap > tolerance {
362 continue;
363 }
364 let tangent = curve.deriv1(t)?.1;
365 let uncapped = ((tolerance / tangent.length().max(EPSILON)) * 10.0).max((t1 - t0) * 1e-9);
388 let capped = uncapped.min((t1 - t0) * 1e-6);
389 let parameter_tolerance = if duplicate_cap_enabled() { capped } else { uncapped };
390 if let Some(result) = results.iter().find(|result| {
391 (result.t - t).abs() <= parameter_tolerance
392 || result.point.sub(on_curve).length() <= tolerance * 10.0
393 }) {
394 let chord = result.point.sub(on_curve).length();
401 let gap = (result.t - t).abs();
402 if chord > tolerance * 10.0
403 && gap > capped
404 && std::env::var("BREP_DEBUG_CS_DUPLICATE").is_ok()
405 {
406 eprintln!(
407 "cs-duplicate: dropped t={t:.12} against t={:.12} gap={gap:.6e} ptol={parameter_tolerance:.6e} \
408 chord={chord:.6e} |tangent|={:.6e} domain=[{t0:.6},{t1:.6}] tolerance={tolerance:.3e}",
409 result.t,
410 tangent.length(),
411 );
412 }
413 continue;
414 }
415 let normal = surface.normal(u, v).ok();
416 let tangential = normal
417 .and_then(|normal| {
418 tangent
419 .normalized()
420 .ok()
421 .map(|unit| normal.dot(unit).abs() <= 1e-3)
422 })
423 .unwrap_or(false);
424 results.push(CurveSurfaceIntersection {
425 t,
426 u,
427 v,
428 point: on_curve.add(on_surface).scale(0.5),
429 gap,
430 tangential,
431 });
432 }
433 results.sort_by(|a, b| a.t.total_cmp(&b.t));
434 Ok(results)
435}
436