ferravex_dynamics/
collision.rs

1use crate::{PhysicsError, Shape, math::*};
2
3/// How the first contact of a checked ball sweep was reached.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum SweepHitKind {
6    /// The ball starts strictly inside the target's inflated boundary.
7    InitialOverlap,
8    /// The ball starts exactly on the boundary, regardless of movement direction.
9    InitialTouch,
10    /// The moving ball enters the boundary after the start.
11    Impact,
12    /// The moving ball touches the boundary tangentially after the start.
13    Grazing,
14}
15
16/// First contact of a ball translated over a finite segment.
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct SweepHit<const D: usize> {
19    /// Fraction of the supplied displacement in `[0, 1]`, including both ends.
20    pub fraction: f32,
21    /// Unit normal pointing out of the stationary target toward the moving ball.
22    /// Coincident ball centers use the opposite movement direction, or +X for
23    /// zero movement. Inside boxes use the closest face, with X winning ties.
24    pub normal: [f32; D],
25    pub kind: SweepHitKind,
26}
27
28impl<const D: usize> Shape<D> {
29    /// Sweep a ball against this stationary shape at `center`.
30    ///
31    /// `displacement` is the complete translation, not a direction or velocity.
32    /// Zero movement still reports initial overlap/touch; a separated stationary
33    /// ball returns `Ok(None)`. Initial contacts take precedence over later hits,
34    /// even when moving away. Tangencies and endpoint hits are included. This
35    /// geometric query does not apply the world's sliding/CCD contact policy.
36    ///
37    /// Shapes/radius and all coordinates use the existing world limits: radii
38    /// and half extents in `[1e-5, 1_000_000]`, and center, origin and displacement
39    /// components in `[-1_000_000, 1_000_000]`. Invalid/nonfinite inputs return
40    /// [`PhysicsError::InvalidBody`]; dimensions other than 2/3 return
41    /// [`PhysicsError::InvalidDimension`]. Intermediates use f64, with results
42    /// rounded to f32; this is not an exact-arithmetic predicate.
43    ///
44    /// ```
45    /// use ferravex_dynamics::Shape;
46    /// let wall = Shape::cuboid([1., 1.]);
47    /// let hit = wall.sweep_ball([0., 0.], [-3., 0.], 0.5, [4., 0.])?
48    ///     .unwrap();
49    /// assert_eq!(hit.fraction, 0.375);
50    /// assert_eq!(hit.normal, [-1., 0.]);
51    /// let overlap = wall.sweep_ball([0., 0.], [0., 0.], 0.5, [0., 0.])?
52    ///     .unwrap();
53    /// assert_eq!(overlap.fraction, 0.);
54    /// assert!(wall.sweep_ball([0., 0.], [-3., 0.], 0.5, [0., 0.])?.is_none());
55    /// # Ok::<(), ferravex_dynamics::PhysicsError>(())
56    /// ```
57    pub fn sweep_ball(
58        self,
59        center: [f32; D],
60        origin: [f32; D],
61        radius: f32,
62        displacement: [f32; D],
63    ) -> Result<Option<SweepHit<D>>, PhysicsError> {
64        if D != 2 && D != 3 {
65            return Err(PhysicsError::InvalidDimension);
66        }
67        if !self.valid()
68            || !Shape::<D>::ball(radius).valid()
69            || !valid(center)
70            || !valid(origin)
71            || !valid(displacement)
72        {
73            return Err(PhysicsError::InvalidBody);
74        }
75        let p = relative64(origin, center);
76        let v = displacement.map(f64::from);
77        let hit = match self {
78            Shape::Ball { radius: target } => {
79                trace_ball(p, v, f64::from(radius) + f64::from(target), 1.)
80            }
81            Shape::Box { half_extents } => {
82                trace_ball_box(p, f64::from(radius), v, half_extents.map(f64::from), 1.)
83            }
84        };
85        Ok(hit.map(|hit| SweepHit {
86            fraction: hit.time as f32,
87            normal: hit.normal,
88            kind: hit.kind,
89        }))
90    }
91}
92
93#[derive(Clone, Copy, Debug)]
94pub(crate) struct Manifold<const D: usize> {
95    /// From the first shape toward the second.
96    pub normal: [f32; D],
97    pub penetration: f32,
98}
99
100pub(crate) fn contact<const D: usize>(
101    a: Shape<D>,
102    pa: [f32; D],
103    b: Shape<D>,
104    pb: [f32; D],
105    margin: f32,
106) -> Option<Manifold<D>> {
107    match (a, b) {
108        (Shape::Ball { radius: ra }, Shape::Ball { radius: rb }) => {
109            let delta = sub(pb, pa);
110            let limit = ra + rb + margin;
111            let dist_sq = dot(delta, delta);
112            if dist_sq > limit * limit {
113                return None;
114            }
115            let distance = dist_sq.sqrt();
116            if distance > limit {
117                return None;
118            }
119            Some(Manifold {
120                normal: if distance > 1e-8 {
121                    mul(delta, distance.recip())
122                } else {
123                    unit(0, 1.)
124                },
125                penetration: (ra + rb - distance).max(0.),
126            })
127        }
128        (Shape::Box { half_extents: ha }, Shape::Box { half_extents: hb }) => {
129            let delta = sub(pb, pa);
130            let mut penetration = f32::INFINITY;
131            let mut axis = 0;
132            for i in 0..D {
133                let overlap = ha[i] + hb[i] - delta[i].abs();
134                if overlap < -margin {
135                    return None;
136                }
137                if overlap < penetration {
138                    penetration = overlap;
139                    axis = i;
140                }
141            }
142            Some(Manifold {
143                normal: unit(axis, if delta[axis] >= 0. { 1. } else { -1. }),
144                penetration: penetration.max(0.),
145            })
146        }
147        (Shape::Ball { radius }, Shape::Box { half_extents }) => {
148            ball_box(pa, radius, pb, half_extents, margin)
149        }
150        (Shape::Box { half_extents }, Shape::Ball { radius }) => {
151            ball_box(pb, radius, pa, half_extents, margin).map(|m| Manifold {
152                normal: mul(m.normal, -1.),
153                ..m
154            })
155        }
156    }
157}
158fn ball_box<const D: usize>(
159    p: [f32; D],
160    radius: f32,
161    center: [f32; D],
162    half: [f32; D],
163    margin: f32,
164) -> Option<Manifold<D>> {
165    let local = sub(p, center);
166    let nearest = std::array::from_fn(|i| local[i].clamp(-half[i], half[i]));
167    let toward_box = sub(nearest, local);
168    let limit = radius + margin;
169    let dist_sq = dot(toward_box, toward_box);
170    if dist_sq > limit * limit {
171        return None;
172    }
173    let distance = dist_sq.sqrt();
174    if distance > limit {
175        return None;
176    }
177    if distance > 1e-7 {
178        return Some(Manifold {
179            normal: mul(toward_box, distance.recip()),
180            penetration: (radius - distance).max(0.),
181        });
182    }
183    // A ball whose center is inside the box must exit through the closest face.
184    let axis = (0..D)
185        .min_by(|&a, &b| (half[a] - local[a].abs()).total_cmp(&(half[b] - local[b].abs())))
186        .unwrap();
187    Some(Manifold {
188        normal: unit(axis, if local[axis] >= 0. { -1. } else { 1. }),
189        penetration: radius + half[axis] - local[axis].abs(),
190    })
191}
192
193// Query kernels use f64 before subtracting, squaring or inflating. This also
194// keeps tiny colliders visible from distant origins within the world limits.
195fn relative64<const D: usize>(a: [f32; D], b: [f32; D]) -> [f64; D] {
196    std::array::from_fn(|i| f64::from(a[i]) - f64::from(b[i]))
197}
198fn dot64<const D: usize>(a: [f64; D], b: [f64; D]) -> f64 {
199    a.iter().zip(b).map(|(a, b)| a * b).sum()
200}
201fn normal64<const D: usize>(v: [f64; D]) -> Option<[f32; D]> {
202    let length = dot64(v, v).sqrt();
203    (length > 0.).then(|| v.map(|x| (x / length) as f32))
204}
205fn query_inputs<const D: usize>(
206    origin: [f32; D],
207    direction: [f32; D],
208    center: [f32; D],
209    max: f32,
210) -> bool {
211    (D == 2 || D == 3)
212        && origin
213            .into_iter()
214            .chain(direction)
215            .chain(center)
216            .all(f32::is_finite)
217        && max.is_finite()
218        && max >= 0.
219}
220
221#[derive(Clone, Copy, Debug)]
222struct TraceHit<const D: usize> {
223    time: f64,
224    normal: [f32; D],
225    kind: SweepHitKind,
226    penetration: f64,
227}
228
229// Unlike b*b - a*c, the closest-point form does not lose the radius squared
230// when a small sphere is far down the ray. Work with the actual direction
231// length: normalizing an f32 vector does not make its squared length exactly 1.
232fn trace_ball<const D: usize>(
233    p: [f64; D],
234    v: [f64; D],
235    radius: f64,
236    max: f64,
237) -> Option<TraceHit<D>> {
238    let distance = dot64(p, p).sqrt();
239    if distance <= radius {
240        return Some(TraceHit {
241            time: 0.,
242            normal: normal64(p)
243                .or_else(|| normal64(v.map(|x| -x)))
244                .unwrap_or_else(|| unit(0, 1.)),
245            kind: if distance < radius {
246                SweepHitKind::InitialOverlap
247            } else {
248                SweepHitKind::InitialTouch
249            },
250            penetration: radius - distance,
251        });
252    }
253    let a = dot64(v, v);
254    let b = dot64(p, v);
255    if a == 0. || b >= 0. {
256        return None;
257    }
258    let closest_time = -b / a;
259    let closest: [f64; D] = std::array::from_fn(|i| v[i].mul_add(closest_time, p[i]));
260    let height_squared = radius * radius - dot64(closest, closest);
261    if height_squared < 0. {
262        return None;
263    }
264    let offset = (height_squared / a).sqrt();
265    // The product form of c preserves very short entry distances, while the
266    // closest-point normal avoids cancellation at far-away small colliders.
267    let c = (distance - radius) * (distance + radius);
268    let time = if offset > closest_time * 0.5 {
269        c / (-b + (a * height_squared).sqrt())
270    } else {
271        closest_time - offset
272    };
273    if time > max {
274        return None;
275    }
276    let outward = std::array::from_fn(|i| (-v[i]).mul_add(offset, closest[i]));
277    Some(TraceHit {
278        time,
279        normal: normal64(outward)
280            .or_else(|| normal64(v.map(|x| -x)))
281            .unwrap_or_else(|| unit(0, 1.)),
282        kind: if height_squared == 0. {
283            SweepHitKind::Grazing
284        } else {
285            SweepHitKind::Impact
286        },
287        penetration: 0.,
288    })
289}
290
291/// Ray parameter measured in world units because callers normalize direction.
292pub(crate) fn ray_ball<const D: usize>(
293    origin: [f32; D],
294    direction: [f32; D],
295    center: [f32; D],
296    radius: f32,
297    max: f32,
298) -> Option<(f32, [f32; D])> {
299    if !query_inputs(origin, direction, center, max) || !radius.is_finite() || radius < 0. {
300        return None;
301    }
302    trace_ball(
303        relative64(origin, center),
304        direction.map(f64::from),
305        f64::from(radius),
306        f64::from(max),
307    )
308    .map(|hit| (hit.time as f32, hit.normal))
309}
310
311fn trace_box<const D: usize>(
312    p: [f64; D],
313    v: [f64; D],
314    half: [f64; D],
315    max: f64,
316) -> Option<(f64, [f32; D])> {
317    let mut enter: f64 = 0.;
318    let mut exit = max;
319    let mut normal = normal64(v.map(|x| -x)).unwrap_or_else(|| unit(0, 1.));
320    for i in 0..D {
321        // A tiny nonzero component can cross a slab over a long segment.
322        if v[i] == 0. {
323            if p[i].abs() > half[i] {
324                return None;
325            }
326            continue;
327        }
328        let t1 = (-half[i] - p[i]) / v[i];
329        let t2 = (half[i] - p[i]) / v[i];
330        let near = t1.min(t2);
331        if near > enter {
332            enter = near;
333            normal = unit(i, -v[i].signum() as f32);
334        }
335        exit = exit.min(t1.max(t2));
336        if enter > exit {
337            return None;
338        }
339    }
340    Some((enter, normal))
341}
342
343pub(crate) fn ray_box<const D: usize>(
344    origin: [f32; D],
345    direction: [f32; D],
346    center: [f32; D],
347    half: [f32; D],
348    max: f32,
349) -> Option<(f32, [f32; D])> {
350    if !query_inputs(origin, direction, center, max)
351        || half.iter().any(|h| !h.is_finite() || *h < 0.)
352    {
353        return None;
354    }
355    trace_box(
356        relative64(origin, center),
357        direction.map(f64::from),
358        half.map(f64::from),
359        f64::from(max),
360    )
361    .map(|(time, normal)| (time as f32, normal))
362}
363
364// Each AABB feature contributes a face, edge-cylinder or corner-sphere root.
365// At most 26 features are examined in 3D, eight in 2D. All storage is on-stack.
366fn trace_ball_box<const D: usize>(
367    p: [f64; D],
368    radius: f64,
369    v: [f64; D],
370    half: [f64; D],
371    max: f64,
372) -> Option<TraceHit<D>> {
373    trace_box(p, v, half.map(|h| h + radius), max)?;
374    let outward = std::array::from_fn(|i| p[i] - p[i].clamp(-half[i], half[i]));
375    let distance = dot64(outward, outward).sqrt();
376    if distance <= radius {
377        let (normal, penetration) = if distance > 0. {
378            (normal64(outward).unwrap(), radius - distance)
379        } else {
380            let axis = (0..D)
381                .min_by(|&a, &b| (half[a] - p[a].abs()).total_cmp(&(half[b] - p[b].abs())))
382                .unwrap();
383            (
384                unit(axis, if p[axis] >= 0. { 1. } else { -1. }),
385                radius + half[axis] - p[axis].abs(),
386            )
387        };
388        return Some(TraceHit {
389            time: 0.,
390            normal,
391            kind: if penetration > 0. {
392                SweepHitKind::InitialOverlap
393            } else {
394                SweepHitKind::InitialTouch
395            },
396            penetration,
397        });
398    }
399    let mut best = max;
400    let mut result = None;
401    for axes in 1..(1_usize << D) {
402        for signs in 0..(1_usize << D) {
403            if signs & !axes != 0 {
404                continue;
405            }
406            let mut q = [0.; D];
407            let mut projected = [0.; D];
408            for i in 0..D {
409                if axes & (1 << i) != 0 {
410                    let sign = if signs & (1 << i) != 0 { 1. } else { -1. };
411                    q[i] = p[i] - sign * half[i];
412                    projected[i] = v[i];
413                }
414            }
415            let Some(hit) = trace_ball(q, projected, radius, best) else {
416                continue;
417            };
418            // Starting inside the projected feature does not mean starting
419            // inside its bounded face/edge. Adjacent features cover its entry.
420            if matches!(
421                hit.kind,
422                SweepHitKind::InitialOverlap | SweepHitKind::InitialTouch
423            ) {
424                continue;
425            }
426            let within = (0..D).all(|i| {
427                if axes & (1 << i) != 0 {
428                    let sign = if signs & (1 << i) != 0 { 1. } else { -1. };
429                    f64::from(hit.normal[i]) * sign >= 0.
430                } else {
431                    v[i].mul_add(hit.time, p[i]).abs() <= half[i]
432                }
433            });
434            if within {
435                best = hit.time;
436                result = Some(hit);
437            }
438        }
439    }
440    result
441}
442
443/// Exact sphere/circle sweep against an AABB, including rounded corners/edges.
444/// Retains the solver policy: tangencies and departing surface contacts do not
445/// block motion; overlaps deeper than the existing 1e-5 slop do.
446pub(crate) fn sweep_ball_box<const D: usize>(
447    origin: [f32; D],
448    radius: f32,
449    direction: [f32; D],
450    center: [f32; D],
451    half: [f32; D],
452    max: f32,
453) -> Option<(f32, [f32; D])> {
454    if !query_inputs(origin, direction, center, max)
455        || !radius.is_finite()
456        || radius <= 0.
457        || half.iter().any(|h| !h.is_finite() || *h < 0.)
458    {
459        return None;
460    }
461    let hit = trace_ball_box(
462        relative64(origin, center),
463        f64::from(radius),
464        direction.map(f64::from),
465        half.map(f64::from),
466        f64::from(max),
467    )?;
468    let into = dot(direction, hit.normal);
469    let blocking = match hit.kind {
470        SweepHitKind::InitialOverlap => hit.penetration > 1e-5 || into < -1e-6,
471        SweepHitKind::InitialTouch | SweepHitKind::Impact => into < -1e-7,
472        SweepHitKind::Grazing => false,
473    };
474    blocking.then_some((hit.time as f32, hit.normal))
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    fn assert_hit<const D: usize>(hit: SweepHit<D>, fraction: f32, kind: SweepHitKind) {
482        assert!((hit.fraction - fraction).abs() <= 1e-6, "{hit:?}");
483        assert_eq!(hit.kind, kind);
484        assert!(hit.normal.iter().all(|n| n.is_finite()), "{hit:?}");
485        assert!((dot(hit.normal, hit.normal) - 1.).abs() < 1e-6, "{hit:?}");
486    }
487
488    #[test]
489    fn stationary_sweeps_distinguish_separation_overlap_and_touch() {
490        for shape in [Shape::ball(1.), Shape::cuboid([1.; 2])] {
491            assert_eq!(shape.sweep_ball([0.; 2], [-3., 0.], 0.5, [0.; 2]), Ok(None));
492            let overlap = shape
493                .sweep_ball([0.; 2], [0.; 2], 0.5, [0.; 2])
494                .unwrap()
495                .unwrap();
496            assert_hit(overlap, 0., SweepHitKind::InitialOverlap);
497            assert_eq!(overlap.normal, [1., 0.]);
498            let touch = shape
499                .sweep_ball([0.; 2], [-1.5, 0.], 0.5, [0.; 2])
500                .unwrap()
501                .unwrap();
502            assert_hit(touch, 0., SweepHitKind::InitialTouch);
503            assert_eq!(touch.normal, [-1., 0.]);
504        }
505    }
506
507    #[test]
508    fn initial_contacts_take_precedence_for_inward_outward_and_tangent_motion() {
509        for shape in [Shape::ball(1.), Shape::cuboid([1.; 3])] {
510            for motion in [[4., 0., 0.], [-4., 0., 0.], [0., 4., 0.]] {
511                let touch = shape
512                    .sweep_ball([0.; 3], [-1.5, 0., 0.], 0.5, motion)
513                    .unwrap()
514                    .unwrap();
515                assert_hit(touch, 0., SweepHitKind::InitialTouch);
516                let overlap = shape
517                    .sweep_ball([0.; 3], [-1.25, 0., 0.], 0.5, motion)
518                    .unwrap()
519                    .unwrap();
520                assert_hit(overlap, 0., SweepHitKind::InitialOverlap);
521            }
522        }
523    }
524
525    #[test]
526    fn checked_sweeps_include_endpoint_impacts_and_exclude_short_segments() {
527        for shape in [Shape::ball(1.), Shape::cuboid([1.; 2])] {
528            let hit = shape
529                .sweep_ball([0.; 2], [-3., 0.], 0.5, [1.5, 0.])
530                .unwrap()
531                .unwrap();
532            assert_hit(hit, 1., SweepHitKind::Impact);
533            assert_eq!(hit.normal, [-1., 0.]);
534            let short = f32::from_bits(1.5_f32.to_bits() - 1);
535            assert_eq!(
536                shape.sweep_ball([0.; 2], [-3., 0.], 0.5, [short, 0.]),
537                Ok(None)
538            );
539        }
540    }
541
542    #[test]
543    fn grazing_is_reported_without_turning_near_misses_into_hits() {
544        for (shape, y, fraction) in [
545            (Shape::ball(1.), 1.5, 0.75),
546            (Shape::cuboid([1.; 2]), 1.5, 0.5),
547        ] {
548            let hit = shape
549                .sweep_ball([0.; 2], [-3., y], 0.5, [4., 0.])
550                .unwrap()
551                .unwrap();
552            assert_hit(hit, fraction, SweepHitKind::Grazing);
553            assert_eq!(hit.normal, [0., 1.]);
554            let beyond = f32::from_bits(y.to_bits() + 1);
555            assert_eq!(
556                shape.sweep_ball([0.; 2], [-3., beyond], 0.5, [4., 0.]),
557                Ok(None)
558            );
559            let inside = f32::from_bits(y.to_bits() - 1);
560            let hit = shape
561                .sweep_ball([0.; 2], [-3., inside], 0.5, [4., 0.])
562                .unwrap()
563                .unwrap();
564            assert_eq!(hit.kind, SweepHitKind::Impact);
565            assert!(hit.normal[0] < 0.);
566        }
567    }
568
569    #[test]
570    fn three_dimensional_rounded_edge_and_corner_grazing() {
571        let shape = Shape::cuboid([1.; 3]);
572        for (origin, radius, expected_normal) in [
573            ([-3., 1.5, 0.], 0.5, [0., 1., 0.]),
574            ([-3., 1.375, 1.5], 0.625, [0., 0.6, 0.8]),
575        ] {
576            let hit = shape
577                .sweep_ball([0.; 3], origin, radius, [4., 0., 0.])
578                .unwrap()
579                .unwrap();
580            assert_hit(hit, 0.5, SweepHitKind::Grazing);
581            assert_eq!(hit.normal, expected_normal);
582        }
583    }
584
585    #[test]
586    fn rounded_corner_is_not_an_expanded_box() {
587        assert_eq!(
588            Shape::cuboid([1.; 2]).sweep_ball([0.; 2], [-1.45, 1.45], 0.5, [0.1, 0.]),
589            Ok(None)
590        );
591        let hit = Shape::cuboid([1.; 3])
592            .sweep_ball([0.; 3], [-3., 1.2, 1.2], 0.5, [4., 0., 0.])
593            .unwrap()
594            .unwrap();
595        assert_hit(hit, (2. - 0.17_f32.sqrt()) / 4., SweepHitKind::Impact);
596        assert!((hit.normal[1] - 0.4).abs() < 1e-6);
597        assert!((hit.normal[2] - 0.4).abs() < 1e-6);
598    }
599
600    #[test]
601    fn distant_small_ball_has_no_spurious_tangency_or_lost_radius() {
602        let (distance, normal) =
603            ray_ball([-1_000_000., 0.], [1., 0.], [0.; 2], 0.5, 1_000_000.).unwrap();
604        assert_eq!(distance, 999_999.5);
605        assert_eq!(normal, [-1., 0.]);
606        assert!(ray_ball([-1_000_000., 1.], [1., 0.], [0.; 2], 0.5, 1_000_000.).is_none());
607        for shape in [Shape::ball(1e-5), Shape::cuboid([1e-5; 2])] {
608            let hit = shape
609                .sweep_ball([0.; 2], [-1_000_000., 0.], 1e-5, [1_000_000., 0.])
610                .unwrap()
611                .unwrap();
612            assert_hit(hit, 1., SweepHitKind::Impact);
613            assert_eq!(hit.normal, [-1., 0.]);
614            assert_eq!(
615                shape.sweep_ball([0.; 2], [-1_000_000., 0.001], 1e-5, [1_000_000., 0.]),
616                Ok(None)
617            );
618        }
619    }
620
621    #[test]
622    fn shallow_ray_and_sweep_components_are_not_treated_as_zero() {
623        let (_, normal) = ray_box([-2., 0.], [1e-9, 0.], [0.; 2], [1.; 2], 2e9).unwrap();
624        assert_eq!(normal, [-1., 0.]);
625        // Both the tiny component and the total segment are within world limits.
626        let hit = Shape::cuboid([1e-5, 1_000_000.])
627            .sweep_ball([0.; 2], [-0.001, -500_000.], 1e-5, [0.002, 1_000_000.])
628            .unwrap()
629            .unwrap();
630        assert_hit(hit, 0.49, SweepHitKind::Impact);
631        assert_eq!(hit.normal, [-1., 0.]);
632    }
633
634    #[test]
635    fn tiny_positive_gaps_are_not_rounded_into_initial_overlap() {
636        let origin = f32::from_bits(1.5_f32.to_bits() + 1);
637        for shape in [Shape::ball(1.), Shape::cuboid([1.; 2])] {
638            let hit = shape
639                .sweep_ball([0.; 2], [-origin, 0.], 0.5, [1., 0.])
640                .unwrap()
641                .unwrap();
642            assert_hit(hit, origin - 1.5, SweepHitKind::Impact);
643            assert!(hit.fraction > 0.);
644        }
645    }
646
647    #[test]
648    fn invalid_checked_inputs_report_errors_instead_of_misses() {
649        let shape = Shape::cuboid([1.; 2]);
650        for bad in [
651            f32::NAN,
652            f32::INFINITY,
653            f32::NEG_INFINITY,
654            f32::MAX,
655            -f32::MAX,
656        ] {
657            assert_eq!(
658                shape.sweep_ball([bad, 0.], [0.; 2], 0.5, [0.; 2]),
659                Err(PhysicsError::InvalidBody)
660            );
661            assert_eq!(
662                shape.sweep_ball([0.; 2], [bad, 0.], 0.5, [0.; 2]),
663                Err(PhysicsError::InvalidBody)
664            );
665            assert_eq!(
666                shape.sweep_ball([0.; 2], [0.; 2], 0.5, [bad, 0.]),
667                Err(PhysicsError::InvalidBody)
668            );
669            assert_eq!(
670                shape.sweep_ball([0.; 2], [0.; 2], bad, [0.; 2]),
671                Err(PhysicsError::InvalidBody)
672            );
673            assert_eq!(
674                Shape::ball(bad).sweep_ball([0.; 2], [0.; 2], 0.5, [0.; 2]),
675                Err(PhysicsError::InvalidBody)
676            );
677            assert_eq!(
678                Shape::cuboid([bad, 1.]).sweep_ball([0.; 2], [0.; 2], 0.5, [0.; 2]),
679                Err(PhysicsError::InvalidBody)
680            );
681        }
682        for radius in [0., -1., 1e-6] {
683            assert_eq!(
684                shape.sweep_ball([0.; 2], [0.; 2], radius, [0.; 2]),
685                Err(PhysicsError::InvalidBody)
686            );
687        }
688        assert_eq!(
689            Shape::<0>::ball(1.).sweep_ball([], [], 0.5, []),
690            Err(PhysicsError::InvalidDimension)
691        );
692        assert_eq!(
693            Shape::<4>::ball(1.).sweep_ball([0.; 4], [0.; 4], 0.5, [0.; 4]),
694            Err(PhysicsError::InvalidDimension)
695        );
696    }
697
698    #[test]
699    fn unchecked_kernels_reject_nonfinite_input_and_invalid_dimensions() {
700        assert!(ray_ball([f32::NAN, 0.], [1., 0.], [0.; 2], 1., 1.).is_none());
701        assert!(ray_box([0.; 2], [f32::INFINITY, 0.], [0.; 2], [1.; 2], 1.).is_none());
702        assert!(sweep_ball_box([0.; 2], 1., [1., 0.], [0.; 2], [-1.; 2], 1.).is_none());
703        assert!(ray_ball::<0>([], [], [], 1., 1.).is_none());
704        assert!(sweep_ball_box::<4>([0.; 4], 1., [0.; 4], [0.; 4], [1.; 4], 1.).is_none());
705        for max in [-1., f32::NAN, f32::INFINITY] {
706            assert!(ray_ball([0.; 2], [1., 0.], [0.; 2], 1., max).is_none());
707            assert!(ray_box([0.; 2], [1., 0.], [0.; 2], [1.; 2], max).is_none());
708            assert!(sweep_ball_box([0.; 2], 1., [1., 0.], [0.; 2], [1.; 2], max).is_none());
709        }
710    }
711
712    #[test]
713    fn finite_extreme_kernel_inputs_never_overflow_the_hit() {
714        let largest = f32::MAX;
715        let (distance, normal) =
716            ray_ball([-largest, 0.], [1., 0.], [largest, 0.], largest, largest).unwrap();
717        assert_eq!(distance, largest);
718        assert_eq!(normal, [-1., 0.]);
719        let (distance, normal) = ray_box(
720            [-largest, 0.],
721            [1., 0.],
722            [largest, 0.],
723            [largest; 2],
724            largest,
725        )
726        .unwrap();
727        assert_eq!(distance, largest);
728        assert_eq!(normal, [-1., 0.]);
729        let (distance, normal) = sweep_ball_box(
730            [-largest, 0.],
731            largest,
732            [1., 0.],
733            [largest, 0.],
734            [largest; 2],
735            largest,
736        )
737        .unwrap();
738        assert_eq!(distance, 0.);
739        assert_eq!(normal, [-1., 0.]);
740    }
741
742    #[test]
743    fn legacy_solver_sweep_retains_sliding_and_overlap_policy() {
744        for direction in [[-1., 0.], [0., 1.], [0.; 2]] {
745            assert!(sweep_ball_box([-1.5, 0.], 0.5, direction, [0.; 2], [1.; 2], 3.).is_none());
746            assert_eq!(
747                sweep_ball_box([-1.25, 0.], 0.5, direction, [0.; 2], [1.; 2], 3.),
748                Some((0., [-1., 0.]))
749            );
750        }
751        assert_eq!(
752            sweep_ball_box([-1.5, 0.], 0.5, [1., 0.], [0.; 2], [1.; 2], 0.),
753            Some((0., [-1., 0.]))
754        );
755        assert!(sweep_ball_box([-3., 1.5], 0.5, [1., 0.], [0.; 2], [1.; 2], 4.).is_none());
756        let shallow = -1.5 + 1e-6;
757        assert!(sweep_ball_box([shallow, 0.], 0.5, [-1., 0.], [0.; 2], [1.; 2], 3.).is_none());
758        assert_eq!(
759            sweep_ball_box([shallow, 0.], 0.5, [1., 0.], [0.; 2], [1.; 2], 3.),
760            Some((0., [-1., 0.]))
761        );
762    }
763
764    #[test]
765    fn discrete_contact_normal_and_penetration_conventions_are_unchanged() {
766        let ball = Shape::ball(0.5);
767        let cube = Shape::cuboid([1.; 2]);
768        let a = contact(ball, [0.; 2], cube, [0.; 2], 0.).unwrap();
769        let b = contact(cube, [0.; 2], ball, [0.; 2], 0.).unwrap();
770        assert_eq!(a.normal, [-1., 0.]);
771        assert_eq!(b.normal, [1., 0.]);
772        assert_eq!(a.penetration, 1.5);
773        assert_eq!(b.penetration, 1.5);
774        assert!(contact(ball, [-1.6, 0.], cube, [0.; 2], 0.).is_none());
775    }
776}