Skip to main content

crcbl_phys/
collider.rs

1//! Collider shapes and bounding volumes for physics queries.
2//!
3//! Every collider shape can produce an axis-aligned bounding box ([`Aabb`]) for
4//! broadphase culling. Shapes are parametric (no mesh data) — L0 covers spheres,
5//! boxes, and capsules, which together handle ~90% of the engines collision
6//! needs (projectiles, characters, vehicles, pickups).
7//!
8//! All spatial types use `f64` so queries are consistent with the server's
9//! deterministic tick loop. Downcasting to `f32` happens only at the render
10//! boundary (camera-relative transforms).
11
12use crcbl_core::bounds::{max_lanes_d, min_lanes_d};
13use glam::{DMat3, DQuat, DVec3};
14
15// ---------------------------------------------------------------------------
16// Aabb
17// ---------------------------------------------------------------------------
18
19/// An axis-aligned bounding box.
20///
21/// Defined by a minimum and maximum corner. An empty / degenerate box has
22/// `min > max` on at least one axis; [`Aabb::EMPTY`] is the canonical empty
23/// value and [`Aabb::is_empty`] checks for it.
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct Aabb {
26    /// Minimum corner (inclusive).
27    pub min: DVec3,
28    /// Maximum corner (inclusive).
29    pub max: DVec3,
30}
31
32impl Aabb {
33    /// The empty AABB: `min = +inf, max = -inf`. Union with any real AABB
34    /// produces that real AABB.
35    pub const EMPTY: Self = Self {
36        min: DVec3::splat(f64::INFINITY),
37        max: DVec3::splat(f64::NEG_INFINITY),
38    };
39
40    /// Create an AABB from explicit min / max bounds.
41    ///
42    /// The caller is responsible for ensuring `min ≤ max` per axis; a box that
43    /// violates it reads as empty (see [`Aabb::is_empty`]).
44    #[inline]
45    #[must_use]
46    pub fn new(min: DVec3, max: DVec3) -> Self {
47        Self { min, max }
48    }
49
50    /// Build an AABB from a centre and half-extents.
51    #[inline]
52    #[must_use]
53    pub fn from_centre_half(centre: DVec3, half: DVec3) -> Self {
54        Self {
55            min: centre - half,
56            max: centre + half,
57        }
58    }
59
60    /// The centre of this AABB.
61    #[inline]
62    #[must_use]
63    pub fn centre(&self) -> DVec3 {
64        (self.min + self.max) * 0.5
65    }
66
67    /// Extents on each axis (full width / height / depth).
68    #[inline]
69    #[must_use]
70    pub fn extents(&self) -> DVec3 {
71        self.max - self.min
72    }
73
74    /// Whether this AABB is degenerate: `min` is past `max` on at least one
75    /// axis. A zero-extent (flat or point) box is *not* empty — it still
76    /// intersects and bounds correctly.
77    #[inline]
78    #[must_use]
79    pub fn is_empty(&self) -> bool {
80        self.min.x > self.max.x || self.min.y > self.max.y || self.min.z > self.max.z
81    }
82
83    /// Half the true surface area of this box — `wh + hd + dw`.
84    ///
85    /// This is the cost term of the surface area heuristic the dynamic BVH
86    /// picks insertion sites with. The factor of two the real surface area
87    /// carries is dropped because every comparison the heuristic makes is
88    /// between two of these, and a constant factor common to both sides cannot
89    /// change which one is smaller.
90    ///
91    /// An empty box has no surface, so it costs `0` rather than the `NaN` that
92    /// `(-inf) - (+inf)` arithmetic on [`Aabb::EMPTY`] would otherwise produce
93    /// and propagate into every subsequent comparison.
94    #[inline]
95    #[must_use]
96    pub(crate) fn half_surface_area(&self) -> f64 {
97        if self.is_empty() {
98            return 0.0;
99        }
100        let e = self.extents();
101        e.x * e.y + e.y * e.z + e.z * e.x
102    }
103
104    /// Widen this AABB by a uniform margin on every side.
105    #[inline]
106    #[must_use]
107    pub fn inflated(self, margin: f64) -> Self {
108        Self {
109            min: self.min - DVec3::splat(margin),
110            max: self.max + DVec3::splat(margin),
111        }
112    }
113
114    // -- set operations -------------------------------------------------------
115
116    /// Union with another AABB, expanding to contain both.
117    #[inline]
118    #[must_use]
119    pub fn union(self, other: Self) -> Self {
120        if other.is_empty() {
121            return self;
122        }
123        if self.is_empty() {
124            return other;
125        }
126        // Not `DVec3::min`/`DVec3::max`: glam writes those as a bare `<` per
127        // lane, which is false against a `NaN` and so yields the *incoming*
128        // box, discarding the accumulator. `Bvh::build_rec` folds this over a
129        // range, so one `NaN` body position followed by one finite body left a
130        // parent node that came back finite and no longer contained its
131        // children — and overlap and ray queries silently miss those pairs.
132        // The `is_empty` guards above do not catch it either: `is_empty` is
133        // `min.x > max.x`, and `>` is false on a `NaN`, so a poisoned box reads
134        // as non-empty. See `crcbl_core::bounds`.
135        Self {
136            min: min_lanes_d(self.min, other.min),
137            max: max_lanes_d(self.max, other.max),
138        }
139    }
140
141    /// Whether `other` overlaps this AABB (touching counts as overlapping).
142    #[inline]
143    #[must_use]
144    pub fn intersects(&self, other: &Self) -> bool {
145        self.min.x <= other.max.x
146            && self.max.x >= other.min.x
147            && self.min.y <= other.max.y
148            && self.max.y >= other.min.y
149            && self.min.z <= other.max.z
150            && self.max.z >= other.min.z
151    }
152
153    /// Whether `other` lies wholly inside this AABB (a shared face counts as
154    /// inside).
155    ///
156    /// The contact broadphase's test for a proxy that has left its fattened
157    /// bounds: a `NaN` anywhere in `other` answers `false`, so a poisoned body
158    /// is re-inserted rather than kept on bounds that no longer describe it.
159    #[inline]
160    #[must_use]
161    pub fn contains(&self, other: &Self) -> bool {
162        self.min.x <= other.min.x
163            && self.min.y <= other.min.y
164            && self.min.z <= other.min.z
165            && self.max.x >= other.max.x
166            && self.max.y >= other.max.y
167            && self.max.z >= other.max.z
168    }
169
170    /// The point of this box (a solid, so its interior counts) nearest to
171    /// `point`: `point` itself when it is inside or on the surface, otherwise
172    /// the point on the surface it is closest to.
173    ///
174    /// `None` when there is no answer to give: the box is empty (`min` past
175    /// `max` on an axis), or `point` or either corner holds a `NaN`. Clamping
176    /// against such a box would either panic in `f64::clamp` or hand back a
177    /// `NaN` that reads as a position everywhere downstream.
178    #[inline]
179    #[must_use]
180    pub fn closest_point(&self, point: DVec3) -> Option<DVec3> {
181        // `cmple` is false on a `NaN` lane, so one test refuses both an
182        // inverted box and a poisoned one — `is_empty` alone passes a `NaN`.
183        if !self.min.cmple(self.max).all() || point.is_nan() {
184            return None;
185        }
186        Some(point.clamp(self.min, self.max))
187    }
188
189    // -- ray intersection (slab method)---------------------------------------
190
191    /// The parametric interval `(t_near, t_far)` over which a ray is inside
192    /// this AABB, or `None` if the ray misses it entirely.
193    ///
194    /// This is the one slab test in the crate — the boolean overlap check, the
195    /// BVH's entry-distance probe and the shape-level box queries all go
196    /// through it. `inv_dir` is the component-wise reciprocal of the ray
197    /// direction and `dir_is_neg` its per-axis sign; both are precomputed by
198    /// the caller because a traversal reuses them across many boxes. Axes with
199    /// a zero direction component (infinite reciprocal) are handled without
200    /// producing `NaN` from `0.0 * INF`.
201    ///
202    /// The interval is unclamped: `t_near` is negative when the ray origin is
203    /// inside the box. Choosing which end to report is the caller's job — see
204    /// `crate::query`'s shared root-selection rule.
205    #[must_use]
206    pub(crate) fn ray_slab(
207        &self,
208        origin: DVec3,
209        inv_dir: DVec3,
210        dir_is_neg: [bool; 3],
211    ) -> Option<(f64, f64)> {
212        let origin = origin.to_array();
213        let inv_dir = inv_dir.to_array();
214        let min = self.min.to_array();
215        let max = self.max.to_array();
216
217        let mut t_near = f64::NEG_INFINITY;
218        let mut t_far = f64::INFINITY;
219        for axis in 0..3 {
220            let (lo, hi) = if dir_is_neg[axis] {
221                (max[axis], min[axis])
222            } else {
223                (min[axis], max[axis])
224            };
225            if inv_dir[axis].is_finite() {
226                t_near = t_near.max((lo - origin[axis]) * inv_dir[axis]);
227                t_far = t_far.min((hi - origin[axis]) * inv_dir[axis]);
228            } else if origin[axis] < min[axis] || origin[axis] > max[axis] {
229                // Parallel to this slab and outside it: no intersection.
230                return None;
231            }
232        }
233
234        if t_near > t_far {
235            return None;
236        }
237        Some((t_near, t_far))
238    }
239
240    /// Test whether a ray intersects this AABB, using the pre-computed
241    /// inverse direction and sign flags for efficiency.
242    ///
243    /// `t_min` and `t_max` bound the ray segment (typically `(0, +inf)` for
244    /// unbounded rays, or `(0, length)` for segments).
245    #[inline]
246    #[must_use]
247    pub fn intersect_ray(
248        &self,
249        origin: DVec3,
250        inv_dir: DVec3,
251        dir_is_neg: [bool; 3],
252        t_min: f64,
253        t_max: f64,
254    ) -> bool {
255        self.ray_slab(origin, inv_dir, dir_is_neg)
256            .is_some_and(|(t_near, t_far)| t_near <= t_max && t_far >= t_min)
257    }
258}
259
260// ---------------------------------------------------------------------------
261// Sphere
262// ---------------------------------------------------------------------------
263
264/// A sphere collider.
265#[derive(Debug, Clone, Copy, PartialEq)]
266pub struct Sphere {
267    /// Centre in local simulation space.
268    pub centre: DVec3,
269    /// Radius, in metres.
270    pub radius: f64,
271}
272
273impl Sphere {
274    /// Create a sphere.
275    #[inline]
276    #[must_use]
277    pub fn new(centre: DVec3, radius: f64) -> Self {
278        debug_assert!(radius >= 0.0, "sphere radius must be non-negative");
279        Self { centre, radius }
280    }
281
282    /// AABB of this sphere.
283    #[inline]
284    #[must_use]
285    pub fn aabb(&self) -> Aabb {
286        let r = DVec3::splat(self.radius);
287        Aabb {
288            min: self.centre - r,
289            max: self.centre + r,
290        }
291    }
292}
293
294// ---------------------------------------------------------------------------
295// BoxCollider
296// ---------------------------------------------------------------------------
297
298/// A box collider: a centre, half extents along the box's own axes, and how
299/// those axes are turned from the world's.
300///
301/// [`BoxCollider::new`] makes an unturned box, whose axes are the world's, and
302/// [`BoxCollider::with_rotation`] turns one. The query world answers rays,
303/// sweeps and overlaps against the turned box itself, not the world-axis box
304/// around it — see [`crate::query::ray_vs_box`] and its siblings — and its
305/// broadphase holds that world-axis box, [`aabb`](Self::aabb).
306#[derive(Debug, Clone, Copy, PartialEq)]
307pub struct BoxCollider {
308    /// Centre in local simulation space.
309    pub centre: DVec3,
310    /// Half-width along each of the box's own axes, in metres.
311    pub half_extents: DVec3,
312    /// How the box's axes are turned from the world's: a unit quaternion,
313    /// [`DQuat::IDENTITY`] for a box whose axes are the world's.
314    pub rotation: DQuat,
315}
316
317impl BoxCollider {
318    /// Create an unturned box collider: its axes are the world's.
319    ///
320    /// # Panics
321    ///
322    /// Panics in debug builds if any half-extent is negative.
323    #[inline]
324    #[must_use]
325    pub fn new(centre: DVec3, half_extents: DVec3) -> Self {
326        debug_assert!(
327            half_extents.x >= 0.0 && half_extents.y >= 0.0 && half_extents.z >= 0.0,
328            "box half-extents must be non-negative"
329        );
330        Self {
331            centre,
332            half_extents,
333            rotation: DQuat::IDENTITY,
334        }
335    }
336
337    /// This box turned by `rotation` about its centre, which must be a unit
338    /// quaternion.
339    #[inline]
340    #[must_use]
341    pub const fn with_rotation(self, rotation: DQuat) -> Self {
342        Self { rotation, ..self }
343    }
344
345    /// The smallest world-axis box holding this one: the box itself for an
346    /// unturned collider, and for a turned one its half extents projected onto
347    /// each world axis (the absolute rotation matrix times the extents,
348    /// Ericson, _Real-Time Collision Detection_ §4.2.6).
349    ///
350    /// Exactly `centre ± half_extents` when unturned, an infinite extent
351    /// included, which the projection would turn into `0 · ∞ = NaN`.
352    #[inline]
353    #[must_use]
354    pub fn aabb(&self) -> Aabb {
355        if !self.is_turned() {
356            return Aabb {
357                min: self.centre - self.half_extents,
358                max: self.centre + self.half_extents,
359            };
360        }
361        let turned = DMat3::from_quat(self.rotation);
362        let reach = DVec3::new(
363            turned.row(0).abs().dot(self.half_extents),
364            turned.row(1).abs().dot(self.half_extents),
365            turned.row(2).abs().dot(self.half_extents),
366        );
367        Aabb {
368            min: self.centre - reach,
369            max: self.centre + reach,
370        }
371    }
372
373    /// Whether the box's axes are not the world's. An unturned box is answered
374    /// by the world-axis queries directly, so its answers are the ones it had
375    /// before boxes could turn, to the bit.
376    #[inline]
377    #[must_use]
378    pub fn is_turned(&self) -> bool {
379        self.rotation != DQuat::IDENTITY
380    }
381
382    /// The box at the origin with its own axes, as a world-axis box: what a
383    /// query moved into the box's frame ([`local_point`](Self::local_point)) is
384    /// tested against.
385    #[inline]
386    #[must_use]
387    pub(crate) fn local_aabb(&self) -> Aabb {
388        Aabb {
389            min: -self.half_extents,
390            max: self.half_extents,
391        }
392    }
393
394    /// `point` in the box's own frame: relative to its centre, turned back by
395    /// its rotation.
396    #[inline]
397    #[must_use]
398    pub(crate) fn local_point(&self, point: DVec3) -> DVec3 {
399        self.rotation.inverse() * (point - self.centre)
400    }
401
402    /// `local`, a point in the box's own frame, back in the world.
403    #[inline]
404    #[must_use]
405    pub(crate) fn world_point(&self, local: DVec3) -> DVec3 {
406        self.centre + self.rotation * local
407    }
408}
409
410// ---------------------------------------------------------------------------
411// Capsule
412// ---------------------------------------------------------------------------
413
414/// A capsule collider: a cylinder with hemispherical caps, aligned to the Y
415/// axis in local space.
416///
417/// A capsule is defined by a centre point, a radius, and a half-height
418/// (half the length of the cylindrical section). The total length is
419/// `2 * half_height + 2 * radius`.
420#[derive(Debug, Clone, Copy, PartialEq)]
421pub struct Capsule {
422    /// Centre of the cylindrical section (midpoint between the two hemisphere
423    /// centres).
424    pub centre: DVec3,
425    /// Radius of the capsule (both the cylinder and the hemispherical caps).
426    pub radius: f64,
427    /// Half the length of the cylindrical section, not including caps.
428    pub half_height: f64,
429}
430
431impl Capsule {
432    /// Create a capsule.
433    ///
434    /// # Panics
435    ///
436    /// Panics in debug builds if radius or half-height is negative.
437    #[inline]
438    #[must_use]
439    pub fn new(centre: DVec3, radius: f64, half_height: f64) -> Self {
440        debug_assert!(radius >= 0.0, "capsule radius must be non-negative");
441        debug_assert!(
442            half_height >= 0.0,
443            "capsule half-height must be non-negative"
444        );
445        Self {
446            centre,
447            radius,
448            half_height,
449        }
450    }
451
452    /// AABB of this capsule (the capsule is always Y-aligned).
453    #[inline]
454    #[must_use]
455    pub fn aabb(&self) -> Aabb {
456        let total_half = DVec3::new(self.radius, self.half_height + self.radius, self.radius);
457        Aabb {
458            min: self.centre - total_half,
459            max: self.centre + total_half,
460        }
461    }
462
463    /// The top hemisphere centre.
464    #[inline]
465    #[must_use]
466    pub fn top(&self) -> DVec3 {
467        DVec3::new(
468            self.centre.x,
469            self.centre.y + self.half_height,
470            self.centre.z,
471        )
472    }
473
474    /// The bottom hemisphere centre.
475    #[inline]
476    #[must_use]
477    pub fn bottom(&self) -> DVec3 {
478        DVec3::new(
479            self.centre.x,
480            self.centre.y - self.half_height,
481            self.centre.z,
482        )
483    }
484}
485
486// ---------------------------------------------------------------------------
487// LyingCapsule
488// ---------------------------------------------------------------------------
489
490/// A capsule lying on its side: a prone body, its core running from the head
491/// back to the feet, level or pitched to follow the ground.
492///
493/// A query shape, not a collider, for asking whether a body lying at a pose
494/// would be inside anything, see [`crate::PhysicsWorld::lying_capsule_blocker`],
495/// and for moving one, see [`crate::CharacterController::move_lying`].
496///
497/// # The pose
498///
499/// - [`head`](Self::head) is the centre of the hemisphere at the head end.
500/// - [`yaw`](Self::yaw) is the way the head faces, in radians: a right-handed
501///   turn about `+Y`, which is up, from `-Z`. Zero faces `-Z`, a quarter turn
502///   faces `-X`, a half turn `+Z` and three quarters `+X` — `-Z` turned by the
503///   rotation [`crate::rotation_from_scaled_axis`] builds from `+Y · yaw`, and
504///   the `ahead` of `OrbitCamera::walk_direction` in `crcbl-render`.
505/// - [`pitch_sine`](Self::pitch_sine) tilts the core out of the horizontal,
506///   about the head: it is the **sine** of the angle the core makes with the
507///   horizontal, **positive when the head end is higher** than the feet end —
508///   a body crawling head first up a slope has a positive pitch. Zero, which
509///   [`new`](Self::new) gives, lies level.
510/// - [`length`](Self::length) is how far behind the head the feet end's
511///   hemisphere centre lies, along the core, so the body reaches a further
512///   [`radius`](Self::radius) past each of the two ends.
513///
514/// The pitch is a sine and not an angle for the reason
515/// [`CharacterConfig::min_ground_normal_y`](crate::CharacterConfig::min_ground_normal_y)
516/// is a cosine: this crate constructs no inverse trigonometry, and a pitch
517/// found from the ground comes out of a square root. [`axis`](Self::axis) is
518/// the direction it gives the core, which is what a renderer orients the body
519/// model by.
520///
521/// A length of zero is a sphere at `head`, which is what a character
522/// controller with a `half_height` of zero already is.
523#[derive(Debug, Clone, Copy, PartialEq)]
524pub struct LyingCapsule {
525    /// Centre of the head end's hemisphere.
526    pub head: DVec3,
527    /// The way the head faces, in radians about `+Y` from `-Z`.
528    pub yaw: f64,
529    /// The sine of the core's angle above the horizontal, positive with the
530    /// head end higher: in `[-1, 1]`.
531    pub pitch_sine: f64,
532    /// Radius of the capsule.
533    pub radius: f64,
534    /// Distance from the head end's hemisphere centre back to the feet end's,
535    /// not including the caps.
536    pub length: f64,
537}
538
539impl LyingCapsule {
540    /// A capsule lying level at a pose; see the type for what each part means.
541    ///
542    /// # Panics
543    ///
544    /// Panics in debug builds if radius or length is negative.
545    #[inline]
546    #[must_use]
547    pub fn new(head: DVec3, yaw: f64, radius: f64, length: f64) -> Self {
548        debug_assert!(radius >= 0.0, "capsule radius must be non-negative");
549        debug_assert!(length >= 0.0, "capsule length must be non-negative");
550        Self {
551            head,
552            yaw,
553            pitch_sine: 0.0,
554            radius,
555            length,
556        }
557    }
558
559    /// The same capsule pitched about its head: see
560    /// [`pitch_sine`](Self::pitch_sine).
561    ///
562    /// # Panics
563    ///
564    /// Panics in debug builds if `pitch_sine` is outside `[-1, 1]`.
565    #[inline]
566    #[must_use]
567    pub fn with_pitch_sine(self, pitch_sine: f64) -> Self {
568        debug_assert!(
569            (-1.0..=1.0).contains(&pitch_sine),
570            "a pitch sine lies in [-1, 1], not {pitch_sine}"
571        );
572        Self { pitch_sine, ..self }
573    }
574
575    /// The unit horizontal direction the head faces, which the
576    /// [`yaw`](Self::yaw) alone decides: from the feet toward the head, seen
577    /// from above.
578    #[inline]
579    #[must_use]
580    pub fn facing(&self) -> DVec3 {
581        DVec3::new(
582            -crcbl_core::trig::sin(self.yaw),
583            0.0,
584            -crcbl_core::trig::cos(self.yaw),
585        )
586    }
587
588    /// The unit direction of the core from the feet end toward the head end:
589    /// the [`facing`](Self::facing), tilted up by the
590    /// [`pitch_sine`](Self::pitch_sine). Level, it is the facing itself.
591    #[inline]
592    #[must_use]
593    pub fn axis(&self) -> DVec3 {
594        let facing = self.facing();
595        let level = (1.0 - self.pitch_sine * self.pitch_sine).max(0.0).sqrt();
596        DVec3::new(facing.x * level, self.pitch_sine, facing.z * level)
597    }
598
599    /// Centre of the feet end's hemisphere: [`length`](Self::length) behind
600    /// the head along the [`axis`](Self::axis).
601    #[inline]
602    #[must_use]
603    pub fn feet(&self) -> DVec3 {
604        self.head - self.axis() * self.length
605    }
606
607    /// AABB of this capsule.
608    #[inline]
609    #[must_use]
610    pub fn aabb(&self) -> Aabb {
611        let feet = self.feet();
612        let r = DVec3::splat(self.radius);
613        Aabb {
614            min: self.head.min(feet) - r,
615            max: self.head.max(feet) + r,
616        }
617    }
618}
619
620// ---------------------------------------------------------------------------
621// Tests
622// ---------------------------------------------------------------------------
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627
628    // -- Aabb ----------------------------------------------------------------
629
630    /// **A `NaN` box does not eat the union it is folded into.**
631    ///
632    /// `Bvh::build_rec` folds `union` over a range of items, so this is the
633    /// shape that matters rather than the pairwise call. glam's `DVec3::min` is
634    /// a bare `<` per lane, false against a `NaN`, so it used to yield the
635    /// incoming box and throw the accumulator away — and then the *next* finite
636    /// box threw the `NaN` away, leaving a node that was finite and no longer
637    /// contained its children. A parent that does not contain its children is a
638    /// BVH that silently misses overlaps.
639    ///
640    /// The `is_empty` early-outs do not save it: `is_empty` is `min.x > max.x`,
641    /// and every comparison against a `NaN` is false, so a poisoned box reads as
642    /// non-empty and goes down the folding path.
643    #[test]
644    fn a_nan_box_does_not_shrink_the_union_it_is_folded_into() {
645        let low = Aabb::from_centre_half(DVec3::splat(-2.0), DVec3::splat(1.0));
646        let high = Aabb::from_centre_half(DVec3::splat(2.0), DVec3::splat(1.0));
647        let nan = Aabb {
648            min: DVec3::new(f64::NAN, 0.0, 0.0),
649            max: DVec3::new(f64::NAN, 0.0, 0.0),
650        };
651
652        assert!(
653            !nan.is_empty(),
654            "a NaN box reads as non-empty, which is why the early-outs above do not catch it"
655        );
656
657        // The damaging order: a finite box after the NaN restores finiteness
658        // while the extent gathered before it would be gone.
659        let folded = [low, high, nan, low]
660            .into_iter()
661            .fold(Aabb::EMPTY, Aabb::union);
662
663        assert!(
664            folded.min.x <= low.min.x && folded.max.x >= high.max.x,
665            "the union came back as {:?}..{:?}, which does not contain the boxes it was folded \
666             from — a BVH node like this misses every pair in the part it dropped",
667            folded.min,
668            folded.max
669        );
670    }
671
672    #[test]
673    fn empty_aabb_is_empty() {
674        assert!(Aabb::EMPTY.is_empty());
675    }
676
677    #[test]
678    fn point_aabb_is_not_empty() {
679        let aabb = Aabb::new(DVec3::splat(1.0), DVec3::splat(1.0));
680        assert!(!aabb.is_empty());
681        assert_eq!(aabb.min, DVec3::splat(1.0));
682        assert_eq!(aabb.max, DVec3::splat(1.0));
683    }
684
685    #[test]
686    fn union_with_empty_is_identity() {
687        let a = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
688        assert_eq!(a.union(Aabb::EMPTY), a);
689        assert_eq!(Aabb::EMPTY.union(a), a);
690    }
691
692    #[test]
693    fn union_expands_to_contain_both() {
694        let a = Aabb::from_centre_half(DVec3::new(-2.0, 0.0, 0.0), DVec3::splat(1.0));
695        let b = Aabb::from_centre_half(DVec3::new(2.0, 0.0, 0.0), DVec3::splat(1.0));
696        let u = a.union(b);
697        assert_eq!(u.min.x, -3.0);
698        assert_eq!(u.max.x, 3.0);
699    }
700
701    #[test]
702    fn two_overlapping_aabbs_report_that_they_intersect() {
703        let a = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(2.0));
704        let b = Aabb::from_centre_half(DVec3::new(1.0, 0.0, 0.0), DVec3::splat(2.0));
705        assert!(a.intersects(&b));
706    }
707
708    #[test]
709    fn aabb_does_not_intersect_separated() {
710        let a = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
711        let b = Aabb::from_centre_half(DVec3::new(5.0, 0.0, 0.0), DVec3::splat(1.0));
712        assert!(!a.intersects(&b));
713    }
714
715    #[test]
716    fn a_ray_aimed_at_a_box_passes_the_slab_test() {
717        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
718        let origin = DVec3::new(-5.0, 0.0, 0.0);
719        let dir = DVec3::new(1.0, 0.0, 0.0);
720        let inv_dir = dir.recip();
721        let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
722        assert!(aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
723    }
724
725    #[test]
726    fn a_ray_passing_above_a_box_fails_the_slab_test() {
727        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
728        let origin = DVec3::new(-5.0, 10.0, 0.0);
729        let dir = DVec3::new(1.0, 0.0, 0.0);
730        let inv_dir = dir.recip();
731        let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
732        assert!(!aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
733    }
734
735    #[test]
736    fn ray_hits_from_inside() {
737        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
738        let origin = DVec3::ZERO;
739        let dir = DVec3::new(1.0, 0.0, 0.0);
740        let inv_dir = dir.recip();
741        let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
742        assert!(aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
743    }
744
745    #[test]
746    fn ray_on_face_with_zero_dir_component_hits() {
747        // Ray starts on +Y face with dir having zero Y component.
748        // Old code: (loy - origin.y) * inv_dir.y = (1.0 - 1.0) * INF = 0.0 * INF = NaN.
749        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
750        let origin = DVec3::new(0.0, 1.0, 0.0);
751        let dir = DVec3::new(1.0, 0.0, 0.0);
752        let inv_dir = dir.recip();
753        let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
754        assert!(aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
755    }
756
757    #[test]
758    fn ray_on_face_with_zero_dir_component_parallel_miss() {
759        // Ray outside AABB on Y, with zero Y direction → parallel miss.
760        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
761        let origin = DVec3::new(0.0, 5.0, 0.0);
762        let dir = DVec3::new(1.0, 0.0, 0.0);
763        let inv_dir = dir.recip();
764        let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
765        assert!(!aabb.intersect_ray(origin, inv_dir, neg, 0.0, f64::INFINITY));
766    }
767
768    #[test]
769    fn ray_slab_reports_entry_and_exit() {
770        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
771        let dir = DVec3::X;
772        let neg = [dir.x < 0.0, dir.y < 0.0, dir.z < 0.0];
773        // Origin inside: entry is behind the origin, exit ahead of it.
774        let (near, far) = aabb.ray_slab(DVec3::ZERO, dir.recip(), neg).unwrap();
775        assert!((near + 1.0).abs() < 1e-12);
776        assert!((far - 1.0).abs() < 1e-12);
777    }
778
779    #[test]
780    fn the_closest_point_of_a_box_is_on_its_surface_from_outside() {
781        let aabb = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 2.0, 3.0));
782        // Past a face: only that axis moves.
783        assert_eq!(
784            aabb.closest_point(DVec3::new(0.5, 5.0, 1.0)),
785            Some(DVec3::new(0.5, 2.0, 1.0))
786        );
787        // Past a corner: every axis clamps.
788        assert_eq!(
789            aabb.closest_point(DVec3::new(-4.0, -1.0, 9.0)),
790            Some(DVec3::new(0.0, 0.0, 3.0))
791        );
792    }
793
794    #[test]
795    fn the_closest_point_of_a_box_to_a_point_inside_it_is_that_point() {
796        let aabb = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 2.0, 3.0));
797        let inside = DVec3::new(0.25, 1.5, 2.75);
798        assert_eq!(aabb.closest_point(inside), Some(inside));
799        // A flat box is a real box: its face is its interior.
800        let flat = Aabb::new(DVec3::ZERO, DVec3::new(1.0, 0.0, 1.0));
801        assert_eq!(
802            flat.closest_point(DVec3::new(0.5, 3.0, 0.5)),
803            Some(DVec3::new(0.5, 0.0, 0.5))
804        );
805    }
806
807    #[test]
808    fn an_empty_or_nan_box_or_a_nan_point_has_no_closest_point() {
809        let unit = Aabb::new(DVec3::ZERO, DVec3::ONE);
810        assert_eq!(Aabb::EMPTY.closest_point(DVec3::ZERO), None);
811        assert_eq!(
812            Aabb::new(DVec3::ONE, DVec3::ZERO).closest_point(DVec3::ZERO),
813            None
814        );
815        let poisoned = Aabb::new(DVec3::new(f64::NAN, 0.0, 0.0), DVec3::ONE);
816        assert!(
817            !poisoned.is_empty(),
818            "a NaN box reads as non-empty, so is_empty alone would not refuse it"
819        );
820        assert_eq!(poisoned.closest_point(DVec3::ZERO), None);
821        assert_eq!(unit.closest_point(DVec3::new(0.0, f64::NAN, 0.0)), None);
822    }
823
824    #[test]
825    fn inflated_aabb_is_larger() {
826        let aabb = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.0));
827        let inflated = aabb.inflated(0.5);
828        assert_eq!(inflated.min, DVec3::splat(-1.5));
829        assert_eq!(inflated.max, DVec3::splat(1.5));
830    }
831
832    #[test]
833    fn from_centre_half_roundtrips() {
834        let aabb = Aabb::from_centre_half(DVec3::new(1.0, 2.0, 3.0), DVec3::new(0.5, 1.0, 1.5));
835        assert_eq!(aabb.centre(), DVec3::new(1.0, 2.0, 3.0));
836        assert_eq!(aabb.extents(), DVec3::new(1.0, 2.0, 3.0));
837    }
838
839    // -- Sphere --------------------------------------------------------------
840
841    #[test]
842    fn a_spheres_bounds_are_its_centre_expanded_by_its_radius() {
843        let s = Sphere::new(DVec3::new(1.0, 2.0, 3.0), 0.5);
844        let aabb = s.aabb();
845        assert_eq!(aabb.min, DVec3::new(0.5, 1.5, 2.5));
846        assert_eq!(aabb.max, DVec3::new(1.5, 2.5, 3.5));
847    }
848
849    // -- BoxCollider ---------------------------------------------------------
850
851    #[test]
852    fn a_box_colliders_bounds_are_its_centre_expanded_by_its_half_extents() {
853        let b = BoxCollider::new(DVec3::ZERO, DVec3::splat(2.0));
854        let aabb = b.aabb();
855        assert_eq!(aabb.min, DVec3::splat(-2.0));
856        assert_eq!(aabb.max, DVec3::splat(2.0));
857    }
858
859    // -- Capsule -------------------------------------------------------------
860
861    #[test]
862    fn a_capsules_bounds_reach_a_radius_past_each_cap_and_a_radius_sideways() {
863        let c = Capsule::new(DVec3::ZERO, 0.5, 1.0);
864        let aabb = c.aabb();
865        assert_eq!(aabb.min, DVec3::new(-0.5, -1.5, -0.5));
866        assert_eq!(aabb.max, DVec3::new(0.5, 1.5, 0.5));
867    }
868
869    #[test]
870    fn a_capsules_end_points_exclude_the_radius_its_caps_add() {
871        let c = Capsule::new(DVec3::new(0.0, 5.0, 0.0), 0.5, 2.0);
872        assert_eq!(c.top(), DVec3::new(0.0, 7.0, 0.0));
873        assert_eq!(c.bottom(), DVec3::new(0.0, 3.0, 0.0));
874    }
875
876    // -- LyingCapsule --------------------------------------------------------
877
878    /// **The yaw convention, written out**: zero faces `-Z`, and each quarter
879    /// turn carries the facing a right-handed quarter turn about `+Y` — to
880    /// `-X`, `+Z`, then `+X` — with the feet the length behind the head.
881    #[test]
882    fn a_lying_capsules_feet_lie_behind_its_head_at_each_quarter_turn() {
883        use std::f64::consts::{FRAC_PI_2, PI};
884        let head = DVec3::new(1.0, 2.0, 3.0);
885        for (yaw, facing) in [
886            (0.0, DVec3::NEG_Z),
887            (FRAC_PI_2, DVec3::NEG_X),
888            (PI, DVec3::Z),
889            (3.0 * FRAC_PI_2, DVec3::X),
890        ] {
891            let capsule = LyingCapsule::new(head, yaw, 0.3, 1.6);
892            assert!(
893                (capsule.facing() - facing).length() < 1e-12,
894                "yaw {yaw} faces {:?}, not {facing:?}",
895                capsule.facing()
896            );
897            let feet = head - facing * 1.6;
898            assert!(
899                (capsule.feet() - feet).length() < 1e-12,
900                "yaw {yaw} puts the feet at {:?}, not {feet:?}",
901                capsule.feet()
902            );
903        }
904    }
905
906    /// **The facing is `-Z` turned by the engine's own rotation about `+Y`**,
907    /// at angles that are not quarter turns too — the claim the type's
908    /// documentation makes about `rotation_from_scaled_axis`.
909    #[test]
910    fn a_lying_capsule_faces_where_the_engines_yaw_rotation_turns_minus_z() {
911        for yaw in [-2.5, -0.7, 0.3, 1.1, 4.0] {
912            let turned = crate::rotation_from_scaled_axis(DVec3::Y * yaw) * DVec3::NEG_Z;
913            let facing = LyingCapsule::new(DVec3::ZERO, yaw, 0.3, 1.6).facing();
914            assert!(
915                (facing - turned).length() < 1e-12,
916                "yaw {yaw}: {facing:?} against {turned:?}"
917            );
918        }
919    }
920
921    #[test]
922    fn a_lying_capsules_bounds_reach_a_radius_past_its_head_and_feet() {
923        let c = LyingCapsule::new(DVec3::new(0.0, 0.5, 0.0), 0.0, 0.5, 1.5);
924        let aabb = c.aabb();
925        assert!((aabb.min - DVec3::new(-0.5, 0.0, -0.5)).length() < 1e-12);
926        assert!((aabb.max - DVec3::new(0.5, 1.0, 2.0)).length() < 1e-12);
927    }
928
929    /// **The pitch convention, written out**: a positive pitch sine puts the
930    /// head end higher than the feet, the feet stay the length behind the head
931    /// along the core, and a pitch of zero is the level capsule to the bit.
932    #[test]
933    fn a_positive_pitch_puts_the_head_above_the_feet_a_length_along_the_core() {
934        let head = DVec3::new(1.0, 2.0, 3.0);
935        let level = LyingCapsule::new(head, 0.0, 0.3, 1.6);
936        assert_eq!(level.with_pitch_sine(0.0).feet(), level.feet());
937        assert_eq!(level.feet(), head + DVec3::Z * 1.6);
938
939        let raised = level.with_pitch_sine(0.6);
940        let feet = raised.feet();
941        assert!(
942            (feet - (head + DVec3::new(0.0, -0.6 * 1.6, 0.8 * 1.6))).length() < 1e-12,
943            "head up by a pitch sine of 0.6 puts the feet at {feet:?}"
944        );
945        assert!(((head - feet).length() - 1.6).abs() < 1e-12);
946        assert!((raised.axis().length() - 1.0).abs() < 1e-12);
947
948        let lowered = level.with_pitch_sine(-0.6);
949        assert!(
950            lowered.feet().y > head.y,
951            "a negative pitch raises the feet"
952        );
953        assert_eq!(lowered.facing(), raised.facing(), "the yaw alone faces");
954    }
955}