Skip to main content

rayengine_core/
physics.rs

1//! Predictable arcade physics with continuous translation and no rotation.
2//!
3//! Worlds are game-owned and stepped explicitly from the fixed update. The
4//! legacy [`crate::collision::Body2D`] and [`crate::collision::Body3D`] remain
5//! independent. See [`crate::physics::guide`] for setup and solver limits.
6
7mod geometry;
8mod grid;
9mod solver;
10
11use crate::collision::{Aabb2, Aabb3};
12use crate::events::Events;
13use crate::time::Tick;
14use geometry::Shape;
15use glam::{Vec2, Vec3};
16use std::collections::{BTreeMap, BTreeSet};
17
18/// Checked usage guide, also available without the rendering SDK.
19#[doc = include_str!("../docs/physics.md")]
20pub mod guide {}
21
22/// Stable, never-reused world collider identity.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
24pub struct BodyId(pub u64);
25
26/// Motion authority. Only dynamic bodies receive forces and collision response.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum BodyKind {
29    /// Immovable solid; velocity is ignored.
30    Static,
31    /// Game-driven velocity; pushes dynamics and carries riders, ignoring solids.
32    Kinematic,
33    /// Integrated and separated using inverse mass.
34    Dynamic,
35}
36
37/// Symmetric collision filtering, shared by bodies, static solids and triggers.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub struct CollisionFilter {
40    /// Bitset of layers this collider belongs to.
41    pub layers: u32,
42    /// Bitset of layers this collider accepts.
43    pub mask: u32,
44}
45impl Default for CollisionFilter {
46    fn default() -> Self {
47        Self {
48            layers: 1,
49            mask: u32::MAX,
50        }
51    }
52}
53impl CollisionFilter {
54    /// Both masks must accept the other collider's layers.
55    pub fn allows(self, other: Self) -> bool {
56        self.mask & other.layers != 0 && other.mask & self.layers != 0
57    }
58}
59
60/// Trigger transition at a fixed tick boundary. A swept pass emits enter/exit.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum TriggerPhase {
63    /// Pair began overlapping, or crossed the trigger during this tick.
64    Enter,
65    /// Pair remained overlapping at consecutive boundaries.
66    Stay,
67    /// Pair stopped overlapping, including removal or filter changes.
68    Exit,
69}
70/// Typed trigger event. Queues append until the game clears or drains them.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub struct TriggerEvent {
73    /// Trigger identity.
74    pub trigger: BodyId,
75    /// Other collider identity (including another trigger).
76    pub other: BodyId,
77    /// Transition kind.
78    pub phase: TriggerPhase,
79}
80
81/// Bounded solver work and any unconsumed simulation time.
82#[derive(Clone, Copy, Debug, Default, PartialEq)]
83pub struct StepReport {
84    /// Number of continuous solid contacts and overlap repairs processed.
85    pub contacts: usize,
86    /// Time discarded if the 256 continuous-contact/repair budget was exhausted.
87    /// Spawn and final overlap repairs have separate bounded passes.
88    pub dropped_time: f32,
89    /// Whether the bounded depenetration pass left any solid overlaps.
90    pub unresolved_overlaps: bool,
91}
92
93#[derive(Clone, Copy)]
94pub(super) struct Contact<const N: usize> {
95    normal: [f32; N],
96    depth: f32,
97}
98
99macro_rules! dimension {
100    ($n:literal, $vec:ident, $aabb:ident, $shape:ident, $round_variant:ident, $body:ident, $world:ident, $grid:ident, $penetration:ident) => {
101        /// Local centered collision geometry, with no rotation.
102        #[derive(Clone, Copy, Debug, PartialEq)]
103        pub enum $shape {
104            /// Axis-aligned box with strictly positive half dimensions.
105            Box {
106                /// Half dimensions in world units.
107                half_size: $vec,
108            },
109            /// Round shape with a strictly positive radius.
110            $round_variant {
111                /// Radius in world units.
112                radius: f32,
113            },
114        }
115        impl $shape {
116            /// Box from full dimensions. Panics for nonfinite/nonpositive sizes.
117            pub fn box_shape(size: $vec) -> Self {
118                let shape = Self::Box {
119                    half_size: size * 0.5,
120                };
121                assert!(shape.internal().valid());
122                shape
123            }
124            /// Round shape. Panics for nonfinite/nonpositive radii.
125            pub fn round(radius: f32) -> Self {
126                assert!(radius.is_finite() && radius > 0.0);
127                Self::$round_variant { radius }
128            }
129            fn internal(self) -> Shape<$n> {
130                match self {
131                    Self::Box { half_size } => Shape::Box(half_size.to_array()),
132                    Self::$round_variant { radius } => Shape::Round(radius),
133                }
134            }
135            /// World bounds for a finite center. Panics for invalid geometry.
136            pub fn bounds(self, center: $vec) -> $aabb {
137                assert!(center.is_finite() && self.internal().valid());
138                let (min, max) = self.internal().bounds(center.to_array());
139                $aabb {
140                    min: $vec::from_array(min),
141                    max: $vec::from_array(max),
142                }
143            }
144            /// Positive penetration. Normal moves `self` away from `other`.
145            /// Coincident centers use the positive X direction as a stable tie.
146            pub fn overlap(
147                self,
148                center: $vec,
149                other: Self,
150                other_center: $vec,
151            ) -> Option<$penetration> {
152                assert!(
153                    center.is_finite()
154                        && other_center.is_finite()
155                        && self.internal().valid()
156                        && other.internal().valid()
157                );
158                geometry::overlap(
159                    self.internal(),
160                    center.to_array(),
161                    other.internal(),
162                    other_center.to_array(),
163                )
164                .map(|c| $penetration {
165                    normal: $vec::from_array(c.normal),
166                    depth: c.depth,
167                })
168            }
169        }
170        /// Minimum translation needed to remove a positive overlap.
171        #[derive(Clone, Copy, Debug, PartialEq)]
172        pub struct $penetration {
173            /// Unit direction from the second shape toward the first.
174            pub normal: $vec,
175            /// Translation distance along the normal.
176            pub depth: f32,
177        }
178        /// World collider, including solids and nonblocking trigger volumes.
179        #[derive(Clone, Copy, Debug, PartialEq)]
180        pub struct $body {
181            /// World-space center.
182            pub position: $vec,
183            /// Local collision geometry.
184            pub shape: $shape,
185            /// Intrinsic velocity, excluding moving-platform carry.
186            pub velocity: $vec,
187            /// Static, kinematic or dynamic motion authority.
188            pub kind: BodyKind,
189            /// Layer membership and symmetric acceptance mask.
190            pub filter: CollisionFilter,
191            /// Nonblocking volume that generates typed trigger events.
192            pub is_trigger: bool,
193            /// Positive mass; affects dynamic/dynamic push-apart and impulses.
194            pub mass: f32,
195            /// Optional per-body acceleration, in world units per second squared.
196            pub gravity: Option<$vec>,
197            /// Bounce coefficient in `[0, 1]`. Pair response uses the maximum.
198            pub restitution: f32,
199            /// Contact friction in `[0, 1]`; scales the normal impulse budget.
200            pub friction: f32,
201            /// Nonnegative drag per second, applied as `velocity / (1 + drag * dt)`.
202            pub drag: f32,
203            /// Optional nonnegative intrinsic speed cap, applied after forces.
204            /// Collision impulses may exceed it until the next tick.
205            pub max_speed: Option<f32>,
206            /// Contact with a solid below (Y down in 2D, Y up in 3D).
207            pub grounded: bool,
208        }
209        impl $body {
210            /// Stationary dynamic collider with mass one and no automatic gravity.
211            pub fn new(position: $vec, shape: $shape) -> Self {
212                assert!(position.is_finite() && shape.internal().valid());
213                Self {
214                    position,
215                    shape,
216                    velocity: $vec::ZERO,
217                    kind: BodyKind::Dynamic,
218                    filter: CollisionFilter::default(),
219                    is_trigger: false,
220                    mass: 1.0,
221                    gravity: None,
222                    restitution: 0.0,
223                    friction: 0.0,
224                    drag: 0.0,
225                    max_speed: None,
226                    grounded: false,
227                }
228            }
229            /// Current conservative world bounds.
230            pub fn bounds(&self) -> $aabb {
231                self.shape.bounds(self.position)
232            }
233        }
234        /// Reusable uniform-grid broadphase with stable, sorted query results.
235        /// Touching bounds are candidates; callers perform their own narrowphase.
236        #[derive(Debug)]
237        pub struct $grid {
238            inner: grid::Grid<$n>,
239        }
240        impl $grid {
241            /// Creates a grid with a finite positive cell width.
242            pub fn new(cell_size: f32) -> Self {
243                Self {
244                    inner: grid::Grid::new(cell_size),
245                }
246            }
247            /// Inserts or replaces caller-owned identity and bounds.
248            /// Panics for nonfinite/reversed bounds.
249            pub fn insert(&mut self, id: u64, bounds: $aabb) {
250                self.inner
251                    .insert(id, bounds.min.to_array(), bounds.max.to_array());
252            }
253            /// Removes an identity, if present.
254            pub fn remove(&mut self, id: u64) {
255                self.inner.remove(id);
256            }
257            /// Removes all entries.
258            pub fn clear(&mut self) {
259                self.inner.clear();
260            }
261            /// Sorted unique IDs whose bounds touch or overlap the query.
262            /// Huge objects and queries use a bounded-storage linear fallback.
263            pub fn query(&self, bounds: $aabb) -> Vec<u64> {
264                self.inner
265                    .query(bounds.min.to_array(), bounds.max.to_array())
266            }
267        }
268        /// Small deterministic arcade world. Own it in game state and call
269        /// `step(ctx.tick, &mut events)` exactly once per fixed update.
270        #[derive(Debug)]
271        pub struct $world {
272            bodies: BTreeMap<BodyId, $body>,
273            next_id: u64,
274            overlaps: BTreeSet<(BodyId, BodyId)>,
275            grid: grid::Grid<$n>,
276        }
277        impl $world {
278            /// Creates an empty world. Cell size should approximate typical bodies.
279            pub fn new(cell_size: f32) -> Self {
280                Self {
281                    bodies: BTreeMap::new(),
282                    next_id: 0,
283                    overlaps: BTreeSet::new(),
284                    grid: grid::Grid::new(cell_size),
285                }
286            }
287            /// Inserts a body and returns an identity that is never reused.
288            pub fn insert(&mut self, body: $body) -> BodyId {
289                let id = BodyId(self.next_id);
290                self.next_id = self
291                    .next_id
292                    .checked_add(1)
293                    .expect("physics identity exhausted");
294                self.bodies.insert(id, body);
295                id
296            }
297            /// Removes a collider. Active trigger pairs exit on the next step.
298            pub fn remove(&mut self, id: BodyId) -> Option<$body> {
299                self.bodies.remove(&id)
300            }
301            /// Reads a collider by stable identity.
302            pub fn body(&self, id: BodyId) -> Option<&$body> {
303                self.bodies.get(&id)
304            }
305            /// Edits a collider. Inputs are validated at the next step.
306            pub fn body_mut(&mut self, id: BodyId) -> Option<&mut $body> {
307                self.bodies.get_mut(&id)
308            }
309            /// All colliders in stable identity order.
310            pub fn iter(&self) -> impl Iterator<Item = (BodyId, &$body)> {
311                self.bodies.iter().map(|(id, b)| (*id, b))
312            }
313            /// Advances one fixed tick; appends trigger transitions to `events`.
314            /// Panics for nonfinite/invalid body properties or negative/nonfinite dt.
315            /// Kinematic bodies follow velocity even through static geometry.
316            pub fn step(&mut self, tick: Tick, events: &mut Events<TriggerEvent>) -> StepReport {
317                let mut nodes: Vec<_> = self
318                    .bodies
319                    .iter()
320                    .map(|(id, b)| solver::Node {
321                        id: *id,
322                        position: b.position.to_array(),
323                        shape: b.shape.internal(),
324                        velocity: b.velocity.to_array(),
325                        kind: b.kind,
326                        filter: b.filter,
327                        trigger: b.is_trigger,
328                        mass: b.mass,
329                        gravity: b.gravity.map(|g| g.to_array()),
330                        restitution: b.restitution,
331                        friction: b.friction,
332                        drag: b.drag,
333                        max_speed: b.max_speed,
334                        grounded: false,
335                        was_grounded: b.grounded,
336                        touched_ground: false,
337                        carry: [0.0; $n],
338                    })
339                    .collect();
340                let report = solver::step(
341                    &mut nodes,
342                    tick.dt,
343                    &mut self.grid,
344                    &mut self.overlaps,
345                    events,
346                );
347                for node in nodes {
348                    let b = self.bodies.get_mut(&node.id).unwrap();
349                    b.position = $vec::from_array(node.position);
350                    b.velocity = $vec::from_array(node.velocity);
351                    b.grounded = node.grounded;
352                }
353                report
354            }
355        }
356    };
357}
358dimension!(
359    2,
360    Vec2,
361    Aabb2,
362    Shape2D,
363    Circle,
364    PhysicsBody2D,
365    PhysicsWorld2D,
366    UniformGrid2D,
367    Penetration2D
368);
369dimension!(
370    3,
371    Vec3,
372    Aabb3,
373    Shape3D,
374    Sphere,
375    PhysicsBody3D,
376    PhysicsWorld3D,
377    UniformGrid3D,
378    Penetration3D
379);
380
381#[cfg(test)]
382mod tests;
383
384// Used by the independent swept character API before its axis sweeps.
385pub(crate) fn depenetrate_box<const N: usize>(
386    position: &mut [f32; N],
387    half: [f32; N],
388    solids: impl Iterator<Item = ([f32; N], [f32; N])> + Clone,
389) {
390    for _ in 0..16 {
391        let mut changed = false;
392        for (min, max) in solids.clone() {
393            let center = std::array::from_fn(|i| (min[i] + max[i]) * 0.5);
394            let extent = std::array::from_fn(|i| (max[i] - min[i]) * 0.5);
395            if let Some(contact) =
396                geometry::overlap(Shape::Box(half), *position, Shape::Box(extent), center)
397            {
398                *position = geometry::outward(*position, contact.normal, contact.depth + 1e-5);
399                changed = true;
400            }
401        }
402        if !changed {
403            break;
404        }
405    }
406}