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            angular_velocity: Vec3::zero(),
22            half_extents,
23            inv_mass: 1.0 / mass.max(0.01),
24            restitution: 0.35,
25            friction: 0.45,
26            linear_damping: 0.04,
27            sleep_timer: 0.0,
28            sleeping: false,
29            grounded: false,
30        }
31    }
32
33    /// Creates a static immovable 3D box collider.
34    ///
35    /// # Arguments
36    ///
37    /// - `Vec3` - Center position.
38    /// - `Vec3` - Box half-extents `(hx, hy, hz)`.
39    ///
40    /// # Returns
41    ///
42    /// - `Self` - Static rigid body (`inv_mass = 0.0`).
43    #[must_use]
44    pub fn static_box(position: Vec3, half_extents: Vec3) -> Self {
45        Self {
46            position,
47            velocity: Vec3::zero(),
48            angular_velocity: Vec3::zero(),
49            half_extents,
50            inv_mass: 0.0,
51            restitution: 0.25,
52            friction: 0.55,
53            linear_damping: 0.0,
54            sleep_timer: 0.0,
55            sleeping: true,
56            grounded: true,
57        }
58    }
59
60    /// Computes this body's world-space `AxisAlignedBox3D`.
61    ///
62    /// # Arguments
63    ///
64    /// - `&Self` - Body reference.
65    ///
66    /// # Returns
67    ///
68    /// - `AxisAlignedBox3D` - World-space bounding box.
69    #[must_use]
70    pub fn world_bounds(&self) -> AxisAlignedBox3D {
71        let vec_value: Vec3 = self.get_position();
72        let height_val: Vec3 = self.get_half_extents();
73        AxisAlignedBox3D::new(vec_value.sub(height_val), vec_value.add(height_val))
74    }
75
76    /// Wakes a sleeping dynamic rigid body so it resumes simulation on the next step.
77    pub fn wake(&mut self) {
78        if self.get_inv_mass() > 0.0 {
79            self.set_sleeping(false);
80            self.set_sleep_timer(0.0);
81        }
82    }
83
84    /// Applies an instantaneous linear impulse to a dynamic rigid body.
85    ///
86    /// # Arguments
87    ///
88    /// - `Vec3` - Linear impulse vector in `N*s`.
89    pub fn apply_impulse(&mut self, impulse: Vec3) {
90        let inv_m: f32 = self.get_inv_mass();
91        if inv_m > 0.0 {
92            self.wake();
93            let next_v: Vec3 = self.get_velocity().add(impulse.scale(inv_m));
94            self.set_velocity(next_v);
95        }
96    }
97}
98
99/// Default Earth-gravity 3D physics world.
100impl Default for PhysicsWorld3D {
101    /// Creates an empty `PhysicsWorld3D` with `-9.81 m/s^2` gravity and ground at `y = 0.0`.
102    ///
103    /// # Returns
104    ///
105    /// - `Self` - Ready 3D physics world.
106    fn default() -> Self {
107        Self {
108            gravity: Vec3::new(0.0, -9.81, 0.0),
109            ground_y: 0.0,
110            bodies: Vec::new(),
111            hash_heads: Vec::new(),
112            hash_next: Vec::new(),
113            hash_body: Vec::new(),
114            touched_buckets: Vec::new(),
115            pair_scratch: Vec::new(),
116        }
117    }
118}
119
120/// Rigid-body integration, spatial-hash broadphase, axis-aligned bounding box collision resolution, and raycasting for `PhysicsWorld3D`.
121impl PhysicsWorld3D {
122    /// Computes the bucket index in `0..bucket_count` for integer 3D grid cell `(cx, cy, cz)`.
123    ///
124    /// # Arguments
125    ///
126    /// - `i32` - Cell X coordinate.
127    /// - `i32` - Cell Y coordinate.
128    /// - `i32` - Cell Z coordinate.
129    /// - `usize` - Power-of-two bucket mask (`bucket_count - 1`).
130    ///
131    /// # Returns
132    ///
133    /// - `usize` - Hash bucket index.
134    #[inline(always)]
135    #[must_use]
136    fn hash_cell(cx: i32, cy: i32, cz: i32, mask: usize) -> usize {
137        let height_val: u32 = (cx.wrapping_mul(73_856_093) as u32)
138            ^ (cy.wrapping_mul(19_349_663) as u32)
139            ^ (cz.wrapping_mul(83_492_791) as u32);
140        (height_val as usize) & mask
141    }
142
143    /// Resolves a single candidate rigid-body pair `(i, j)` in place and returns `true` if colliding.
144    ///
145    /// # Arguments
146    ///
147    /// - `&mut [RigidBody3D]` - Mutable rigid-body slice.
148    /// - `usize` - First body index.
149    /// - `usize` - Second body index.
150    ///
151    /// # Returns
152    ///
153    /// - `bool` - `true` when an overlap was resolved.
154    #[inline(always)]
155    fn resolve_body_pair(
156        bodies: &mut [RigidBody3D],
157        item_index: usize,
158        inner_index: usize,
159    ) -> bool {
160        let alpha_val: RigidBody3D = bodies[item_index];
161        let blue_val: RigidBody3D = bodies[inner_index];
162        let alpha_inactive: bool = alpha_val.get_inv_mass() <= 0.0 || alpha_val.get_sleeping();
163        let blue_inactive: bool = blue_val.get_inv_mass() <= 0.0 || blue_val.get_sleeping();
164        if alpha_inactive && blue_inactive {
165            return false;
166        }
167        let inv_sum: f32 = alpha_val.get_inv_mass() + blue_val.get_inv_mass();
168        if inv_sum <= 0.0 {
169            return false;
170        }
171        let delta: Vec3 = blue_val.get_position().sub(alpha_val.get_position());
172        let ox: f32 = alpha_val.get_half_extents().get_x() + blue_val.get_half_extents().get_x()
173            - delta.get_x().abs();
174        let oy: f32 = alpha_val.get_half_extents().get_y() + blue_val.get_half_extents().get_y()
175            - delta.get_y().abs();
176        let oz: f32 = alpha_val.get_half_extents().get_z() + blue_val.get_half_extents().get_z()
177            - delta.get_z().abs();
178        if ox <= 0.0 || oy <= 0.0 || oz <= 0.0 {
179            return false;
180        }
181        let (normal, pen): (Vec3, f32) = if ox <= oy && ox <= oz {
182            let source_val: f32 = if delta.get_x() < 0.0 { -1.0 } else { 1.0 };
183            (Vec3::new(source_val, 0.0, 0.0), ox)
184        } else if oy <= oz {
185            let scale_val: f32 = if delta.get_y() < 0.0 { -1.0 } else { 1.0 };
186            (Vec3::new(0.0, scale_val, 0.0), oy)
187        } else {
188            let series_item: f32 = if delta.get_z() < 0.0 { -1.0 } else { 1.0 };
189            (Vec3::new(0.0, 0.0, series_item), oz)
190        };
191        let corr: Vec3 = normal.scale(pen / inv_sum);
192        let a_pos: Vec3 = alpha_val
193            .get_position()
194            .sub(corr.scale(alpha_val.get_inv_mass()));
195        let b_pos: Vec3 = blue_val
196            .get_position()
197            .add(corr.scale(blue_val.get_inv_mass()));
198        let rel_v: Vec3 = blue_val.get_velocity().sub(alpha_val.get_velocity());
199        let vn: f32 = rel_v.dot(normal);
200        let mut a_vel: Vec3 = alpha_val.get_velocity();
201        let mut b_vel: Vec3 = blue_val.get_velocity();
202        let mut a_ang: Vec3 = alpha_val.get_angular_velocity();
203        let mut b_ang: Vec3 = blue_val.get_angular_velocity();
204        if vn < 0.0 {
205            let rest: f32 = alpha_val.get_restitution().min(blue_val.get_restitution());
206            let j_imp: f32 = -(1.0 + rest) * vn / inv_sum;
207            let imp: Vec3 = normal.scale(j_imp);
208            a_vel = a_vel.sub(imp.scale(alpha_val.get_inv_mass()));
209            b_vel = b_vel.add(imp.scale(blue_val.get_inv_mass()));
210            let tangent_raw: Vec3 = rel_v.sub(normal.scale(vn));
211            let tangent_len_sq: f32 = tangent_raw.length_sq();
212            if tangent_len_sq > 1e-8 {
213                let tangent: Vec3 = tangent_raw.scale(1.0 / tangent_len_sq.sqrt());
214                let vt: f32 = rel_v.dot(tangent);
215                let combined_friction: f32 =
216                    (alpha_val.get_friction() * blue_val.get_friction()).sqrt();
217                let jt: f32 =
218                    (-vt / inv_sum).clamp(-j_imp * combined_friction, j_imp * combined_friction);
219                let friction_imp: Vec3 = tangent.scale(jt);
220                a_vel = a_vel.sub(friction_imp.scale(alpha_val.get_inv_mass()));
221                b_vel = b_vel.add(friction_imp.scale(blue_val.get_inv_mass()));
222                let spin_axis: Vec3 = normal.cross(friction_imp);
223                a_ang = a_ang.sub(spin_axis.scale(alpha_val.get_inv_mass() * 0.25));
224                b_ang = b_ang.add(spin_axis.scale(blue_val.get_inv_mass() * 0.25));
225            }
226        }
227        bodies[item_index].set_position(a_pos);
228        bodies[item_index].set_velocity(a_vel);
229        bodies[item_index].set_angular_velocity(a_ang);
230        bodies[inner_index].set_position(b_pos);
231        bodies[inner_index].set_velocity(b_vel);
232        bodies[inner_index].set_angular_velocity(b_ang);
233        if alpha_val.get_inv_mass() > 0.0 {
234            bodies[item_index].wake();
235        }
236        if blue_val.get_inv_mass() > 0.0 {
237            bodies[inner_index].wake();
238        }
239        true
240    }
241
242    /// Returns the number of currently awake dynamic rigid bodies active in the simulation.
243    ///
244    /// # Returns
245    ///
246    /// - `usize` - Count of dynamic bodies not in the sleeping island state.
247    #[must_use]
248    pub fn awake_body_count(&self) -> usize {
249        self.get_bodies()
250            .iter()
251            .filter(|body: &&RigidBody3D| body.get_inv_mass() > 0.0 && !body.get_sleeping())
252            .count()
253    }
254
255    /// Adds a `RigidBody3D` to the simulation and returns its handle index.
256    ///
257    /// # Arguments
258    ///
259    /// - `&Self` - Mutable physics world.
260    /// - `RigidBody3D` - Body to insert.
261    ///
262    /// # Returns
263    ///
264    /// - `usize` - Body index.
265    pub fn add_body(&mut self, body: RigidBody3D) -> usize {
266        let idx: usize = self.get_bodies().len();
267        self.get_mut_bodies().push(body);
268        idx
269    }
270
271    /// Advances all rigid bodies by `dt` seconds using adaptive CCD substepping, gravity, ground collisions, and an O(N) zero-allocation 3D spatial hash grid broadphase.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Mutable physics world.
276    /// - `f32` - Timestep in seconds.
277    ///
278    /// # Returns
279    ///
280    /// - `usize` - Number of collisions resolved during this step.
281    pub fn step(&mut self, dt: f32) -> usize {
282        self.step_internal(dt, None)
283    }
284
285    /// Advances all rigid bodies by `dt` seconds with adaptive CCD substepping and real triangle-mesh collision against all solid `World3D` models.
286    ///
287    /// # Arguments
288    ///
289    /// - `&Self` - Mutable physics world.
290    /// - `f32` - Timestep in seconds.
291    /// - `&World3D` - 3D world supplying real static/dynamic mesh colliders.
292    ///
293    /// # Returns
294    ///
295    /// - `usize` - Total rigid-body, ground, and real-mesh collisions resolved during this step.
296    pub fn step_with_world(&mut self, dt: f32, world: &World3D) -> usize {
297        self.step_internal(dt, Some(world))
298    }
299
300    /// Executes adaptive CCD substepping for `PhysicsWorld3D`, preventing high-speed tunneling through thin walls and optionally resolving dynamic bodies against real `World3D` mesh triangles.
301    ///
302    /// # Arguments
303    ///
304    /// - `&Self` - Mutable physics world.
305    /// - `f32` - Frame timestep in seconds.
306    /// - `Option<&World3D>` - Optional 3D scene for real triangle-mesh collision resolution.
307    ///
308    /// # Returns
309    ///
310    /// - `usize` - Total collisions resolved across all substeps.
311    fn step_internal(&mut self, dt: f32, world_opt: Option<&World3D>) -> usize {
312        let total_dt: f32 = dt.clamp(0.0, 0.1);
313        if total_dt <= 0.0 {
314            return 0;
315        }
316        let gravity: Vec3 = self.get_gravity();
317        let mut max_ratio: f32 = 0.0;
318        for body in self.get_bodies().iter() {
319            if body.get_inv_mass() <= 0.0 || body.get_sleeping() {
320                continue;
321            }
322            let height_val: Vec3 = body.get_half_extents();
323            let min_h: f32 = height_val
324                .get_x()
325                .min(height_val.get_y())
326                .min(height_val.get_z())
327                .max(0.05);
328            let est_vel: Vec3 = body.get_velocity().add(gravity.scale(total_dt));
329            let disp: f32 = est_vel.length() * total_dt;
330            let ratio: f32 = disp / min_h;
331            if ratio > max_ratio {
332                max_ratio = ratio;
333            }
334        }
335        let substeps: usize = if max_ratio > 0.45 {
336            ((max_ratio / 0.45).ceil() as usize).clamp(2, 16)
337        } else {
338            1
339        };
340        let sub_dt: f32 = total_dt / (substeps as f32);
341        let mut total_collisions: usize = 0;
342        for _ in 0..substeps {
343            total_collisions += self.step_single_substep(sub_dt, world_opt);
344        }
345        total_collisions
346    }
347
348    /// Advances a single physics substep including gravity, ground plane, spatial-hash body pairs, and optional real-mesh triangle collisions.
349    ///
350    /// # Arguments
351    ///
352    /// - `&Self` - Mutable physics world.
353    /// - `f32` - Substep duration in seconds.
354    /// - `Option<&World3D>` - Optional 3D world for real mesh collision.
355    ///
356    /// # Returns
357    ///
358    /// - `usize` - Collisions resolved during this substep.
359    fn step_single_substep(&mut self, step_dt: f32, world_opt: Option<&World3D>) -> usize {
360        let gravity: Vec3 = self.get_gravity();
361        let ground_y: f32 = self.get_ground_y();
362        let mut collisions: usize = 0;
363        let mut max_extent: f32 = 0.5;
364        let Self {
365            bodies,
366            hash_heads,
367            hash_next,
368            hash_body,
369            touched_buckets,
370            pair_scratch,
371            ..
372        } = self;
373        for body in bodies.iter_mut() {
374            let height_val: Vec3 = body.get_half_extents();
375            let extent: f32 = height_val
376                .get_x()
377                .max(height_val.get_y())
378                .max(height_val.get_z());
379            if extent > max_extent {
380                max_extent = extent;
381            }
382            let inv_m: f32 = body.get_inv_mass();
383            if inv_m <= 0.0 || body.get_sleeping() {
384                continue;
385            }
386            let damp: f32 = (1.0 - body.get_linear_damping() * step_dt).clamp(0.0, 1.0);
387            let ang_damp: f32 = (1.0 - 0.12 * step_dt).clamp(0.0, 1.0);
388            let mut vel: Vec3 = body.get_velocity().add(gravity.scale(step_dt)).scale(damp);
389            let mut ang_vel: Vec3 = body.get_angular_velocity().scale(ang_damp);
390            let mut pos: Vec3 = body.get_position().add(vel.scale(step_dt));
391            let min_y: f32 = ground_y + height_val.get_y();
392            let mut grounded: bool = false;
393            if pos.get_y() <= min_y {
394                pos.set_y(min_y);
395                let ground_grip: f32 = (1.0 - body.get_friction() * 0.18).clamp(0.75, 0.99);
396                if vel.get_y() < 0.0 {
397                    vel.set_y(-vel.get_y() * body.get_restitution());
398                    if vel.get_y().abs() < 0.25 {
399                        vel.set_y(0.0);
400                    }
401                    vel.set_x(vel.get_x() * ground_grip);
402                    vel.set_z(vel.get_z() * ground_grip);
403                    ang_vel = ang_vel.scale(ground_grip);
404                    collisions += 1;
405                }
406                grounded = true;
407            }
408            if let Some(world) = world_opt {
409                for _ in 0..3usize {
410                    let oriented_box: OrientedBox3D = OrientedBox3D::from_bounds(
411                        AxisAlignedBox3D::new(pos.sub(height_val), pos.add(height_val)),
412                    );
413                    let Some(hit) = world.mesh_oriented_box_collision(oriented_box, None) else {
414                        break;
415                    };
416                    let vec_value: Vec3 = hit.get_normal();
417                    pos = pos.add(vec_value.scale(hit.get_penetration() + 1e-4));
418                    let vn: f32 = vel.dot(vec_value);
419                    if vn < 0.0 {
420                        let rest: f32 = body.get_restitution();
421                        vel = vel.sub(vec_value.scale((1.0 + rest) * vn));
422                    }
423                    if vec_value.get_y() > 0.55 {
424                        grounded = true;
425                    }
426                    collisions += 1;
427                }
428            }
429            let speed_sq: f32 = vel.length_sq();
430            let ang_speed_sq: f32 = ang_vel.length_sq();
431            if grounded && speed_sq < 0.0025 && ang_speed_sq < 0.0025 {
432                let next_sleep_timer: f32 = body.get_sleep_timer() + step_dt;
433                body.set_sleep_timer(next_sleep_timer);
434                if next_sleep_timer >= 0.45 {
435                    vel = Vec3::zero();
436                    ang_vel = Vec3::zero();
437                    body.set_sleeping(true);
438                }
439            } else {
440                body.set_sleep_timer(0.0);
441            }
442            body.set_position(pos);
443            body.set_velocity(vel);
444            body.set_angular_velocity(ang_vel);
445            body.set_grounded(grounded);
446        }
447        let count: usize = bodies.len();
448        if count <= 1 {
449            return collisions;
450        }
451        if count <= 16 {
452            for item_index in 0..count {
453                for inner_index in (item_index + 1)..count {
454                    if Self::resolve_body_pair(bodies.as_mut_slice(), item_index, inner_index) {
455                        collisions += 1;
456                    }
457                }
458            }
459            return collisions;
460        }
461        let target_buckets: usize = (count * 4).next_power_of_two().clamp(256, 16_384);
462        if hash_heads.len() != target_buckets {
463            hash_heads.clear();
464            hash_heads.resize(target_buckets, u32::MAX);
465            touched_buckets.clear();
466        } else {
467            for &blue_val in touched_buckets.iter() {
468                hash_heads[blue_val] = u32::MAX;
469            }
470            touched_buckets.clear();
471        }
472        hash_next.clear();
473        hash_body.clear();
474        pair_scratch.clear();
475        let cell_size: f32 = (max_extent * 2.5).max(1.0);
476        let inv_cell: f32 = 1.0 / cell_size;
477        let mask: usize = target_buckets - 1;
478        for (idx, body) in bodies.iter().enumerate() {
479            let direction_vec: Vec3 = body.get_position();
480            let span_height: Vec3 = body.get_half_extents();
481            let min_cx: i32 =
482                ((direction_vec.get_x() - span_height.get_x()) * inv_cell).floor() as i32;
483            let max_cx: i32 =
484                ((direction_vec.get_x() + span_height.get_x()) * inv_cell).floor() as i32;
485            let min_cy: i32 =
486                ((direction_vec.get_y() - span_height.get_y()) * inv_cell).floor() as i32;
487            let max_cy: i32 =
488                ((direction_vec.get_y() + span_height.get_y()) * inv_cell).floor() as i32;
489            let min_cz: i32 =
490                ((direction_vec.get_z() - span_height.get_z()) * inv_cell).floor() as i32;
491            let max_cz: i32 =
492                ((direction_vec.get_z() + span_height.get_z()) * inv_cell).floor() as i32;
493            for cx in min_cx..=max_cx {
494                for cy in min_cy..=max_cy {
495                    for cz in min_cz..=max_cz {
496                        let bucket: usize = Self::hash_cell(cx, cy, cz, mask);
497                        let mut cur: u32 = hash_heads[bucket];
498                        if cur == u32::MAX {
499                            touched_buckets.push(bucket);
500                        } else {
501                            while cur != u32::MAX {
502                                let other: usize = hash_body[cur as usize] as usize;
503                                if other != idx {
504                                    let pair: (usize, usize) = if other < idx {
505                                        (other, idx)
506                                    } else {
507                                        (idx, other)
508                                    };
509                                    pair_scratch.push(pair);
510                                }
511                                cur = hash_next[cur as usize];
512                            }
513                        }
514                        let entry: u32 = hash_body.len() as u32;
515                        hash_body.push(idx as u32);
516                        hash_next.push(hash_heads[bucket]);
517                        hash_heads[bucket] = entry;
518                    }
519                }
520            }
521        }
522        pair_scratch.sort_unstable();
523        pair_scratch.dedup();
524        for &(outer_index, col_index) in pair_scratch.iter() {
525            if Self::resolve_body_pair(bodies.as_mut_slice(), outer_index, col_index) {
526                collisions += 1;
527            }
528        }
529        collisions
530    }
531
532    /// Casts a `Ray3D` against all 3D rigid bodies up to `max_distance` and returns the closest hit.
533    ///
534    /// # Arguments
535    ///
536    /// - `&Self` - Physics world reference.
537    /// - `&Ray3D` - Query ray.
538    /// - `f32` - Maximum cast distance in meters.
539    ///
540    /// # Returns
541    ///
542    /// - `Option<RayHitPhysics3D>` - Closest hit body and contact position if any.
543    #[must_use]
544    pub fn raycast(&self, ray: &Ray3D, max_distance: f32) -> Option<RayHitPhysics3D> {
545        let mut best: Option<RayHitPhysics3D> = None;
546        let mut best_t: f32 = max_distance.max(0.0);
547        for (idx, body) in self.get_bodies().iter().enumerate() {
548            let bounds_rect: AxisAlignedBox3D = body.world_bounds();
549            let blend_factor: f32 = bounds_rect.intersect_ray_near(
550                ray.get_origin(),
551                ray.get_inv_direction(),
552                0.001,
553                best_t,
554            );
555            if blend_factor.is_finite() && blend_factor < best_t {
556                best_t = blend_factor;
557                let vec_value: Vec3 = ray
558                    .get_origin()
559                    .add(ray.get_direction().scale(blend_factor));
560                best = Some(RayHitPhysics3D::new(idx, blend_factor, vec_value));
561            }
562        }
563        best
564    }
565}