ferravex_play/camera/
collision.rs

1use super::{CameraError, bounded};
2use ferravex_math::{Quat, Vec3};
3pub const MAX_BLOCKERS: usize = 4096;
4/// A sphere-center segment. Equal endpoints perform a stationary overlap check.
5/// Use [`Sweep::new`] to check inputs, or [`Sweep::probe`] to also check adapter
6/// results and obtain distances and a padded placement.
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub struct Sweep {
9    pub start: Vec3,
10    pub end: Vec3,
11    pub radius: f32,
12}
13impl Sweep {
14    /// Construct a checked probe with finite endpoints in `[-1e6, 1e6]` on
15    /// each axis and a finite radius in `0.001..=1000`.
16    ///
17    /// Invalid inputs return [`CameraError::InvalidQuery`]. Zero-length
18    /// segments are valid and must still be sent to the collision query.
19    ///
20    /// ```
21    /// use ferravex_math::Vec3;
22    /// use ferravex_play::camera::{CameraError, Sweep};
23    /// let point = Sweep::new(Vec3::ZERO, Vec3::ZERO, 0.25)?;
24    /// assert!(point.valid());
25    /// assert_eq!(Sweep::new(Vec3::ZERO, Vec3::Z, 0.),
26    ///            Err(CameraError::InvalidQuery));
27    /// # Ok::<(), CameraError>(())
28    /// ```
29    pub fn new(start: Vec3, end: Vec3, radius: f32) -> Result<Self, CameraError> {
30        let sweep = Self { start, end, radius };
31        if sweep.valid() {
32            Ok(sweep)
33        } else {
34            Err(CameraError::InvalidQuery)
35        }
36    }
37
38    pub fn valid(self) -> bool {
39        bounded(self.start)
40            && bounded(self.end)
41            && self.radius.is_finite()
42            && (0.001..=1000.).contains(&self.radius)
43    }
44
45    /// Run exactly one query and report travel available before the first hit.
46    ///
47    /// `padding` is a finite distance in `0..=10`, matching camera obstruction
48    /// settings. It retreats along the segment only when a hit is reported;
49    /// it does not enlarge the probe or change a clear endpoint. Zero padding
50    /// permits contact. A blocked start has no permitted placement: this
51    /// method does not depenetrate or search for an escape route.
52    ///
53    /// Invalid sweep/padding or an invalid adapter fraction returns
54    /// [`CameraError::InvalidQuery`]; adapter errors propagate unchanged.
55    /// A stationary query still runs, and may return only `None` or `Some(0)`.
56    /// Storage and query count are constant; slice adapters retain their
57    /// [`MAX_BLOCKERS`] budget. Custom adapters determine geometric accuracy.
58    ///
59    /// ```
60    /// use ferravex_math::Vec3;
61    /// use ferravex_play::camera::{Blocker, CameraError, NoObstructions, Sweep};
62    /// let sweep = Sweep::new(Vec3::ZERO, Vec3::Z * 10., 0.25)?;
63    /// let wall = [Blocker::Plane { normal: -Vec3::Z, offset: -5. }];
64    /// let hit = sweep.probe(&wall[..], 0.25)?;
65    /// assert_eq!(hit.requested_distance, 10.);
66    /// assert_eq!(hit.hit_fraction, Some(0.475));
67    /// assert_eq!(hit.allowed_distance, 4.5);
68    /// assert_eq!(hit.allowed_position, Some(Vec3::Z * 4.5));
69    /// assert!(!hit.starts_blocked());
70    /// let clear = sweep.probe(&NoObstructions, 0.25)?;
71    /// assert_eq!(clear.hit_fraction, None);
72    /// assert_eq!(clear.allowed_position, Some(sweep.end));
73    /// # Ok::<(), CameraError>(())
74    /// ```
75    pub fn probe(
76        self,
77        query: &(impl CollisionQuery + ?Sized),
78        padding: f32,
79    ) -> Result<SweepOutcome, CameraError> {
80        if !self.valid() || !padding.is_finite() || !(0. ..=10.).contains(&padding) {
81            return Err(CameraError::InvalidQuery);
82        }
83        let hit_fraction = query.sweep(self)?;
84        if hit_fraction.is_some_and(|t| {
85            !t.is_finite() || !(0. ..=1.).contains(&t) || (self.start == self.end && t != 0.)
86        }) {
87            return Err(CameraError::InvalidQuery);
88        }
89        let requested_distance = self.start.distance(self.end);
90        let allowed_distance = hit_fraction.map_or(requested_distance, |t| {
91            (t * requested_distance - padding).max(0.)
92        });
93        let allowed_position = match hit_fraction {
94            Some(0.) => None,
95            None => Some(self.end),
96            Some(_) if allowed_distance == 0. => Some(self.start),
97            Some(_) => Some(
98                self.start
99                    .lerp(self.end, allowed_distance / requested_distance),
100            ),
101        };
102        Ok(SweepOutcome {
103            hit_fraction,
104            requested_distance,
105            allowed_distance,
106            allowed_position,
107        })
108    }
109}
110
111/// Diagnostics from [`Sweep::probe`], describing only the queried segment.
112/// Distances are sphere-center travel in world units, not surface separation.
113/// No penetration depth, surface normal or blocker identity is inferred from
114/// the fraction-only [`CollisionQuery`] abstraction.
115///
116/// ```
117/// use ferravex_math::Vec3;
118/// use ferravex_play::camera::{Blocker, CameraError, Sweep};
119/// let blockers = [Blocker::Sphere { center: Vec3::ZERO, radius: 1. }];
120/// let outcome = Sweep::new(Vec3::ZERO, Vec3::ZERO, 0.25)?
121///     .probe(&blockers[..], 0.02)?;
122/// assert!(outcome.starts_blocked());
123/// assert_eq!(outcome.allowed_position, None);
124/// # Ok::<(), CameraError>(())
125/// ```
126#[derive(Clone, Copy, Debug, PartialEq)]
127pub struct SweepOutcome {
128    /// First impact in `[0, 1]`; `None` means the whole segment is clear.
129    /// `Some(0)` includes initial contact as well as initial penetration.
130    pub hit_fraction: Option<f32>,
131    /// Length of the requested center segment, including zero-length queries.
132    pub requested_distance: f32,
133    /// Travel after subtracting padding from the hit distance and clamping to
134    /// zero. A clear probe retains the full requested distance.
135    pub allowed_distance: f32,
136    /// Placement after padding, or `None` when the starting point is blocked.
137    /// With zero padding this may touch an obstacle. It is not an escape point.
138    pub allowed_position: Option<Vec3>,
139}
140impl SweepOutcome {
141    /// Whether the adapter reported initial contact/overlap. Zero allowed
142    /// distance alone does not imply this: padding can consume a clear gap.
143    pub fn starts_blocked(self) -> bool {
144        self.hit_fraction == Some(0.)
145    }
146}
147
148/// Return the first sphere-center impact fraction in `[0,1]`, or None if clear.
149/// A blocked starting point must return Some(0), including zero-length sweeps.
150/// Stationary sweeps must return only None or Some(0). Use [`Sweep::probe`] for
151/// checked results and padded clearance without changing this adapter contract.
152pub trait CollisionQuery {
153    fn sweep(&self, sweep: Sweep) -> Result<Option<f32>, CameraError>;
154}
155impl<F: Fn(Sweep) -> Result<Option<f32>, CameraError>> CollisionQuery for F {
156    fn sweep(&self, sweep: Sweep) -> Result<Option<f32>, CameraError> {
157        self(sweep)
158    }
159}
160pub struct NoObstructions;
161impl CollisionQuery for NoObstructions {
162    fn sweep(&self, sweep: Sweep) -> Result<Option<f32>, CameraError> {
163        if sweep.valid() {
164            Ok(None)
165        } else {
166            Err(CameraError::InvalidQuery)
167        }
168    }
169}
170/// A small built-in adapter for authored environments. Box sweeps inflate the
171/// local box by radius and are conservative at corners; physics adapters may
172/// provide exact rounded-box/primitive sphere sweeps through CollisionQuery.
173#[derive(Clone, Copy, Debug, PartialEq)]
174pub enum Blocker {
175    Box {
176        center: Vec3,
177        half: Vec3,
178        rotation: Quat,
179    },
180    Sphere {
181        center: Vec3,
182        radius: f32,
183    },
184    /// Solid half-space normal.dot(point) <= offset, with unit outward normal.
185    Plane {
186        normal: Vec3,
187        offset: f32,
188    },
189}
190impl Blocker {
191    pub fn valid(self) -> bool {
192        match self {
193            Self::Box {
194                center,
195                half,
196                rotation,
197            } => {
198                bounded(center)
199                    && half.is_finite()
200                    && half.min_element() > 0.
201                    && half.max_element() <= 1e5
202                    && rotation.is_finite()
203                    && (rotation.length_squared() - 1.).abs() < 0.001
204            }
205            Self::Sphere { center, radius } => {
206                bounded(center) && radius.is_finite() && (0.001..=1e5).contains(&radius)
207            }
208            Self::Plane { normal, offset } => {
209                normal.is_finite()
210                    && (normal.length_squared() - 1.).abs() < 0.001
211                    && offset.is_finite()
212                    && offset.abs() <= 1e6
213            }
214        }
215    }
216    fn fraction(self, sweep: Sweep) -> Option<f32> {
217        match self {
218            Self::Box {
219                center,
220                half,
221                rotation,
222            } => {
223                let start = rotation.conjugate() * (sweep.start - center);
224                let end = rotation.conjugate() * (sweep.end - center);
225                let delta = end - start;
226                let half = half + Vec3::splat(sweep.radius);
227                let mut enter = 0_f32;
228                let mut exit = 1_f32;
229                for i in 0..3 {
230                    if delta[i].abs() < 1e-10 {
231                        if start[i].abs() > half[i] {
232                            return None;
233                        }
234                    } else {
235                        let a = (-half[i] - start[i]) / delta[i];
236                        let b = (half[i] - start[i]) / delta[i];
237                        enter = enter.max(a.min(b));
238                        exit = exit.min(a.max(b));
239                        if enter > exit {
240                            return None;
241                        }
242                    }
243                }
244                Some(enter)
245            }
246            Self::Sphere { center, radius } => {
247                // Widen before subtraction and dot products: an f32 squared
248                // distance can round away a real gap in a stationary probe.
249                let relative: [f64; 3] =
250                    std::array::from_fn(|i| f64::from(sweep.start[i]) - f64::from(center[i]));
251                let delta: [f64; 3] =
252                    std::array::from_fn(|i| f64::from(sweep.end[i]) - f64::from(sweep.start[i]));
253                let r = f64::from(radius) + f64::from(sweep.radius);
254                let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
255                let c = dot(relative, relative) - r * r;
256                if c <= 0. {
257                    return Some(0.);
258                }
259                let a = dot(delta, delta);
260                let b = dot(relative, delta);
261                if a == 0. || b >= 0. {
262                    return None;
263                }
264                // Use perpendicular distance to the line, avoiding cancellation
265                // in b*b - a*c on long segments passing small spheres.
266                let closest = std::array::from_fn(|i| relative[i] - delta[i] * (b / a));
267                let chord_squared = r * r - dot(closest, closest);
268                if chord_squared < 0. {
269                    return None;
270                }
271                // Equivalent to (-b - sqrt(discriminant)) / a, but does not
272                // subtract almost equal numbers when starting close to contact.
273                let t = c / (-b + (a * chord_squared).sqrt());
274                (0. ..=1.).contains(&t).then_some(t as f32)
275            }
276            Self::Plane { normal, offset } => {
277                let start = normal.dot(sweep.start) - offset - sweep.radius;
278                if start <= 0. {
279                    return Some(0.);
280                }
281                let end = normal.dot(sweep.end) - offset - sweep.radius;
282                if end > 0. {
283                    None
284                } else {
285                    Some(start / (start - end))
286                }
287            }
288        }
289    }
290}
291impl CollisionQuery for [Blocker] {
292    fn sweep(&self, sweep: Sweep) -> Result<Option<f32>, CameraError> {
293        if !sweep.valid() {
294            return Err(CameraError::InvalidQuery);
295        }
296        if self.len() > MAX_BLOCKERS {
297            return Err(CameraError::QueryBudget);
298        }
299        let mut first = None;
300        for &blocker in self {
301            if !blocker.valid() {
302                return Err(CameraError::InvalidObstacle);
303            }
304            if let Some(t) = blocker.fraction(sweep) {
305                first = Some(first.map_or(t, |old: f32| old.min(t)));
306            }
307        }
308        Ok(first)
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use std::cell::Cell;
316
317    #[test]
318    fn checked_sweep_enforces_existing_bounds_and_accepts_stationary_queries() {
319        for radius in [0.001, 1000.] {
320            assert!(Sweep::new(Vec3::splat(-1e6), Vec3::splat(1e6), radius).is_ok());
321            assert!(Sweep::new(Vec3::ZERO, Vec3::ZERO, radius).is_ok());
322        }
323        for radius in [0., -1., 0.0009, 1000.1, f32::NAN, f32::INFINITY] {
324            assert_eq!(
325                Sweep::new(Vec3::ZERO, Vec3::X, radius),
326                Err(CameraError::InvalidQuery)
327            );
328        }
329        for position in [Vec3::splat(1_000_001.), Vec3::NAN, Vec3::NEG_INFINITY] {
330            assert_eq!(
331                Sweep::new(position, Vec3::ZERO, 0.25),
332                Err(CameraError::InvalidQuery)
333            );
334            assert_eq!(
335                Sweep::new(Vec3::ZERO, position, 0.25),
336                Err(CameraError::InvalidQuery)
337            );
338        }
339    }
340
341    #[test]
342    fn invalid_probe_configuration_is_rejected_before_querying() {
343        let query = |_: Sweep| -> Result<Option<f32>, CameraError> {
344            panic!("invalid configuration must not reach the adapter")
345        };
346        let sweep = Sweep::new(Vec3::ZERO, Vec3::X, 0.25).unwrap();
347        for padding in [-0.001, 10.001, f32::NAN, f32::INFINITY] {
348            assert_eq!(sweep.probe(&query, padding), Err(CameraError::InvalidQuery));
349        }
350        for invalid in [
351            Sweep {
352                radius: 0.,
353                ..sweep
354            },
355            Sweep {
356                start: Vec3::NAN,
357                ..sweep
358            },
359            Sweep {
360                end: Vec3::INFINITY,
361                ..sweep
362            },
363        ] {
364            assert_eq!(invalid.probe(&query, 0.), Err(CameraError::InvalidQuery));
365        }
366    }
367
368    #[test]
369    fn clear_probes_keep_the_exact_endpoint_and_query_even_when_stationary() {
370        for (start, end) in [
371            (Vec3::ZERO, Vec3::Z * 10.),
372            (Vec3::X, Vec3::X),
373            (Vec3::splat(-1e6), Vec3::splat(1e6)),
374        ] {
375            let sweep = Sweep::new(start, end, 0.25).unwrap();
376            let calls = Cell::new(0);
377            let adapter = |observed| {
378                assert_eq!(observed, sweep);
379                calls.set(calls.get() + 1);
380                Ok(None)
381            };
382            let query: &dyn CollisionQuery = &adapter;
383            let result = sweep.probe(query, 10.).unwrap();
384            assert_eq!(calls.get(), 1);
385            assert_eq!(result.hit_fraction, None);
386            assert_eq!(result.requested_distance, start.distance(end));
387            assert_eq!(result.allowed_distance, result.requested_distance);
388            assert_eq!(result.allowed_position, Some(end));
389            assert!(!result.starts_blocked());
390        }
391    }
392
393    #[test]
394    fn padding_consuming_the_clearance_does_not_mean_the_start_is_blocked() {
395        let sweep = Sweep::new(Vec3::ZERO, Vec3::X * 10., 0.25).unwrap();
396        let blockers = [Blocker::Sphere {
397            center: Vec3::X * 5.,
398            radius: 1.,
399        }];
400        for (padding, expected_distance) in [(0., 3.75), (0.25, 3.5), (10., 0.)] {
401            let result = sweep.probe(&blockers[..], padding).unwrap();
402            assert_eq!(result.hit_fraction, Some(0.375));
403            assert_eq!(result.requested_distance, 10.);
404            assert_eq!(result.allowed_distance, expected_distance);
405            assert_eq!(result.allowed_position, Some(Vec3::X * expected_distance));
406            assert!(!result.starts_blocked());
407        }
408        let result = sweep.probe(&|_| Ok(Some(0.)), 0.25).unwrap();
409        assert!(result.starts_blocked());
410        assert_eq!(result.allowed_distance, 0.);
411        assert_eq!(result.allowed_position, None);
412    }
413
414    #[test]
415    fn every_shape_reports_initial_contact_and_stationary_overlap() {
416        for blocker in [
417            Blocker::Sphere {
418                center: Vec3::ZERO,
419                radius: 1.,
420            },
421            Blocker::Box {
422                center: Vec3::ZERO,
423                half: Vec3::ONE,
424                rotation: Quat::IDENTITY,
425            },
426            Blocker::Plane {
427                normal: Vec3::X,
428                offset: 1.,
429            },
430        ] {
431            let blockers = [blocker];
432            for start in [Vec3::ZERO, Vec3::X * 1.25] {
433                // Even motion out of an obstacle reports the blocked start.
434                for end in [start, Vec3::X * 3.] {
435                    let result = Sweep::new(start, end, 0.25)
436                        .unwrap()
437                        .probe(&blockers[..], 0.02)
438                        .unwrap();
439                    assert_eq!(result.hit_fraction, Some(0.), "{blocker:?}");
440                    assert!(result.starts_blocked());
441                    assert_eq!(result.allowed_distance, 0.);
442                    assert_eq!(result.allowed_position, None);
443                }
444            }
445            let outside = Vec3::X * 3.;
446            let result = Sweep::new(outside, outside, 0.25)
447                .unwrap()
448                .probe(&blockers[..], 0.02)
449                .unwrap();
450            assert_eq!(result.hit_fraction, None, "{blocker:?}");
451            assert_eq!(result.requested_distance, 0.);
452            assert_eq!(result.allowed_position, Some(outside));
453        }
454    }
455
456    #[test]
457    fn malformed_adapter_results_are_rejected_and_errors_propagate() {
458        let sweep = Sweep::new(Vec3::ZERO, Vec3::X, 0.25).unwrap();
459        for fraction in [-0.001, 1.001, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
460            assert_eq!(
461                sweep.probe(&|_| Ok(Some(fraction)), 0.),
462                Err(CameraError::InvalidQuery)
463            );
464        }
465        let point = Sweep::new(Vec3::ZERO, Vec3::ZERO, 0.25).unwrap();
466        for fraction in [f32::EPSILON, 0.5, 1.] {
467            assert_eq!(
468                point.probe(&|_| Ok(Some(fraction)), 0.),
469                Err(CameraError::InvalidQuery)
470            );
471        }
472        assert!(
473            point
474                .probe(&|_| Ok(Some(-0.)), 0.)
475                .unwrap()
476                .starts_blocked()
477        );
478        for error in [CameraError::InvalidObstacle, CameraError::QueryBudget] {
479            assert_eq!(sweep.probe(&|_| Err(error), 0.), Err(error));
480            assert_eq!(point.probe(&|_| Err(error), 0.), Err(error));
481        }
482    }
483
484    #[test]
485    fn probe_preserves_blocker_budget_and_validates_even_after_an_initial_hit() {
486        let sweep = Sweep::new(Vec3::ZERO, Vec3::ZERO, 0.25).unwrap();
487        let sphere = Blocker::Sphere {
488            center: Vec3::ZERO,
489            radius: 1.,
490        };
491        let mut blockers = vec![sphere; MAX_BLOCKERS];
492        assert!(sweep.probe(&blockers[..], 0.).unwrap().starts_blocked());
493        blockers.push(sphere);
494        assert_eq!(
495            sweep.probe(&blockers[..], 0.),
496            Err(CameraError::QueryBudget)
497        );
498        blockers.truncate(2);
499        blockers[1] = Blocker::Sphere {
500            center: Vec3::ZERO,
501            radius: f32::NAN,
502        };
503        assert_eq!(
504            sweep.probe(&blockers[..], 0.),
505            Err(CameraError::InvalidObstacle)
506        );
507        assert_eq!(sweep.probe(&[][..], 0.).unwrap().hit_fraction, None);
508    }
509
510    #[test]
511    fn stationary_sphere_probe_preserves_a_near_tangent_gap() {
512        let blockers = [Blocker::Sphere {
513            center: Vec3::ZERO,
514            radius: 1.,
515        }];
516        let position = Vec3::new(1.25, 0.0001, 0.);
517        assert_eq!(
518            blockers[..].sweep(Sweep {
519                start: position,
520                end: position,
521                radius: 0.25,
522            }),
523            Ok(None)
524        );
525    }
526
527    #[test]
528    fn long_sphere_sweep_preserves_a_clear_miss() {
529        let blockers = [Blocker::Sphere {
530            center: Vec3::new(500_000., 2., 0.),
531            radius: 0.25,
532        }];
533        assert_eq!(
534            blockers[..].sweep(Sweep {
535                start: Vec3::ZERO,
536                end: Vec3::X * 1_000_000.,
537                radius: 0.25,
538            }),
539            Ok(None)
540        );
541    }
542
543    #[test]
544    fn sphere_entry_at_near_contact_tangency_and_endpoints_is_retained() {
545        let blockers = [Blocker::Sphere {
546            center: Vec3::ZERO,
547            radius: 1.,
548        }];
549        for (start, end, expected) in [
550            (Vec3::X * 2., Vec3::ZERO, Some(0.375)),
551            (Vec3::X * 2., Vec3::X * 1.25, Some(1.)),
552            (Vec3::new(-2., 1.25, 0.), Vec3::new(2., 1.25, 0.), Some(0.5)),
553            (Vec3::X * 2., Vec3::X * 3., None),
554            (Vec3::X * 2., Vec3::X * 1.5, None),
555        ] {
556            assert_eq!(
557                blockers[..].sweep(Sweep::new(start, end, 0.25).unwrap()),
558                Ok(expected)
559            );
560        }
561        let start = Vec3::X * f32::from_bits(1.25_f32.to_bits() + 1);
562        let sweep = Sweep::new(start, Vec3::ZERO, 0.25).unwrap();
563        let result = sweep.probe(&blockers[..], 0.).unwrap();
564        assert!(!result.starts_blocked());
565        assert!(result.hit_fraction.unwrap() > 0.);
566        assert!(result.allowed_distance > 0.);
567        assert_eq!(result.allowed_position, Some(Vec3::X * 1.25));
568    }
569
570    #[test]
571    fn sphere_probe_retains_small_radii_on_long_paths() {
572        for y in [0., 0.004] {
573            let blockers = [Blocker::Sphere {
574                center: Vec3::new(500_000., y, 0.),
575                radius: 0.001,
576            }];
577            let sweep = Sweep::new(Vec3::ZERO, Vec3::X * 1_000_000., 0.001).unwrap();
578            let fraction = blockers[..].sweep(sweep).unwrap();
579            if y == 0. {
580                assert!((fraction.unwrap() - 0.5).abs() < f32::EPSILON);
581            } else {
582                assert_eq!(fraction, None);
583            }
584        }
585    }
586}