Skip to main content

brepkit_math/nurbs/intersection/
ray.rs

1//! Every crossing of a ray with a NURBS surface.
2
3use crate::frame::Frame3;
4use crate::madd::Madd;
5use crate::nurbs::decompose::surface_to_bezier_patches;
6use crate::nurbs::surface::NurbsSurface;
7use crate::vec::{Point3, Vec3};
8
9/// Deepest subdivision of one Bezier patch.
10const MAX_DEPTH: u32 = 48;
11
12/// Most patches one ray may visit before it is reported as grazing.
13const MAX_VISITS: usize = 20_000;
14
15/// A leaf's size against the surface's: below it, Newton from the leaf's
16/// middle finds the crossing the leaf holds.
17const LEAF: f64 = 1e-3;
18
19/// The least slant a hit is read at, however flat the surface.
20const GRAZE_COS: f64 = 1e-9;
21
22/// How many leaves apart a hit's second crossing may lie and still share a
23/// leaf's Newton with it.
24const SEPARATION: f64 = 4.0;
25
26/// A NURBS surface made ready for ray crossings.
27///
28/// It holds the surface's Bezier patches, each a grid of homogeneous control
29/// points. A surface whose weights are all positive lies in the hull of each
30/// patch's control points, which the search relies on to pass over the
31/// patches a ray misses.
32#[derive(Debug, Clone)]
33pub struct RaySurface {
34    surface: NurbsSurface,
35    patches: Vec<Patch>,
36    scale: f64,
37}
38
39#[derive(Debug, Clone)]
40struct Patch {
41    rows: usize,
42    cols: usize,
43    /// `rows` rows of `cols` homogeneous points `[w x, w y, w z, w]`, a row
44    /// per `u` index.
45    pts: Vec<[f64; 4]>,
46    u: (f64, f64),
47    v: (f64, f64),
48}
49
50/// Where a ray meets a surface.
51#[derive(Debug, Clone, Copy)]
52pub struct RayHit {
53    /// The surface's `u` there.
54    pub u: f64,
55    /// The surface's `v` there.
56    pub v: f64,
57    /// The distance along the ray's unit direction.
58    pub t: f64,
59    /// The point.
60    pub point: Point3,
61}
62
63/// A ray's hits on a surface, and whether any of them, or a place the ray
64/// passes, is too near tangent for the count of hits to be trusted.
65#[derive(Debug, Clone, Default)]
66pub struct RayHits {
67    /// The hits, each once.
68    pub hits: Vec<RayHit>,
69    /// The ray touches the surface tangentially, runs in it, or passes
70    /// within the reach of it without a crossing that settles.
71    pub grazed: bool,
72}
73
74impl Patch {
75    fn point(&self, i: usize, j: usize) -> Point3 {
76        let [x, y, z, w] = self.pts[i * self.cols + j];
77        Point3::new(x / w, y / w, z / w)
78    }
79
80    /// The patch split at the middle of its `u` range (`along_u`) or its
81    /// `v` range, by de Casteljau on the homogeneous points.
82    fn split(&self, along_u: bool) -> (Self, Self) {
83        let (n, m) = if along_u {
84            (self.rows, self.cols)
85        } else {
86            (self.cols, self.rows)
87        };
88        let at = |k: usize, l: usize| {
89            if along_u {
90                k * self.cols + l
91            } else {
92                l * self.cols + k
93            }
94        };
95        let mut low = self.pts.clone();
96        let mut high = self.pts.clone();
97        let mut work = vec![[0.0; 4]; n];
98        for l in 0..m {
99            for (k, slot) in work.iter_mut().enumerate() {
100                *slot = self.pts[at(k, l)];
101            }
102            low[at(0, l)] = work[0];
103            high[at(n - 1, l)] = work[n - 1];
104            for r in 1..n {
105                for k in 0..n - r {
106                    for c in 0..4 {
107                        work[k][c] = 0.5 * (work[k][c] + work[k + 1][c]);
108                    }
109                }
110                low[at(r, l)] = work[0];
111                high[at(n - 1 - r, l)] = work[n - 1 - r];
112            }
113        }
114        let (mut a, mut b) = (self.clone(), self.clone());
115        a.pts = low;
116        b.pts = high;
117        if along_u {
118            let mid = f64::midpoint(self.u.0, self.u.1);
119            (a.u, b.u) = ((self.u.0, mid), (mid, self.u.1));
120        } else {
121            let mid = f64::midpoint(self.v.0, self.v.1);
122            (a.v, b.v) = ((self.v.0, mid), (mid, self.v.1));
123        }
124        (a, b)
125    }
126
127    /// The longest control polygon along `u` and along `v`: each bounds the
128    /// length of the patch's curves that way, however far a bulge between
129    /// its ends rises.
130    fn spans(&self) -> (f64, f64) {
131        let mut along_u = 0.0_f64;
132        for j in 0..self.cols {
133            let length: f64 = (1..self.rows)
134                .map(|i| (self.point(i, j) - self.point(i - 1, j)).length())
135                .sum();
136            along_u = along_u.max(length);
137        }
138        let mut along_v = 0.0_f64;
139        for i in 0..self.rows {
140            let length: f64 = (1..self.cols)
141                .map(|j| (self.point(i, j) - self.point(i, j - 1)).length())
142                .sum();
143            along_v = along_v.max(length);
144        }
145        (along_u, along_v)
146    }
147}
148
149impl RaySurface {
150    /// `surface` made ready, or `None` when a weight is not positive, a knot
151    /// vector is not clamped, or the surface cannot be cut into Bezier
152    /// patches.
153    #[must_use]
154    pub fn new(surface: &NurbsSurface) -> Option<Self> {
155        // An unclamped knot vector's end spans are not Bezier patches of the
156        // surface as decomposed, so the search would cross a different one.
157        let clamped = |knots: &[f64], degree: usize| {
158            let n = knots.len();
159            n > 2 * degree + 1
160                && knots[..=degree]
161                    .iter()
162                    .all(|&k| (k - knots[0]).abs() <= 0.0)
163                && knots[n - degree - 1..]
164                    .iter()
165                    .all(|&k| (k - knots[n - 1]).abs() <= 0.0)
166        };
167        if surface
168            .weights()
169            .iter()
170            .flatten()
171            .any(|&w| !w.is_finite() || w <= 0.0)
172            || !clamped(surface.knots_u(), surface.degree_u())
173            || !clamped(surface.knots_v(), surface.degree_v())
174        {
175            return None;
176        }
177        let patches = surface_to_bezier_patches(surface)
178            .ok()?
179            .into_iter()
180            .map(|p| {
181                let cps = p.surface.control_points();
182                let ws = p.surface.weights();
183                let rows = cps.len();
184                let cols = cps.first().map_or(0, Vec::len);
185                let pts = cps
186                    .iter()
187                    .zip(ws)
188                    .flat_map(|(row, wrow)| {
189                        row.iter()
190                            .zip(wrow)
191                            .map(|(c, &w)| [c.x() * w, c.y() * w, c.z() * w, w])
192                    })
193                    .collect();
194                Patch {
195                    rows,
196                    cols,
197                    pts,
198                    u: p.u_range,
199                    v: p.v_range,
200                }
201            })
202            .filter(|p| p.rows > 0 && p.cols > 0)
203            .collect();
204        let b = surface.aabb();
205        let scale = (b.max - b.min).length().max(1e-9);
206        Some(Self {
207            surface: surface.clone(),
208            patches,
209            scale,
210        })
211    }
212
213    /// The surface.
214    #[must_use]
215    pub const fn surface(&self) -> &NurbsSurface {
216        &self.surface
217    }
218
219    /// Every point where the line through `origin` along `dir` meets the
220    /// surface no farther than `reach` behind `origin`, with `t` measured
221    /// along `dir` made unit. A hit within `reach` of another is the same
222    /// hit.
223    #[must_use]
224    pub fn hits(&self, origin: Point3, dir: Vec3, reach: f64) -> RayHits {
225        let mut out = RayHits::default();
226        // How near another hit must lie to each hit to be it: a hit settled
227        // on its parameters' spacing is known no closer than that.
228        let mut radii: Vec<f64> = Vec::new();
229        out = self.collect_hits(origin, dir, reach, (out, &mut radii));
230        coalesce(&mut out.hits, &radii);
231        out
232    }
233
234    /// Every hit [`Self::hits`] finds, before those of one crossing are
235    /// joined, each with its radius in `radii`.
236    fn collect_hits(
237        &self,
238        origin: Point3,
239        dir: Vec3,
240        reach: f64,
241        (mut out, radii): (RayHits, &mut Vec<f64>),
242    ) -> RayHits {
243        let Ok(frame) = Frame3::from_normal(origin, dir) else {
244            out.grazed = true;
245            return out;
246        };
247        let leaf = LEAF * self.scale;
248        let mut stack: Vec<(Patch, u32)> = self.patches.iter().map(|p| (p.clone(), 0)).collect();
249        let mut visits = 0_usize;
250        while let Some((patch, depth)) = stack.pop() {
251            visits += 1;
252            if visits > MAX_VISITS {
253                out.grazed = true;
254                return out;
255            }
256            let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
257            for i in 0..patch.rows {
258                for j in 0..patch.cols {
259                    let d = patch.point(i, j) - origin;
260                    for (k, x) in [frame.x.dot(d), frame.y.dot(d), frame.z.dot(d)]
261                        .into_iter()
262                        .enumerate()
263                    {
264                        lo[k] = lo[k].min(x);
265                        hi[k] = hi[k].max(x);
266                    }
267                }
268            }
269            if lo[0] > reach || hi[0] < -reach || lo[1] > reach || hi[1] < -reach || hi[2] < -reach
270            {
271                continue;
272            }
273            let (along_u, along_v) = patch.spans();
274            if along_u.max(along_v) <= leaf || depth >= MAX_DEPTH {
275                // A leaf the solve cannot settle is cut further, and at the
276                // deepest level the ray is taken to graze it.
277                if self.solve(&patch, origin, frame.z, reach, (&mut out, radii)) {
278                    continue;
279                }
280                if depth >= MAX_DEPTH {
281                    out.grazed = true;
282                    continue;
283                }
284            }
285            let (a, b) = patch.split(along_u >= along_v);
286            stack.push((a, depth + 1));
287            stack.push((b, depth + 1));
288        }
289        out
290    }
291
292    /// Whether a ray along `dir` through the surface at `(u, v)` meets it
293    /// again too near to be found apart: bending by its normal curvature
294    /// `k` along the ray's tangential part `w`, the surface comes back to
295    /// the ray `2 (n . dir) / (k |w|^2)` along it. A ray at a tangent point
296    /// meets it there twice.
297    fn second_crossing_near(&self, u: f64, v: f64, dir: Vec3) -> bool {
298        let d = self.surface.derivatives(u, v, 2);
299        let (su, sv) = (d[1][0], d[0][1]);
300        let Ok(n) = su.cross(sv).normalize() else {
301            return true;
302        };
303        let slant = n.dot(dir);
304        if slant.abs() <= GRAZE_COS {
305            return true;
306        }
307        let w = dir - n * slant;
308        let (guu, guv, gvv) = (su.dot(su), su.dot(sv), sv.dot(sv));
309        let det = guu.madd(gvv, -guv * guv);
310        if det <= 0.0 || w.length() <= GRAZE_COS {
311            return false;
312        }
313        let (wu, wv) = (su.dot(w), sv.dot(w));
314        let a = gvv.madd(wu, -guv * wv) / det;
315        let b = guu.madd(wv, -guv * wu) / det;
316        let bend = n.dot(d[2][0] * (a * a) + d[1][1] * (2.0 * a * b) + d[0][2] * (b * b));
317        2.0 * slant.abs() <= SEPARATION * LEAF * self.scale * bend.abs()
318    }
319
320    /// Newton on `S(u, v) = origin + t dir` from the middle of `leaf`,
321    /// recording the hit when it lands in the leaf. Whether it converged,
322    /// in the leaf or out of it: a stall (the ray along the tangent plane
323    /// at a step) or no convergence leaves the leaf unsettled.
324    ///
325    /// Where the surface runs fast in its parameters, a unit in the last
326    /// place of `u` or `v` moves the point farther than 1e-12 of the
327    /// surface's size, and Newton stalls short of that. A hit it stalls on
328    /// within four such units is settled there, after Newton has run its
329    /// course; it is one hit with any other that near, and when that is
330    /// farther than `reach` the ray is flagged, its count in doubt.
331    fn solve(
332        &self,
333        leaf: &Patch,
334        origin: Point3,
335        dir: Vec3,
336        reach: f64,
337        (out, radii): (&mut RayHits, &mut Vec<f64>),
338    ) -> bool {
339        let (mut u, mut v) = (
340            f64::midpoint(leaf.u.0, leaf.u.1),
341            f64::midpoint(leaf.v.0, leaf.v.1),
342        );
343        let (du, dv) = (self.surface.domain_u(), self.surface.domain_v());
344        let mut t = dir.dot(self.surface.evaluate(u, v) - origin);
345        let mut stalled = None;
346        for _ in 0..32 {
347            let d = self.surface.first_derivatives(u, v);
348            let (s, su, sv) = (d.0, d.1, d.2);
349            let f = s - Vec3::new(origin.x(), origin.y(), origin.z()) - dir * t;
350            if f.length() <= 1e-12 * self.scale {
351                return self.record(leaf, (u, v, t), origin, dir, reach, reach, (out, radii));
352            }
353            let spacing = 4.0 * f64::EPSILON * su.length().madd(u.abs(), sv.length() * v.abs());
354            stalled = (f.length() <= spacing).then_some((u, v, t, spacing));
355            let normal = su.cross(sv);
356            let det = -normal.dot(dir);
357            if det.abs() <= 1e-300 {
358                break;
359            }
360            // Cramer's rule on [su sv -dir] x = -f.
361            let neg_dir = -dir;
362            let rhs = -f;
363            let x_u = rhs.cross(sv).dot(neg_dir) / det;
364            let x_v = su.cross(rhs).dot(neg_dir) / det;
365            let x_t = normal.dot(rhs) / det;
366            u = (u + x_u).clamp(du.0, du.1);
367            v = (v + x_v).clamp(dv.0, dv.1);
368            t += x_t;
369        }
370        let Some((u, v, t, spacing)) = stalled else {
371            return false;
372        };
373        out.grazed |= spacing > reach;
374        self.record(
375            leaf,
376            (u, v, t),
377            origin,
378            dir,
379            reach,
380            spacing.max(reach),
381            (out, radii),
382        )
383    }
384
385    /// Record the hit at `(u, v)`, `t` along the ray, when it lies in `leaf`
386    /// and ahead of `origin` by no less than `-reach`, with `merge` in
387    /// `radii`: the distance within which another hit is the same one.
388    /// Always settles the leaf.
389    #[allow(clippy::too_many_arguments)]
390    fn record(
391        &self,
392        leaf: &Patch,
393        (u, v, t): (f64, f64, f64),
394        origin: Point3,
395        dir: Vec3,
396        reach: f64,
397        merge: f64,
398        (out, radii): (&mut RayHits, &mut Vec<f64>),
399    ) -> bool {
400        let (du, dv) = (self.surface.domain_u(), self.surface.domain_v());
401        let slack_u = 1e-9 * (du.1 - du.0);
402        let slack_v = 1e-9 * (dv.1 - dv.0);
403        if u < leaf.u.0 - slack_u
404            || u > leaf.u.1 + slack_u
405            || v < leaf.v.0 - slack_v
406            || v > leaf.v.1 + slack_v
407            || t < -reach
408        {
409            return true;
410        }
411        out.grazed |= self.second_crossing_near(u, v, dir);
412        let point = origin + dir * t;
413        out.hits.push(RayHit { u, v, t, point });
414        radii.push(merge);
415        true
416    }
417}
418
419/// Join the hits of one crossing: two lie on one when they lie within the
420/// wider of their radii, and so does any chain of such pairs. A chain does
421/// not hang on the order the hits were found in, so neither does the count.
422/// Each crossing keeps its most precise hit, the nearest along the ray among
423/// those as precise, and the hits are left in order along the ray.
424///
425/// Every hit lies on the ray, `t` along it, so two lie `|t - t'|` apart.
426/// Taken in order of `t`, a hit joins the last crossing when it lies within
427/// the farthest that crossing's hits reach, or its own radius reaches back to
428/// that crossing's last hit, and its radius can reach on back to join the
429/// crossings before it into one. A crossing before the last whose own reach
430/// takes the hit in would have taken the last one in already.
431fn coalesce(hits: &mut Vec<RayHit>, radii: &[f64]) {
432    /// A crossing's hits so far: the last along the ray, the one whose radius
433    /// reaches farthest past it, and the most precise.
434    struct Crossing {
435        last: f64,
436        reacher: (f64, f64),
437        best: usize,
438    }
439    // Separations are taken between `t`s and set against radii, never as
440    // sums: at `t` = 1e10 a unit in the last place is 1.9e-6, and `t + r`
441    // would round a radius of 1e-6 away. A hit at `(t, r)` reaches past one
442    // at `(s, q)` when `t - s` exceeds `q - r`.
443    let farther = |a: (f64, f64), b: (f64, f64)| a.0 - b.0 > b.1 - a.1;
444    let mut order: Vec<usize> = (0..hits.len()).collect();
445    order.sort_by(|&a, &b| hits[a].t.total_cmp(&hits[b].t));
446    let precise = |a: usize, b: usize| {
447        radii[a]
448            .total_cmp(&radii[b])
449            .then(hits[a].t.total_cmp(&hits[b].t))
450            .is_lt()
451    };
452    let mut crossings: Vec<Crossing> = Vec::new();
453    for i in order {
454        let (t, r) = (hits[i].t, radii[i]);
455        match crossings.last_mut() {
456            Some(c) if t - c.reacher.0 <= c.reacher.1 || t - c.last <= r => {
457                c.last = t;
458                if farther((t, r), c.reacher) {
459                    c.reacher = (t, r);
460                }
461                if precise(i, c.best) {
462                    c.best = i;
463                }
464            }
465            _ => crossings.push(Crossing {
466                last: t,
467                reacher: (t, r),
468                best: i,
469            }),
470        }
471        while crossings.len() >= 2 && t - crossings[crossings.len() - 2].last <= r {
472            let Some(later) = crossings.pop() else { break };
473            if let Some(c) = crossings.last_mut() {
474                c.last = later.last;
475                if farther(later.reacher, c.reacher) {
476                    c.reacher = later.reacher;
477                }
478                if precise(later.best, c.best) {
479                    c.best = later.best;
480                }
481            }
482        }
483    }
484    *hits = crossings.into_iter().map(|c| hits[c.best]).collect();
485}
486
487#[cfg(test)]
488mod tests {
489    #![allow(clippy::unwrap_used)]
490
491    use super::*;
492
493    /// The lid `z = 100 u (1 - u)^4 v (1 - v)` over the unit square, flat
494    /// along its rim and peaking at 2.048 at `(0.2, 0.5)`.
495    fn lid() -> NurbsSurface {
496        let rows = (0..6)
497            .map(|i| {
498                (0..3)
499                    .map(|j| {
500                        let z = if (i, j) == (1, 1) { 10.0 } else { 0.0 };
501                        Point3::new(f64::from(i) / 5.0, f64::from(j) / 2.0, z)
502                    })
503                    .collect()
504            })
505            .collect();
506        NurbsSurface::new(
507            5,
508            2,
509            [vec![0.0; 6], vec![1.0; 6]].concat(),
510            vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
511            rows,
512            vec![vec![1.0; 3]; 6],
513        )
514        .unwrap()
515    }
516
517    #[test]
518    fn a_ray_up_through_the_lids_peak_meets_it_there() {
519        let lid = RaySurface::new(&lid()).unwrap();
520        let up = Vec3::new(0.0, 0.0, 1.0);
521        let at_peak = lid.hits(Point3::new(0.2, 0.5, -1.0), up, 1e-9);
522        assert!(!at_peak.grazed);
523        assert_eq!(at_peak.hits.len(), 1);
524        assert!((at_peak.hits[0].point.z() - 2.048).abs() < 1e-12);
525        assert!((at_peak.hits[0].t - 3.048).abs() < 1e-12);
526        assert!((at_peak.hits[0].u - 0.2).abs() < 1e-9 && (at_peak.hits[0].v - 0.5).abs() < 1e-9);
527
528        let beside = lid.hits(Point3::new(1.5, 0.5, -1.0), up, 1e-9);
529        assert!(beside.hits.is_empty() && !beside.grazed);
530        let behind = lid.hits(Point3::new(0.2, 0.5, 3.0), up, 1e-9);
531        assert!(behind.hits.is_empty());
532    }
533
534    /// A level ray at `z = 1.5` along `u` through `v = 0.5` crosses the
535    /// lid's bulge twice, where `100 u (1 - u)^4 / 4 = 1.5`.
536    #[test]
537    fn a_level_ray_crosses_the_bulge_twice() {
538        let lid = RaySurface::new(&lid()).unwrap();
539        let across = lid.hits(Point3::new(-1.0, 0.5, 1.5), Vec3::new(1.0, 0.0, 0.0), 1e-9);
540        assert!(!across.grazed);
541        assert_eq!(across.hits.len(), 2, "{:?}", across.hits);
542        for h in &across.hits {
543            let u = h.point.x();
544            assert!((25.0 * u * (1.0 - u).powi(4) - 1.5).abs() < 1e-9, "{h:?}");
545        }
546    }
547
548    #[test]
549    fn a_ray_touching_the_peak_grazes() {
550        let lid = RaySurface::new(&lid()).unwrap();
551        let level = lid.hits(
552            Point3::new(-1.0, 0.5, 2.048),
553            Vec3::new(1.0, 0.0, 0.0),
554            1e-9,
555        );
556        assert!(level.grazed, "{level:?}");
557    }
558
559    /// A unit biquadratic patch with only its middle control point raised,
560    /// to 4000: a level ray at 500 along u through v = 0.5 crosses its
561    /// spike twice, where 4000 u (1 - u) = 500 at v = 0.5, so at
562    /// u = (1 ± 1/√2) / 2.
563    #[test]
564    fn a_level_ray_crosses_a_tall_spike() {
565        let rows = (0..3)
566            .map(|i| {
567                (0..3)
568                    .map(|j| {
569                        let z = if (i, j) == (1, 1) { 4000.0 } else { 0.0 };
570                        Point3::new(f64::from(i) / 2.0, f64::from(j) / 2.0, z)
571                    })
572                    .collect()
573            })
574            .collect();
575        let knots = vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0];
576        let spike =
577            NurbsSurface::new(2, 2, knots.clone(), knots, rows, vec![vec![1.0; 3]; 3]).unwrap();
578        let ray = RaySurface::new(&spike).unwrap();
579        let across = ray.hits(
580            Point3::new(-1.0, 0.5, 500.0),
581            Vec3::new(1.0, 0.0, 0.0),
582            1e-9,
583        );
584        assert!(!across.grazed);
585        let mut xs: Vec<f64> = across.hits.iter().map(|h| h.point.x()).collect();
586        xs.sort_by(f64::total_cmp);
587        let root = std::f64::consts::FRAC_1_SQRT_2;
588        assert_eq!(xs.len(), 2, "{xs:?}");
589        assert!((xs[0] - (1.0 - root) / 2.0).abs() < 1e-9, "{xs:?}");
590        assert!((xs[1] - f64::midpoint(1.0, root)).abs() < 1e-9, "{xs:?}");
591    }
592
593    /// The saddle `(u, v, (u - 1/2)(v - 1/2))` over the unit square, beside
594    /// a span reaching to `x = 2000` that makes the whole saddle one leaf.
595    /// A level ray from its middle at height 0.04 along `(1, 1, 0)` crosses
596    /// it at `(0.7, 0.7)`, though at the leaf's middle the ray runs along
597    /// the tangent plane and a solve from there stalls.
598    #[test]
599    fn a_ray_level_with_a_saddles_middle_crosses_it() {
600        let p = Point3::new;
601        let rows = vec![
602            vec![p(0.0, 0.0, 0.25), p(0.0, 1.0, -0.25)],
603            vec![p(1.0, 0.0, -0.25), p(1.0, 1.0, 0.25)],
604            vec![p(2000.0, 0.0, 0.0), p(2000.0, 1.0, 0.0)],
605        ];
606        let s = NurbsSurface::new(
607            1,
608            1,
609            vec![0.0, 0.0, 1.0, 2.0, 2.0],
610            vec![0.0, 0.0, 1.0, 1.0],
611            rows,
612            vec![vec![1.0; 2]; 3],
613        )
614        .unwrap();
615        let ray = RaySurface::new(&s).unwrap();
616        let dir = Vec3::new(1.0, 1.0, 0.0).normalize().unwrap();
617        let found = ray.hits(p(0.5, 0.5, 0.04), dir, 1e-9);
618        assert_eq!(found.hits.len(), 1, "{:?}", found.grazed);
619        assert!((found.hits[0].point - p(0.7, 0.7, 0.04)).length() < 1e-9);
620    }
621
622    /// A surface whose `u` knots run `[-2, -1, 0, 1, 2, 3]`, unclamped, is
623    /// not taken: its end patches as decomposed are not the surface.
624    #[test]
625    fn an_unclamped_surface_is_not_ready() {
626        let rows = (0..3)
627            .map(|i| {
628                (0..2)
629                    .map(|j| Point3::new(0.5 * f64::from(i), f64::from(j), 0.0))
630                    .collect()
631            })
632            .collect();
633        let s = NurbsSurface::new(
634            2,
635            1,
636            vec![-2.0, -1.0, 0.0, 1.0, 2.0, 3.0],
637            vec![0.0, 0.0, 1.0, 1.0],
638            rows,
639            vec![vec![1.0; 2]; 3],
640        )
641        .unwrap();
642        assert!(RaySurface::new(&s).is_none());
643    }
644
645    #[test]
646    fn a_surface_with_a_negative_weight_is_not_ready() {
647        let mut weights = vec![vec![1.0; 3]; 6];
648        weights[2][1] = -1.0;
649        let s = lid();
650        let s = NurbsSurface::new(
651            5,
652            2,
653            s.knots_u().to_vec(),
654            s.knots_v().to_vec(),
655            s.control_points().to_vec(),
656            weights,
657        )
658        .unwrap();
659        assert!(RaySurface::new(&s).is_none());
660    }
661
662    /// A flat unit patch crossed slant: one hit over [0, 1] in each
663    /// parameter, over [0, 1e-12], and over [2^40, 2^40 + 1], each through
664    /// its middle, where every leaf of its subdivision has a corner. Over
665    /// [2^40, 2^40 + 1] a unit in the last place of a parameter is 2^-12:
666    /// the middle lies on that grid, but (0.50003, 0.50007) does not, and
667    /// its hit, settled no finer, is flagged.
668    #[test]
669    fn a_patch_on_a_tiny_or_far_knot_domain_is_crossed_once() {
670        let p = Point3::new;
671        let corners = vec![
672            vec![p(0.0, 0.0, 0.0), p(0.0, 1.0, 0.0)],
673            vec![p(1.0, 0.0, 0.0), p(1.0, 1.0, 0.0)],
674        ];
675        let dir = Vec3::new(0.3, 0.2, -1.0);
676        let far = 2.0_f64.powi(40);
677        let middle = p(0.5, 0.5, 0.0);
678        for (lo, hi, through, flagged) in [
679            (0.0, 1.0, middle, false),
680            (0.0, 1e-12, middle, false),
681            (far, far + 1.0, middle, false),
682            (far, far + 1.0, p(0.500_03, 0.500_07, 0.0), true),
683        ] {
684            let knots = vec![lo, lo, hi, hi];
685            let s = NurbsSurface::new(
686                1,
687                1,
688                knots.clone(),
689                knots,
690                corners.clone(),
691                vec![vec![1.0; 2]; 2],
692            )
693            .unwrap();
694            let found = RaySurface::new(&s).unwrap().hits(through - dir, dir, 1e-6);
695            let case = format!("knots {lo} to {hi} through {through:?}");
696            assert_eq!(found.hits.len(), 1, "{case}: {:?}", found.hits);
697            assert_eq!(found.grazed, flagged, "{case}");
698        }
699    }
700
701    /// Three hits along a ray at 1, 1.0001 and 1.0002, the middle one
702    /// settled on a spacing of 1e-3 and the others found to 1e-6, are one
703    /// crossing in every order they are found in, and so are three a wide
704    /// radius chains from the last hit back past the middle one. Two hits
705    /// 1.9e-6 apart at 1e10 along the ray, each found to 1e-6, are two.
706    #[test]
707    fn hits_merge_on_the_wider_radius_in_any_order() {
708        let p = Point3::new;
709        let knots = vec![0.0, 0.0, 1.0, 1.0];
710        let flat = NurbsSurface::new(
711            1,
712            1,
713            knots.clone(),
714            knots,
715            vec![
716                vec![p(0.0, 0.0, 0.0), p(0.0, 1.0, 0.0)],
717                vec![p(1.0, 0.0, 0.0), p(1.0, 1.0, 0.0)],
718            ],
719            vec![vec![1.0; 2]; 2],
720        )
721        .unwrap();
722        let ray = RaySurface::new(&flat).unwrap();
723        let leaf = ray.patches[0].clone();
724        let (origin, dir) = (p(0.5, 0.5, 1.0), Vec3::new(0.0, 0.0, -1.0));
725        // The middle hit reaches both others; and a hit at 1.0021, reaching
726        // back 3e-3, joins one at 1 reaching 1e-3 with one at 1.002 that
727        // neither reaches.
728        let chains = [
729            [
730                ((0.5, 0.5, 1.0), 1e-6),
731                ((0.5, 0.5, 1.0001), 1e-3),
732                ((0.5, 0.5, 1.0002), 1e-6),
733            ],
734            [
735                ((0.5, 0.5, 1.0), 1e-3),
736                ((0.5, 0.5, 1.002), 1e-6),
737                ((0.5, 0.5, 1.0021), 3e-3),
738            ],
739        ];
740        let orders = [
741            [0, 1, 2],
742            [0, 2, 1],
743            [1, 0, 2],
744            [1, 2, 0],
745            [2, 0, 1],
746            [2, 1, 0],
747        ];
748        // Far along the ray a unit in the last place of `t` is 1.9e-6: two hits
749        // that far apart, each found to 1e-6, are two crossings.
750        let far = 1e10_f64;
751        let next = f64::from_bits(far.to_bits() + 1);
752        for order in [[0, 1], [1, 0]] {
753            let (mut out, mut radii) = (RayHits::default(), Vec::new());
754            for k in order {
755                let t = [far, next][k];
756                assert!(ray.record(
757                    &leaf,
758                    (0.5, 0.5, t),
759                    origin,
760                    dir,
761                    1e-6,
762                    1e-6,
763                    (&mut out, &mut radii)
764                ));
765            }
766            coalesce(&mut out.hits, &radii);
767            assert_eq!(out.hits.len(), 2, "far along the ray in {order:?}");
768        }
769        for found in chains {
770            for order in orders {
771                let (mut out, mut radii) = (RayHits::default(), Vec::new());
772                for k in order {
773                    let (hit, merge) = found[k];
774                    assert!(ray.record(
775                        &leaf,
776                        hit,
777                        origin,
778                        dir,
779                        1e-6,
780                        merge,
781                        (&mut out, &mut radii)
782                    ));
783                }
784                coalesce(&mut out.hits, &radii);
785                assert_eq!(out.hits.len(), 1, "{found:?} in {order:?}: {:?}", out.hits);
786            }
787        }
788    }
789}