Skip to main content

euv_core/game/engine3d/physics/
impl.rs

1use super::*;
2
3/// Constructors and bounding-box helpers for `RigidBody3D`.
4impl RigidBody3D {
5    /// Creates a dynamic 3D rigid body with given mass, position, and box half-extents.
6    ///
7    /// # Arguments
8    ///
9    /// - `Vec3` - Initial center position.
10    /// - `Vec3` - Box half-extents `(hx, hy, hz)`.
11    /// - `f32` - Positive mass in kilograms.
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Dynamic rigid body.
16    #[must_use]
17    pub fn dynamic_box(position: Vec3, half_extents: Vec3, mass: f32) -> Self {
18        Self {
19            position,
20            velocity: Vec3::zero(),
21            half_extents,
22            inv_mass: 1.0 / mass.max(0.01),
23            restitution: 0.35,
24            linear_damping: 0.04,
25            grounded: false,
26        }
27    }
28
29    /// Creates a static immovable 3D box collider.
30    ///
31    /// # Arguments
32    ///
33    /// - `Vec3` - Center position.
34    /// - `Vec3` - Box half-extents `(hx, hy, hz)`.
35    ///
36    /// # Returns
37    ///
38    /// - `Self` - Static rigid body (`inv_mass = 0.0`).
39    #[must_use]
40    pub fn static_box(position: Vec3, half_extents: Vec3) -> Self {
41        Self {
42            position,
43            velocity: Vec3::zero(),
44            half_extents,
45            inv_mass: 0.0,
46            restitution: 0.25,
47            linear_damping: 0.0,
48            grounded: true,
49        }
50    }
51
52    /// Computes this body's world-space `Aabb3D`.
53    ///
54    /// # Arguments
55    ///
56    /// - `&Self` - Body reference.
57    ///
58    /// # Returns
59    ///
60    /// - `Aabb3D` - World-space bounding box.
61    #[must_use]
62    pub fn world_aabb(&self) -> Aabb3D {
63        let p: Vec3 = self.get_position();
64        let h: Vec3 = self.get_half_extents();
65        Aabb3D::new(p.sub(h), p.add(h))
66    }
67
68    /// Applies an instantaneous linear impulse to a dynamic rigid body.
69    ///
70    /// # Arguments
71    ///
72    /// - `&Self` - Mutable body reference.
73    /// - `Vec3` - Linear impulse vector in `N*s`.
74    pub fn apply_impulse(&mut self, impulse: Vec3) {
75        let inv_m: f32 = self.get_inv_mass();
76        if inv_m > 0.0 {
77            let next_v: Vec3 = self.get_velocity().add(impulse.scale(inv_m));
78            self.set_velocity(next_v);
79        }
80    }
81}
82
83/// Default Earth-gravity 3D physics world.
84impl Default for PhysicsWorld3D {
85    /// Creates an empty `PhysicsWorld3D` with `-9.81 m/s^2` gravity and ground at `y = 0.0`.
86    ///
87    /// # Returns
88    ///
89    /// - `Self` - Ready 3D physics world.
90    fn default() -> Self {
91        Self {
92            gravity: Vec3::new(0.0, -9.81, 0.0),
93            ground_y: 0.0,
94            bodies: Vec::new(),
95        }
96    }
97}
98
99/// Rigid-body integration, AABB collision resolution, and raycasting for `PhysicsWorld3D`.
100impl PhysicsWorld3D {
101    /// Adds a `RigidBody3D` to the simulation and returns its handle index.
102    ///
103    /// # Arguments
104    ///
105    /// - `&Self` - Mutable physics world.
106    /// - `RigidBody3D` - Body to insert.
107    ///
108    /// # Returns
109    ///
110    /// - `usize` - Body index.
111    pub fn add_body(&mut self, body: RigidBody3D) -> usize {
112        let idx: usize = self.get_bodies().len();
113        self.get_mut_bodies().push(body);
114        idx
115    }
116
117    /// Advances all rigid bodies by `dt` seconds with gravity, ground collisions, and pairwise AABB impulses.
118    ///
119    /// # Arguments
120    ///
121    /// - `&Self` - Mutable physics world.
122    /// - `f32` - Timestep in seconds.
123    ///
124    /// # Returns
125    ///
126    /// - `usize` - Number of collisions resolved during this step.
127    pub fn step(&mut self, dt: f32) -> usize {
128        let step_dt: f32 = dt.clamp(0.0, 0.1);
129        let gravity: Vec3 = self.get_gravity();
130        let ground_y: f32 = self.get_ground_y();
131        let mut collisions: usize = 0;
132        for body in self.get_mut_bodies().iter_mut() {
133            let inv_m: f32 = body.get_inv_mass();
134            if inv_m <= 0.0 {
135                continue;
136            }
137            let damp: f32 = (1.0 - body.get_linear_damping() * step_dt).clamp(0.0, 1.0);
138            let mut vel: Vec3 = body.get_velocity().add(gravity.scale(step_dt)).scale(damp);
139            let mut pos: Vec3 = body.get_position().add(vel.scale(step_dt));
140            let min_y: f32 = ground_y + body.get_half_extents().get_y();
141            let mut grounded: bool = false;
142            if pos.get_y() <= min_y {
143                pos.set_y(min_y);
144                if vel.get_y() < 0.0 {
145                    vel.set_y(-vel.get_y() * body.get_restitution());
146                    if vel.get_y().abs() < 0.25 {
147                        vel.set_y(0.0);
148                    }
149                    vel.set_x(vel.get_x() * 0.92);
150                    vel.set_z(vel.get_z() * 0.92);
151                    collisions += 1;
152                }
153                grounded = true;
154            }
155            body.set_position(pos);
156            body.set_velocity(vel);
157            body.set_grounded(grounded);
158        }
159        let count: usize = self.get_bodies().len();
160        for i in 0..count {
161            for j in (i + 1)..count {
162                let a: RigidBody3D = self.get_bodies()[i];
163                let b: RigidBody3D = self.get_bodies()[j];
164                let inv_sum: f32 = a.get_inv_mass() + b.get_inv_mass();
165                if inv_sum <= 0.0 {
166                    continue;
167                }
168                let delta: Vec3 = b.get_position().sub(a.get_position());
169                let ox: f32 = a.get_half_extents().get_x() + b.get_half_extents().get_x()
170                    - delta.get_x().abs();
171                let oy: f32 = a.get_half_extents().get_y() + b.get_half_extents().get_y()
172                    - delta.get_y().abs();
173                let oz: f32 = a.get_half_extents().get_z() + b.get_half_extents().get_z()
174                    - delta.get_z().abs();
175                if ox <= 0.0 || oy <= 0.0 || oz <= 0.0 {
176                    continue;
177                }
178                let (normal, pen): (Vec3, f32) = if ox <= oy && ox <= oz {
179                    let s: f32 = if delta.get_x() < 0.0 { -1.0 } else { 1.0 };
180                    (Vec3::new(s, 0.0, 0.0), ox)
181                } else if oy <= oz {
182                    let s: f32 = if delta.get_y() < 0.0 { -1.0 } else { 1.0 };
183                    (Vec3::new(0.0, s, 0.0), oy)
184                } else {
185                    let s: f32 = if delta.get_z() < 0.0 { -1.0 } else { 1.0 };
186                    (Vec3::new(0.0, 0.0, s), oz)
187                };
188                let corr: Vec3 = normal.scale(pen / inv_sum);
189                let mut a_pos: Vec3 = a.get_position();
190                let mut b_pos: Vec3 = b.get_position();
191                a_pos = a_pos.sub(corr.scale(a.get_inv_mass()));
192                b_pos = b_pos.add(corr.scale(b.get_inv_mass()));
193                let rel_v: Vec3 = b.get_velocity().sub(a.get_velocity());
194                let vn: f32 = rel_v.dot(normal);
195                let mut a_vel: Vec3 = a.get_velocity();
196                let mut b_vel: Vec3 = b.get_velocity();
197                if vn < 0.0 {
198                    let rest: f32 = a.get_restitution().min(b.get_restitution());
199                    let j_imp: f32 = -(1.0 + rest) * vn / inv_sum;
200                    let imp: Vec3 = normal.scale(j_imp);
201                    a_vel = a_vel.sub(imp.scale(a.get_inv_mass()));
202                    b_vel = b_vel.add(imp.scale(b.get_inv_mass()));
203                }
204                let bodies_mut: &mut [RigidBody3D] = self.get_mut_bodies().as_mut_slice();
205                bodies_mut[i].set_position(a_pos);
206                bodies_mut[i].set_velocity(a_vel);
207                bodies_mut[j].set_position(b_pos);
208                bodies_mut[j].set_velocity(b_vel);
209                collisions += 1;
210            }
211        }
212        collisions
213    }
214
215    /// Casts a `Ray3D` against all 3D rigid bodies up to `max_distance` and returns the closest hit.
216    ///
217    /// # Arguments
218    ///
219    /// - `&Self` - Physics world reference.
220    /// - `&Ray3D` - Query ray.
221    /// - `f32` - Maximum cast distance in meters.
222    ///
223    /// # Returns
224    ///
225    /// - `Option<RayHitPhysics3D>` - Closest hit body and contact position if any.
226    #[must_use]
227    pub fn raycast(&self, ray: &Ray3D, max_distance: f32) -> Option<RayHitPhysics3D> {
228        let mut best: Option<RayHitPhysics3D> = None;
229        let mut best_t: f32 = max_distance.max(0.0);
230        for (idx, body) in self.get_bodies().iter().enumerate() {
231            let aabb: Aabb3D = body.world_aabb();
232            let t: f32 =
233                aabb.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), 0.001, best_t);
234            if t.is_finite() && t < best_t {
235                best_t = t;
236                let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
237                best = Some(RayHitPhysics3D::new(idx, t, pt));
238            }
239        }
240        best
241    }
242}