ferravex_physics/
world.rs

1use crate::{
2    body::{Access, BodySet, Collider, ColliderHandle, ColliderSet, Kind, RigidBodyHandle, Shape},
3    geometry::{self, Bounds, Point},
4};
5use ferravex_math::{Quat, Vec3};
6mod cache;
7mod compounds;
8mod islands;
9mod joints;
10use cache::Manifold;
11pub use cache::{ContactManifold, ContactPoint, SolverSettings};
12pub use compounds::{MAX_CHILDREN, MAX_COLLIDERS};
13use islands::Islands;
14use joints::{JointPhase, JointRow};
15
16/// Maximum logical outer-step impact records. Recording is disabled by default.
17/// Call `set_impact_settings` through the dimensional `PhysicsWorld`; its
18/// method documentation includes preparation and a runnable recipe.
19pub const MAX_IMPACT_RECORDS: usize = 65536;
20
21/// Observation thresholds only; these never change solver tolerances or impulses.
22/// The dimensional `PhysicsWorld::set_impact_settings` method documents an
23/// example using inferred defaults.
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct ImpactSettings {
26    /// First qualifying pairs in substep/solver order are retained, up to this
27    /// bound (0..=MAX_IMPACT_RECORDS). Zero records still counts rejections.
28    pub capacity: usize,
29    /// Strict lower bound on the peak newly solved point normal impulse.
30    /// Finite and nonnegative; zero accepts any positive qualifying impulse.
31    pub min_normal_impulse: f32,
32    /// Strict lower bound on approach speed, finite and positive. Approach must
33    /// exceed this both before substep forces/gravity/damping/integration and at
34    /// contact creation before warm start. This excludes ordinary resting
35    /// support, even with warm start off. Choose above expected solver jitter.
36    pub min_approach_speed: f32,
37}
38impl Default for ImpactSettings {
39    fn default() -> Self {
40        Self {
41            capacity: 64,
42            min_normal_impulse: 0.,
43            min_approach_speed: 1.,
44        }
45    }
46}
47/// One canonical generational collider pair's strongest accepted point solve in
48/// the latest outer step, including contacts absent from the final cache.
49/// Read these through the dimensional world's `impacts` method after opting
50/// in with `set_impact_settings`.
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct ImpactRecord {
53    pub collider1: ColliderHandle,
54    pub collider2: ColliderHandle,
55    /// World-space constraint creation position, represented as Vec3 in 2D/3D.
56    pub point: Vec3,
57    /// Unit world normal from collider1 toward collider2.
58    pub normal: Vec3,
59    /// Maximum over points, iterations and substeps of
60    /// `max(0, accumulated_normal_impulse - initial_warm_start_impulse)`.
61    /// Neither a sum over points/substeps nor total energy/acoustic loudness.
62    /// Solver iteration overshoot can affect this peak; tangential, rolling,
63    /// joint, positional and cached warm-start replay impulses are excluded.
64    pub peak_normal_impulse: f32,
65    /// Minimum of the before-force and before-warm-start approach speeds at
66    /// this record's selected point. Useful when authoring thresholds.
67    pub approach_speed: f32,
68}
69/// Transactional impact configuration failure; the previous settings and
70/// snapshot remain intact. Successful reservation before a later allocation
71/// failure may retain additional unused capacity for reuse.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum ImpactRecordingError {
74    InvalidSettings,
75    AllocationFailed,
76}
77impl std::fmt::Display for ImpactRecordingError {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.write_str(match self {
80            Self::InvalidSettings => "invalid impact recording settings",
81            Self::AllocationFailed => "impact recording reservation failed",
82        })
83    }
84}
85impl std::error::Error for ImpactRecordingError {}
86
87/// Contacts include transient impacts from all substeps of the latest outer step.
88#[derive(Clone, Copy, Debug)]
89pub struct ContactPair {
90    pub collider1: ColliderHandle,
91    pub collider2: ColliderHandle,
92    pub normal: [f32; 3],
93    pub sensor: bool,
94}
95impl ContactPair {
96    pub fn has_any_active_contact(&self) -> bool {
97        !self.sensor
98    }
99}
100/// Changes to the set of pairs observed during consecutive valid outer steps.
101/// Both physical contacts and sensor overlaps count. Changing sensor status alone
102/// does not restart an overlap, provided the pair remains collision-eligible.
103/// Handles retain their original generations, including in removal stop events.
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub enum ContactEvent {
106    Started(ColliderHandle, ColliderHandle),
107    Stopped(ColliderHandle, ColliderHandle),
108}
109/// A copied, current sleep snapshot for a live body; no solver state is exposed
110/// for mutation. The dimensional world's `sleep_state` method includes a
111/// handle-checked example.
112#[derive(Clone, Copy, Debug, PartialEq)]
113pub struct BodySleepState {
114    /// Only dynamic bodies participate in sleeping and sleep counters.
115    pub dynamic: bool,
116    pub sleeping: bool,
117    /// An explicit wake request is pending until the next valid outer step ends.
118    /// Edits, gravity and moving neighbors can also wake bodies without this flag.
119    pub wake_requested: bool,
120    /// Quiet simulation seconds, capped at the current solver's sleep delay.
121    /// Fixed and kinematic bodies report zero. This is not time spent asleep.
122    pub quiet_time: f32,
123}
124/// Current dynamic-body counts, each bounded by the world's 4096-body limit.
125/// This is an allocation-free snapshot, not a cumulative event history or the
126/// last-step island report. See the dimensional world's `sleep_stats` method
127/// for an example.
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129pub struct SleepStats {
130    pub awake_bodies: usize,
131    pub sleeping_bodies: usize,
132    /// Dynamic bodies with explicit wake requests awaiting a valid outer step.
133    /// These bodies are also counted in `awake_bodies`.
134    pub wake_requests: usize,
135}
136#[derive(Clone, Copy, Debug, Default)]
137pub struct StepStats {
138    pub substeps: usize,
139    pub broadphase_pairs: usize,
140    pub contact_points: usize,
141    pub ccd_impacts: usize,
142    pub sleeping_bodies: usize,
143    pub islands: usize,
144    pub active_islands: usize,
145    pub sleeping_islands: usize,
146    pub persisted_points: usize,
147    pub warm_started_points: usize,
148    pub reused_manifolds: usize,
149    pub cached_manifolds: usize,
150    pub cache_dropped: usize,
151    pub velocity_constraints: usize,
152    pub joint_rows: usize,
153    pub joint_constraints: usize,
154}
155#[derive(Clone, Debug)]
156struct Constraint {
157    a: RigidBodyHandle,
158    b: RigidBodyHandle,
159    normal: Vec3,
160    point: Vec3,
161    local_a: Vec3,
162    local_b: Vec3,
163    normal_impulse: f32,
164    normal_denominator: f32,
165    /// Contact point minus each body's world center of mass. Poses are fixed
166    /// during velocity iterations, so these are computed once per solve.
167    ra: Vec3,
168    rb: Vec3,
169    impact_baseline: f32,
170    impact_peak: f32,
171    impact_approach: f32,
172    tangent_impulse: Vec3,
173    bounce: f32,
174    friction: f32,
175    static_friction: f32,
176    rolling_resistance: f32,
177    rolling_impulse: Vec3,
178    key: (ColliderHandle, ColliderHandle),
179    feature: u64,
180    cache: Option<(usize, usize)>,
181}
182/// One collider's current pose, bounds, substep start position and filter
183/// data, cached once per substep for the continuous sweep broadphase.
184#[derive(Clone, Copy)]
185struct CcdTarget {
186    body: RigidBodyHandle,
187    pose: geometry::Pose,
188    start: Vec3,
189    bounds: Bounds,
190    /// Conservative swept AABB covering `bounds` plus negative displacement
191    /// `start - pose.position`, so `own_swept.intersects(swept_bounds)` is a
192    /// guaranteed superset of `swept_relative.intersects(bounds)`.
193    swept_bounds: Bounds,
194    shape: Shape,
195    sensor: bool,
196    membership: u32,
197    filter: u32,
198}
199impl CcdTarget {
200    fn new(
201        body_handle: RigidBodyHandle,
202        collider: &Collider,
203        body: &crate::body::Core,
204        origin: Vec3,
205        rotation: Quat,
206    ) -> Self {
207        let pose = collider.pose(body);
208        let start = origin + rotation * collider.local_translation;
209        let bounds = geometry::bounds(collider.shape, pose.position, pose.rotation);
210        let neg_disp = start - pose.position;
211        let pad = Vec3::splat(1.0e-4);
212        let swept_bounds = Bounds {
213            min: bounds.min + neg_disp.min(Vec3::ZERO) - pad,
214            max: bounds.max + neg_disp.max(Vec3::ZERO) + pad,
215        };
216        Self {
217            body: body_handle,
218            pose,
219            start,
220            bounds,
221            swept_bounds,
222            shape: collider.shape,
223            sensor: collider.sensor,
224            membership: collider.membership,
225            filter: collider.filter,
226        }
227    }
228}
229#[derive(Clone, Copy)]
230struct Proxy {
231    body: RigidBodyHandle,
232    collider: ColliderHandle,
233    bounds: Bounds,
234    membership: u32,
235    filter: u32,
236    kind: Kind,
237    sensor: bool,
238}
239#[derive(Clone, Copy)]
240struct SleepWorldCache {
241    dt: f32,
242    gravity: Vec3,
243    settings: SolverSettings,
244    fingerprint: u64,
245    body_count: usize,
246    collider_count: usize,
247    stats: StepStats,
248}
249/// Bodies and child collider handles use generation counters;
250/// capacity is deliberately limited to 4096 bodies for predictable memory use.
251pub struct World<B> {
252    pub bodies: BodySet<B>,
253    pub colliders: ColliderSet,
254    pub gravity: Vec3,
255    pub joints: crate::JointSet,
256    joint_rows: Vec<JointRow>,
257    broken_joints: Vec<crate::JointBreakEvent>,
258    joint_solver: Option<fn(&mut Self, JointPhase, f32, &mut StepStats)>,
259    disabled_joint_pairs: Vec<(RigidBodyHandle, RigidBodyHandle)>,
260    planar: bool,
261    contacts: Vec<ContactPair>,
262    next_contacts: Vec<ContactPair>,
263    manifolds: Vec<Manifold>,
264    next_manifolds: Vec<Manifold>,
265    next_feature: u64,
266    settings: SolverSettings,
267    impact_settings: Option<ImpactSettings>,
268    impacts: Vec<ImpactRecord>,
269    impact_dropped: usize,
270    impact_motions: Vec<cache::ImpactMotion>,
271    islands: Islands,
272    last_gravity: Vec3,
273    old_positions: Vec<(RigidBodyHandle, Vec3, Quat)>,
274    /// Reused sweep scratch: per-collider targets, body spans, and X-sorted broadphase.
275    ccd_targets: Vec<CcdTarget>,
276    ccd_first: Vec<usize>,
277    ccd_order: Vec<usize>,
278    ccd_wide: Vec<usize>,
279    ccd_prefix_max_x: Vec<f32>,
280    active_constraints: Vec<usize>,
281    sleep_cache: Option<SleepWorldCache>,
282    mass_updates: Vec<(RigidBodyHandle, Option<crate::mass::Mass>)>,
283    events: Vec<ContactEvent>,
284    constraints: Vec<Constraint>,
285    proxies: Vec<Proxy>,
286    points: Vec<Point>,
287    pub last_step: StepStats,
288}
289impl<B: Access> World<B> {
290    pub(crate) fn new(gravity: Vec3, planar: bool) -> Self {
291        assert!(gravity.is_finite());
292        Self {
293            bodies: BodySet::default(),
294            colliders: ColliderSet::default(),
295            gravity,
296            joints: Default::default(),
297            joint_rows: Vec::new(),
298            broken_joints: Vec::new(),
299            joint_solver: None,
300            disabled_joint_pairs: Vec::new(),
301            planar,
302            contacts: Vec::new(),
303            next_contacts: Vec::new(),
304            manifolds: Vec::new(),
305            next_manifolds: Vec::new(),
306            next_feature: 1,
307            settings: Default::default(),
308            impact_settings: None,
309            impacts: Vec::new(),
310            impact_dropped: 0,
311            impact_motions: Vec::new(),
312            islands: Default::default(),
313            last_gravity: gravity,
314            old_positions: Vec::new(),
315            ccd_targets: Vec::new(),
316            ccd_first: Vec::new(),
317            ccd_order: Vec::new(),
318            ccd_wide: Vec::new(),
319            ccd_prefix_max_x: Vec::new(),
320            active_constraints: Vec::new(),
321            sleep_cache: None,
322            mass_updates: Vec::new(),
323            events: Vec::new(),
324            constraints: Vec::new(),
325            proxies: Vec::new(),
326            points: Vec::with_capacity(8),
327            last_step: StepStats::default(),
328        }
329    }
330    pub fn joint_break_events(&self) -> &[crate::JointBreakEvent] {
331        &self.broken_joints
332    }
333    /// Inspect current body state without indexing a possibly stale handle.
334    /// Removed/reused handles return `None`; fixed and kinematic bodies report
335    /// `dynamic == false` and never report sleeping. No allocation or wake occurs.
336    ///
337    /// ```
338    /// # #[cfg(feature = "dim2")] {
339    /// use ferravex_physics::d2::*;
340    /// let mut world = PhysicsWorld::default();
341    /// let (body, _) = world.insert(RigidBodyBuilder::dynamic(), ColliderBuilder::ball(1.));
342    /// let state = world.sleep_state(body).unwrap();
343    /// assert!(state.dynamic && !state.sleeping && state.wake_requested);
344    /// assert_eq!(state.quiet_time, 0.);
345    /// world.remove_body(body);
346    /// assert_eq!(world.sleep_state(body), None);
347    /// # }
348    /// ```
349    pub fn sleep_state(&self, body: RigidBodyHandle) -> Option<BodySleepState> {
350        let b = self.bodies.get(body)?.core();
351        let dynamic = b.kind == Kind::Dynamic;
352        Some(BodySleepState {
353            dynamic,
354            sleeping: b.sleeping,
355            wake_requested: b.wake_requested,
356            quiet_time: if dynamic {
357                b.quiet.min(self.settings.sleep_delay)
358            } else {
359                0.
360            },
361        })
362    }
363    /// Count current dynamic-body states, including edits since the last step.
364    /// Fixed/kinematic bodies are excluded. Reads reuse body storage; counts do
365    /// not accumulate over steps. Use `last_step` for last-step island counts.
366    ///
367    /// ```
368    /// # #[cfg(feature = "dim2")] {
369    /// use ferravex_physics::d2::*;
370    /// let mut world = PhysicsWorld::default();
371    /// world.insert(RigidBodyBuilder::dynamic(), ColliderBuilder::ball(1.));
372    /// for _ in 0..120 { world.step(1. / 60.); }
373    /// let stats = world.sleep_stats();
374    /// assert_eq!(stats.awake_bodies, 0);
375    /// assert_eq!(stats.sleeping_bodies, 1);
376    /// assert_eq!(stats.wake_requests, 0);
377    /// # }
378    /// ```
379    pub fn sleep_stats(&self) -> SleepStats {
380        let mut stats = SleepStats::default();
381        for (_, body) in self.bodies.iter() {
382            let b = body.core();
383            if b.kind != Kind::Dynamic {
384                continue;
385            }
386            if b.sleeping {
387                stats.sleeping_bodies += 1;
388            } else {
389                stats.awake_bodies += 1;
390            }
391            stats.wake_requests += usize::from(b.wake_requested);
392        }
393        stats
394    }
395    /// Wake a dynamic body immediately and request island propagation on the
396    /// next valid step. Returns whether it was sleeping; an already awake body
397    /// still has its quiet timer reset and its wake request set. This neither
398    /// advances simulation nor changes the last-step contacts/events/stats.
399    ///
400    /// Returns [`crate::PhysicsError::InvalidHandle`] for stale handles and
401    /// [`crate::PhysicsError::InvalidBody`] for fixed/kinematic bodies, without edits.
402    ///
403    /// ```
404    /// # #[cfg(feature = "dim2")] {
405    /// use ferravex_physics::{PhysicsError, d2::*};
406    /// let mut world = PhysicsWorld::default();
407    /// let (body, _) = world.insert(RigidBodyBuilder::dynamic(), ColliderBuilder::ball(1.));
408    /// for _ in 0..120 { world.step(1. / 60.); }
409    /// assert_eq!(world.wake_body(body), Ok(true));
410    /// assert_eq!(world.wake_body(body), Ok(false));
411    /// assert_eq!(world.sleep_stats().wake_requests, 1);
412    /// world.remove_body(body);
413    /// assert_eq!(world.wake_body(body), Err(PhysicsError::InvalidHandle));
414    /// # }
415    /// ```
416    pub fn wake_body(&mut self, body: RigidBodyHandle) -> Result<bool, crate::PhysicsError> {
417        let b = self
418            .bodies
419            .get_mut(body)
420            .ok_or(crate::PhysicsError::InvalidHandle)?
421            .core_mut();
422        if b.kind != Kind::Dynamic {
423            return Err(crate::PhysicsError::InvalidBody);
424        }
425        let was_sleeping = b.sleeping;
426        b.wake();
427        Ok(was_sleeping)
428    }
429    pub fn insert(
430        &mut self,
431        b: impl Into<B>,
432        c: impl Into<Collider>,
433    ) -> (RigidBodyHandle, ColliderHandle) {
434        let body = self
435            .insert_compound(b, [c.into()])
436            .expect("valid body/collider within capacities");
437        (body, self.bodies[body].core().colliders[0])
438    }
439
440    /// Remove a live body and its colliders/joints; return false for a stale handle.
441    /// Contact queries immediately exclude its colliders. Their stop events are
442    /// reported once on the next valid [`Self::step`], even if slots are reused.
443    pub fn remove_body(&mut self, h: RigidBodyHandle) -> bool {
444        if self.bodies.get(h).is_none() {
445            return false;
446        }
447        loop {
448            let id = self
449                .joints
450                .iter()
451                .find(|(_, j)| j.a == h || j.b == h)
452                .map(|(id, _)| id);
453            let Some(id) = id else {
454                break;
455            };
456            self.remove_joint(id);
457        }
458        let Some(b) = self.bodies.remove(h) else {
459            return false;
460        };
461        for &c in &b.core().colliders {
462            for contact in &self.contacts {
463                if contact.sensor {
464                    continue;
465                }
466                let other = if contact.collider1 == c {
467                    Some(contact.collider2)
468                } else if contact.collider2 == c {
469                    Some(contact.collider1)
470                } else {
471                    None
472                };
473                if let Some(other) = other
474                    .and_then(|id| self.colliders.get(id))
475                    .and_then(|o| o.parent)
476                    && let Some(body) = self.bodies.get_mut(other)
477                {
478                    body.core_mut().wake();
479                }
480            }
481            self.manifolds.retain(|m| m.key.0 != c && m.key.1 != c);
482            self.next_manifolds.retain(|m| m.key.0 != c && m.key.1 != c);
483            self.colliders.remove(c);
484        }
485        true
486    }
487    /// Look up a pair from the last valid outer step, in either handle order.
488    /// Removed handles return `None` immediately, without consuming the pending
489    /// stop event. Pose, sensor and layer edits are reflected after the next step.
490    ///
491    /// ```
492    /// # #[cfg(feature = "dim2")] {
493    /// use ferravex_physics::{ContactEvent, d2::*};
494    /// let mut world = PhysicsWorld::default();
495    /// let (_, sensor) = world.insert(
496    ///     RigidBodyBuilder::fixed(), ColliderBuilder::ball(2.).sensor(true),
497    /// );
498    /// let (body, collider) = world.insert(
499    ///     RigidBodyBuilder::dynamic(), ColliderBuilder::ball(0.5),
500    /// );
501    /// world.step(1. / 60.);
502    /// assert!(world.contact_pair(collider, sensor).unwrap().sensor);
503    /// world.remove_body(body);
504    /// assert!(world.contact_pair(sensor, collider).is_none());
505    /// world.step(1. / 60.);
506    /// assert_eq!(world.contact_events(), &[ContactEvent::Stopped(sensor, collider)]);
507    /// # }
508    /// ```
509    pub fn contact_pair(&self, a: ColliderHandle, b: ColliderHandle) -> Option<&ContactPair> {
510        self.colliders.get(a)?;
511        self.colliders.get(b)?;
512        let key = pair_key(a, b);
513        self.contacts
514            .binary_search_by_key(&key, |c| pair_key(c.collider1, c.collider2))
515            .ok()
516            .map(|i| &self.contacts[i])
517    }
518    /// Borrow events from the last valid outer step without consuming them.
519    /// Started events precede stopped events; each group is sorted by canonical
520    /// `(collider1, collider2)` handle order. A pair appears at most once per group.
521    /// Removal stops arrive on the next valid step; an empty-world step still
522    /// reports them. Invalid timestep/gravity panics leave this snapshot intact.
523    /// Transient substep contacts count for the whole outer step and stop on a
524    /// subsequent step in which they are absent.
525    pub fn contact_events(&self) -> &[ContactEvent] {
526        &self.events
527    }
528    /// Iterate last-step contacts in canonical pair order, skipping removed
529    /// colliders. Like [`Self::contact_pair`], this includes sensors and transient
530    /// substep contacts and borrows existing storage without allocating.
531    pub fn contacts(&self) -> impl Iterator<Item = &ContactPair> {
532        self.contacts.iter().filter(|c| {
533            self.colliders.get(c.collider1).is_some() && self.colliders.get(c.collider2).is_some()
534        })
535    }
536    /// Advance a fixed simulation interval in (0, 0.1] seconds. Forces apply for
537    /// this complete interval and are then cleared. The caller owns accumulation.
538    ///
539    /// # Panics
540    /// Invalid timesteps or non-finite gravity panic before replacing contact
541    /// events or advancing bodies. Invalid compound mass properties also panic.
542    fn compute_sleeping_fingerprint(&self) -> Option<u64> {
543        if !self.settings.allow_sleep || self.impact_settings.is_some() || !self.joints.is_empty() {
544            return None;
545        }
546        let mut h = 0xcbf29ce484222325_u64;
547        let mut mix = |v: u64| {
548            h ^= v;
549            h = h.wrapping_mul(0x100000001b3);
550        };
551        for (id, body) in self.bodies.iter() {
552            let b = body.core();
553            if b.solver_dirty || b.wake_requested || b.force != Vec3::ZERO || b.torque != Vec3::ZERO
554            {
555                return None;
556            }
557            match b.kind {
558                Kind::Dynamic => {
559                    if !b.sleeping || b.quiet < self.settings.sleep_delay {
560                        return None;
561                    }
562                }
563                Kind::Kinematic => {
564                    if b.next_position.is_some()
565                        || b.next_rotation.is_some()
566                        || b.velocity.length_squared() + b.angular_velocity.length_squared() > 1e-12
567                    {
568                        return None;
569                    }
570                }
571                Kind::Fixed => {}
572            }
573            mix(id.index as u64);
574            mix(u64::from(id.generation));
575            mix(b.revision);
576            mix(b.kind as u64);
577            mix(u64::from(b.position.x.to_bits()) | (u64::from(b.position.y.to_bits()) << 32));
578            mix(u64::from(b.position.z.to_bits()) | (u64::from(b.gravity_scale.to_bits()) << 32));
579            mix(u64::from(b.rotation.x.to_bits()) | (u64::from(b.rotation.y.to_bits()) << 32));
580            mix(u64::from(b.rotation.z.to_bits()) | (u64::from(b.rotation.w.to_bits()) << 32));
581            mix(u64::from(b.velocity.x.to_bits()) | (u64::from(b.velocity.y.to_bits()) << 32));
582            mix(u64::from(b.velocity.z.to_bits())
583                | (u64::from(b.angular_velocity.x.to_bits()) << 32));
584            mix(u64::from(b.angular_velocity.y.to_bits())
585                | (u64::from(b.angular_velocity.z.to_bits()) << 32));
586        }
587        for (cid, c) in self.colliders.iter() {
588            if c.dirty || c.mass_dirty {
589                return None;
590            }
591            mix(cid.index as u64);
592            mix(u64::from(cid.generation));
593            mix(c.revision);
594            mix(u64::from(c.membership) | (u64::from(c.filter) << 32));
595            mix(u64::from(c.sensor));
596        }
597        Some(h)
598    }
599
600    pub fn step(&mut self, dt: f32) -> StepStats {
601        assert!(
602            dt.is_finite() && dt > 0. && dt <= 0.1,
603            "use a fixed timestep in (0, 0.1]"
604        );
605        assert!(self.gravity.is_finite());
606        if let Some(cache) = self.sleep_cache {
607            if dt == cache.dt
608                && self.gravity == cache.gravity
609                && self.settings == cache.settings
610                && self.bodies.len() == cache.body_count
611                && self.colliders.len() == cache.collider_count
612                && self.compute_sleeping_fingerprint() == Some(cache.fingerprint)
613            {
614                self.events.clear();
615                self.clear_impacts();
616                self.broken_joints.clear();
617                self.last_step = cache.stats;
618                ferravex_core::telemetry::record_physics(
619                    cache.stats.broadphase_pairs,
620                    cache.stats.contact_points,
621                    cache.stats.ccd_impacts,
622                );
623                return cache.stats;
624            }
625            self.sleep_cache = None;
626        }
627        let asleep_before_step = self.compute_sleeping_fingerprint().is_some();
628        self.refresh_mass_properties()
629            .expect("valid compound mass properties");
630        self.run_joints(JointPhase::Refresh, dt, &mut StepStats::default());
631        self.next_contacts.clear();
632        self.events.clear();
633        self.clear_impacts();
634        let mut substeps = 1;
635        for (_, body) in self.bodies.iter_mut() {
636            let b = body.core_mut();
637            if b.kind == Kind::Kinematic {
638                b.velocity = b.next_position.map_or(Vec3::ZERO, |p| {
639                    (p + b.next_rotation.unwrap_or(b.rotation) * b.local_com - b.world_com()) / dt
640                });
641                b.angular_velocity = b
642                    .next_rotation
643                    .map_or(Vec3::ZERO, |r| rotation_delta(b.rotation, r) / dt);
644                substeps = substeps.max((b.angular_velocity.length() * dt / 0.06).ceil() as usize);
645            }
646            if b.kind == Kind::Dynamic && b.ccd {
647                let mut size = f32::INFINITY;
648                for child in &b.colliders {
649                    let extent = match self.colliders[*child].shape {
650                        Shape::Ball(r) => r,
651                        Shape::Box(h) => h.x.min(h.y).min(if self.planar { h.x } else { h.z }),
652                        #[cfg(feature = "dim2")]
653                        Shape::Capsule { radius, .. } => radius,
654                        #[cfg(feature = "dim3")]
655                        Shape::Cylinder {
656                            radius,
657                            half_height,
658                        } => radius.min(half_height),
659                    };
660                    size = size.min(extent);
661                }
662                substeps = substeps.max((b.velocity.length() * dt / (size * 0.75)).ceil() as usize);
663                substeps = substeps.max((b.angular_velocity.length() * dt / 0.06).ceil() as usize);
664            }
665        }
666        for (_, j) in self.joints.iter() {
667            if j.description().enabled {
668                let speed =
669                    joints::motor_speed(j, self.bodies[j.a].core(), self.bodies[j.b].core());
670                substeps = substeps.max((speed * dt / 0.06).ceil() as usize);
671            }
672        }
673        substeps = substeps.clamp(1, 8);
674        let h = dt / substeps as f32;
675        let mut stats = StepStats {
676            substeps,
677            ..StepStats::default()
678        };
679        let gravity_changed = self.gravity != self.last_gravity;
680        self.wake_previous_islands(gravity_changed);
681        if gravity_changed {
682            self.manifolds.clear();
683        }
684        self.broken_joints.clear();
685        for (_, j) in self.joints.iter_mut() {
686            j.peak = crate::JointLoad::default();
687        }
688        for _ in 0..substeps {
689            self.capture_impact_motion();
690            self.old_positions.clear();
691            self.old_positions.extend(
692                self.bodies
693                    .iter()
694                    .map(|(id, b)| (id, b.core().position, b.core().rotation)),
695            );
696            for (_, body) in self.bodies.iter_mut() {
697                let b = body.core_mut();
698                if b.kind == Kind::Dynamic && !b.sleeping {
699                    b.velocity += (self.gravity * b.gravity_scale + b.force * b.inv_mass) * h;
700                    b.angular_velocity += b.inverse_inertia(b.torque) * h;
701                    b.velocity /= 1. + b.linear_damping * h;
702                    b.angular_velocity /= 1. + b.angular_damping * h;
703                }
704                if b.kind != Kind::Fixed && !b.sleeping {
705                    b.integrate(h);
706                }
707            }
708            stats.ccd_impacts += self.sweep_fast_bodies();
709            self.find_contacts(h, &mut stats);
710            self.wake_edited_contact_bodies();
711            self.wake_contact_islands();
712            self.warm_start(&mut stats);
713            self.run_joints(JointPhase::Prepare, h, &mut stats);
714            self.solve_velocities(&mut stats);
715            self.record_impacts();
716            self.run_joints(JointPhase::Integrate, h, &mut stats);
717            self.solve_positions();
718            self.store_manifolds(h);
719            self.run_joints(JointPhase::Store, h, &mut stats);
720            self.sleep_islands(h, &mut stats);
721        }
722        for (_, body) in self.bodies.iter_mut() {
723            let b = body.core_mut();
724            b.force = Vec3::ZERO;
725            b.torque = Vec3::ZERO;
726            if b.kind == Kind::Kinematic {
727                if let Some(p) = b.next_position.take() {
728                    b.position = p;
729                }
730                if let Some(q) = b.next_rotation.take() {
731                    b.set_rotation(q);
732                }
733            }
734            b.wake_requested = false;
735            b.solver_dirty = false;
736            if b.sleeping {
737                stats.sleeping_bodies += 1;
738            }
739        }
740        self.next_contacts
741            .sort_unstable_by_key(|c| pair_key(c.collider1, c.collider2));
742        self.next_contacts
743            .dedup_by_key(|c| pair_key(c.collider1, c.collider2));
744        // Both `next_contacts` and `contacts` are sorted and deduplicated by `pair_key`.
745        // Emit all `Started` events first, then all `Stopped` events in O(M) linear scans.
746        let mut old_i = 0_usize;
747        for c in &self.next_contacts {
748            let k = pair_key(c.collider1, c.collider2);
749            while old_i < self.contacts.len()
750                && pair_key(
751                    self.contacts[old_i].collider1,
752                    self.contacts[old_i].collider2,
753                ) < k
754            {
755                old_i += 1;
756            }
757            if old_i >= self.contacts.len()
758                || pair_key(
759                    self.contacts[old_i].collider1,
760                    self.contacts[old_i].collider2,
761                ) != k
762            {
763                self.events
764                    .push(ContactEvent::Started(c.collider1, c.collider2));
765            }
766        }
767        let mut new_i = 0_usize;
768        for c in &self.contacts {
769            let k = pair_key(c.collider1, c.collider2);
770            while new_i < self.next_contacts.len()
771                && pair_key(
772                    self.next_contacts[new_i].collider1,
773                    self.next_contacts[new_i].collider2,
774                ) < k
775            {
776                new_i += 1;
777            }
778            if new_i >= self.next_contacts.len()
779                || pair_key(
780                    self.next_contacts[new_i].collider1,
781                    self.next_contacts[new_i].collider2,
782                ) != k
783            {
784                self.events
785                    .push(ContactEvent::Stopped(c.collider1, c.collider2));
786            }
787        }
788        std::mem::swap(&mut self.contacts, &mut self.next_contacts);
789        self.next_contacts.clear();
790        for (_, c) in self.colliders.iter_mut() {
791            c.dirty = false;
792        }
793        self.last_gravity = self.gravity;
794        stats.cached_manifolds = self.manifolds.len();
795        self.last_step = stats;
796        if asleep_before_step
797            && !gravity_changed
798            && stats.substeps == 1
799            && stats.cache_dropped == 0
800            && stats.warm_started_points == 0
801            && stats.velocity_constraints == 0
802            && stats.active_islands == 0
803            && stats.ccd_impacts == 0
804            && self.events.is_empty()
805            && self.joints.is_empty()
806            && let Some(fingerprint) = self.compute_sleeping_fingerprint()
807        {
808            self.sleep_cache = Some(SleepWorldCache {
809                dt,
810                gravity: self.gravity,
811                settings: self.settings,
812                fingerprint,
813                body_count: self.bodies.len(),
814                collider_count: self.colliders.len(),
815                stats,
816            });
817        }
818        ferravex_core::telemetry::record_physics(
819            stats.broadphase_pairs,
820            stats.contact_points,
821            stats.ccd_impacts,
822        );
823        stats
824    }
825    fn wake_edited_contact_bodies(&mut self) {
826        // A sensor becoming solid or newly matching layers has no previous
827        // solid island to wake. A moved or newly inserted fixed/kinematic body
828        // also has no dynamic island of its own. Insertion sets wake_requested
829        // even when there is no dirty pose or collider revision. Seed current
830        // solid contacts before their normal island activation/solving pass.
831        for c in &self.constraints {
832            if self.colliders[c.key.0].dirty
833                || self.colliders[c.key.1].dirty
834                || self.bodies[c.a].core().solver_dirty
835                || self.bodies[c.b].core().solver_dirty
836                || self.bodies[c.a].core().wake_requested
837                || self.bodies[c.b].core().wake_requested
838            {
839                for id in [c.a, c.b] {
840                    let b = self.bodies[id].core_mut();
841                    if b.kind == Kind::Dynamic && b.sleeping {
842                        b.wake();
843                    }
844                }
845            }
846        }
847    }
848    fn sweep_fast_bodies(&mut self) -> usize {
849        let swept_body = |b: &crate::body::Core| b.ccd && b.kind == Kind::Dynamic;
850        if !self
851            .old_positions
852            .iter()
853            .any(|&(id, _, _)| swept_body(self.bodies[id].core()))
854        {
855            return 0;
856        }
857        let mut targets = std::mem::take(&mut self.ccd_targets);
858        let mut first = std::mem::take(&mut self.ccd_first);
859        let mut order = std::mem::take(&mut self.ccd_order);
860        let mut wide = std::mem::take(&mut self.ccd_wide);
861        let mut prefix_max_x = std::mem::take(&mut self.ccd_prefix_max_x);
862        targets.clear();
863        first.clear();
864        order.clear();
865        wide.clear();
866        // Fixed bodies (floors/walls) often span the whole arena in X; separating
867        // them keeps `prefix_max_x` tight for dynamic targets so sweep queries
868        // terminate after a few local neighbors instead of scanning the full list.
869        for &(id, origin, rotation) in &self.old_positions {
870            let body = self.bodies[id].core();
871            let is_fixed = body.kind == Kind::Fixed;
872            first.push(targets.len());
873            for &child in &body.colliders {
874                let ti = targets.len();
875                let target = CcdTarget::new(id, &self.colliders[child], body, origin, rotation);
876                if !target.sensor {
877                    if is_fixed || (target.swept_bounds.max.x - target.swept_bounds.min.x) > 8.0 {
878                        wide.push(ti);
879                    } else {
880                        order.push(ti);
881                    }
882                }
883                targets.push(target);
884            }
885        }
886        first.push(targets.len());
887        order.sort_unstable_by(|&a, &b| {
888            targets[a]
889                .swept_bounds
890                .min
891                .x
892                .total_cmp(&targets[b].swept_bounds.min.x)
893                .then(a.cmp(&b))
894        });
895        prefix_max_x.clear();
896        let mut running_max = f32::NEG_INFINITY;
897        for &ti in &order {
898            running_max = running_max.max(targets[ti].swept_bounds.max.x);
899            prefix_max_x.push(running_max);
900        }
901
902        let has_disabled = !self.disabled_joint_pairs.is_empty();
903        let planar = self.planar;
904        let mut hits = 0;
905        for (index, &(id, start_origin, start_rotation)) in self.old_positions.iter().enumerate() {
906            if !swept_body(self.bodies[id].core()) {
907                continue;
908            }
909            let mut closest = 1.;
910            let mut best_ti = usize::MAX;
911            let mut correction = None;
912            for own_ti in first[index]..first[index + 1] {
913                let own = targets[own_ti];
914                if own.sensor {
915                    continue;
916                }
917                let radius = match own.shape {
918                    Shape::Ball(r) => r,
919                    Shape::Box(h) => h.length(),
920                    _ => continue,
921                };
922                let start = own.start;
923                let end = own.pose.position;
924                let minimum_motion = if matches!(own.shape, Shape::Ball(_)) {
925                    radius * radius * 0.04
926                } else {
927                    1e-12
928                };
929                let own_swept = Bounds {
930                    min: start.min(end) - Vec3::splat(radius),
931                    max: start.max(end) + Vec3::splat(radius),
932                };
933                let mut test_target = |ti: usize| {
934                    let target = targets[ti];
935                    if target.swept_bounds.max.x < own_swept.min.x
936                        || target.swept_bounds.min.x > own_swept.max.x
937                        || target.swept_bounds.min.y > own_swept.max.y
938                        || target.swept_bounds.max.y < own_swept.min.y
939                        || target.swept_bounds.min.z > own_swept.max.z
940                        || target.swept_bounds.max.z < own_swept.min.z
941                    {
942                        return;
943                    }
944                    if target.body == id
945                        || own.membership & target.filter == 0
946                        || target.membership & own.filter == 0
947                    {
948                        return;
949                    }
950                    if has_disabled && self.joint_contacts_disabled(id, target.body) {
951                        return;
952                    }
953                    let target_pose = target.pose;
954                    let relative_start = start - target.start + target_pose.position;
955                    if relative_start.distance_squared(end) < minimum_motion {
956                        return;
957                    }
958                    let swept = Bounds {
959                        min: relative_start.min(end) - Vec3::splat(radius),
960                        max: relative_start.max(end) + Vec3::splat(radius),
961                    };
962                    if !swept.intersects(target.bounds) {
963                        return;
964                    }
965                    let impact = match (own.shape, target.shape) {
966                        (Shape::Ball(r), shape) => geometry::sweep_ball(
967                            relative_start,
968                            end,
969                            r,
970                            shape,
971                            target_pose.position,
972                            target_pose.rotation,
973                            planar,
974                        ),
975                        (Shape::Box(h), Shape::Box(target_half)) => geometry::sweep_box(
976                            relative_start,
977                            end,
978                            h,
979                            own.pose.rotation,
980                            target_half,
981                            &target_pose,
982                        ),
983                        _ => None,
984                    };
985                    if let Some((t, n)) = impact
986                        && (t < closest || (t == closest && ti < best_ti))
987                        && (end - relative_start).dot(n) < -1e-7
988                    {
989                        closest = t;
990                        best_ti = ti;
991                        correction =
992                            Some(relative_start + (end - relative_start) * t + n * 0.00002 - end);
993                    }
994                };
995                for &ti in &wide {
996                    test_target(ti);
997                }
998                let end_k =
999                    order.partition_point(|&ti| targets[ti].swept_bounds.min.x <= own_swept.max.x);
1000                for k in (0..end_k).rev() {
1001                    if prefix_max_x[k] < own_swept.min.x {
1002                        break;
1003                    }
1004                    test_target(order[k]);
1005                }
1006            }
1007            if let Some(delta) = correction {
1008                self.bodies[id].core_mut().position += delta;
1009                // Later swept bodies observe this corrected pose as their target.
1010                let body = self.bodies[id].core();
1011                let mut need_resort = false;
1012                for (offset, &child) in body.colliders.iter().enumerate() {
1013                    let ti = first[index] + offset;
1014                    let prev = targets[ti];
1015                    let was_wide =
1016                        prev.sensor || (prev.swept_bounds.max.x - prev.swept_bounds.min.x) > 8.0;
1017                    let mut updated = CcdTarget::new(
1018                        id,
1019                        &self.colliders[child],
1020                        body,
1021                        start_origin,
1022                        start_rotation,
1023                    );
1024                    if !was_wide
1025                        && updated.swept_bounds.min.x >= prev.swept_bounds.min.x
1026                        && updated.swept_bounds.max.x <= prev.swept_bounds.max.x
1027                    {
1028                        // Keep the conservative X envelope so `order` and `prefix_max_x`
1029                        // remain valid without O(N) resorting on every hit.
1030                        updated.swept_bounds.min.x = prev.swept_bounds.min.x;
1031                        updated.swept_bounds.max.x = prev.swept_bounds.max.x;
1032                    } else if !was_wide {
1033                        need_resort = true;
1034                    }
1035                    targets[ti] = updated;
1036                }
1037                if need_resort {
1038                    for i in 1..order.len() {
1039                        let key = order[i];
1040                        let key_x = targets[key].swept_bounds.min.x;
1041                        let mut j = i;
1042                        while j > 0 {
1043                            let prev = order[j - 1];
1044                            let prev_x = targets[prev].swept_bounds.min.x;
1045                            if prev_x > key_x || (prev_x == key_x && prev > key) {
1046                                order[j] = prev;
1047                                j -= 1;
1048                            } else {
1049                                break;
1050                            }
1051                        }
1052                        order[j] = key;
1053                    }
1054                    let mut running = f32::NEG_INFINITY;
1055                    for (slot, &ti) in prefix_max_x.iter_mut().zip(&order) {
1056                        running = running.max(targets[ti].swept_bounds.max.x);
1057                        *slot = running;
1058                    }
1059                }
1060                hits += 1;
1061            }
1062        }
1063        self.ccd_targets = targets;
1064        self.ccd_first = first;
1065        self.ccd_order = order;
1066        self.ccd_wide = wide;
1067        self.ccd_prefix_max_x = prefix_max_x;
1068        hits
1069    }
1070    fn solve_velocities(&mut self, stats: &mut StepStats) {
1071        // Waking is complete and velocity iterations do not change body poses,
1072        // masses or contact normals. Filter sleeping constraints once and reuse
1073        // the normal denominator across all velocity iterations.
1074        self.active_constraints.clear();
1075        for (i, c) in self.constraints.iter_mut().enumerate() {
1076            let a = self.bodies[c.a].core();
1077            let b = self.bodies[c.b].core();
1078            if a.sleeping && (b.sleeping || b.kind != Kind::Dynamic)
1079                || b.sleeping && a.kind != Kind::Dynamic
1080            {
1081                continue;
1082            }
1083            c.ra = c.point - a.world_com();
1084            c.rb = c.point - b.world_com();
1085            c.normal_denominator = if a.contact_inv_mass() + b.contact_inv_mass() == 0. {
1086                0.
1087            } else {
1088                effective_mass(a, b, c.ra, c.rb, c.normal)
1089            };
1090            self.active_constraints.push(i);
1091        }
1092        let has_joints = !self.joints.is_empty();
1093        if self.active_constraints.is_empty() && !has_joints {
1094            return;
1095        }
1096        for _ in 0..self.settings.velocity_iterations {
1097            for &ci in &self.active_constraints {
1098                let c = &mut self.constraints[ci];
1099                let (a, b) = self.bodies.two_mut(c.a, c.b);
1100                let a = a.core_mut();
1101                let b = b.core_mut();
1102                stats.velocity_constraints += 1;
1103                let (ra, rb) = (c.ra, c.rb);
1104                let denom = c.normal_denominator;
1105                if denom <= 1e-10 {
1106                    continue;
1107                }
1108                let relative = b.offset_velocity(rb) - a.offset_velocity(ra);
1109                let change = (c.bounce - relative.dot(c.normal)) / denom;
1110                let accumulated = (c.normal_impulse + change).max(0.);
1111                let dj = accumulated - c.normal_impulse;
1112                c.normal_impulse = accumulated;
1113                if c.impact_approach > 0. {
1114                    c.impact_peak = c.impact_peak.max((accumulated - c.impact_baseline).max(0.));
1115                }
1116                if dj != 0. {
1117                    let j = c.normal * dj;
1118                    a.offset_impulse(-j, ra);
1119                    b.offset_impulse(j, rb);
1120                }
1121                let relative = b.offset_velocity(rb) - a.offset_velocity(ra);
1122                let tangent = relative - c.normal * relative.dot(c.normal);
1123                let mut candidate = c.tangent_impulse;
1124                if tangent != Vec3::ZERO
1125                    && let Some(t) = tangent.try_normalize()
1126                {
1127                    let denominator = effective_mass(a, b, ra, rb, t);
1128                    if denominator > 1e-10 {
1129                        candidate -= t * (relative.dot(t) / denominator);
1130                    }
1131                }
1132                // Re-clamp even at zero slip: a reduced normal load also reduces
1133                // the friction cone of an already accumulated tangent impulse.
1134                let new = if candidate == Vec3::ZERO
1135                    || candidate.length() <= c.static_friction * c.normal_impulse
1136                {
1137                    candidate
1138                } else {
1139                    candidate.clamp_length_max(c.friction * c.normal_impulse)
1140                };
1141                let j = new - c.tangent_impulse;
1142                c.tangent_impulse = new;
1143                if j != Vec3::ZERO {
1144                    a.offset_impulse(-j, ra);
1145                    b.offset_impulse(j, rb);
1146                }
1147                if c.rolling_resistance > 0. {
1148                    let relative = b.angular_velocity - a.angular_velocity;
1149                    if let Some(axis) = relative.try_normalize() {
1150                        let denominator = axis
1151                            .dot(a.contact_inverse_inertia(axis) + b.contact_inverse_inertia(axis));
1152                        if denominator > 1e-10 {
1153                            let new = (c.rolling_impulse
1154                                - axis * (relative.dot(axis) / denominator))
1155                                .clamp_length_max(c.rolling_resistance * c.normal_impulse);
1156                            let j = new - c.rolling_impulse;
1157                            c.rolling_impulse = new;
1158                            a.angular_velocity -= a.contact_inverse_inertia(j);
1159                            b.angular_velocity += b.contact_inverse_inertia(j);
1160                        }
1161                    }
1162                }
1163            }
1164            if has_joints {
1165                self.run_joints(JointPhase::Velocity, 0., stats);
1166            }
1167        }
1168    }
1169    fn solve_positions(&mut self) {
1170        let has_joints = !self.joints.is_empty();
1171        if self.active_constraints.is_empty() && !has_joints {
1172            return;
1173        }
1174        for _ in 0..self.settings.position_iterations {
1175            for &ci in &self.active_constraints {
1176                let c = &self.constraints[ci];
1177                let (a, b) = self.bodies.two_mut(c.a, c.b);
1178                let a = a.core_mut();
1179                let b = b.core_mut();
1180                if a.contact_inv_mass() + b.contact_inv_mass() == 0. {
1181                    continue;
1182                }
1183                let ra_off = a.rotation * c.local_a;
1184                let rb_off = b.rotation * c.local_b;
1185                let pa = a.position + ra_off;
1186                let pb = b.position + rb_off;
1187                let depth = -(pb - pa).dot(c.normal);
1188                if depth <= 0.0005 {
1189                    continue;
1190                }
1191                let ra = if a.local_com == Vec3::ZERO {
1192                    ra_off
1193                } else {
1194                    a.rotation * (c.local_a - a.local_com)
1195                };
1196                let rb = if b.local_com == Vec3::ZERO {
1197                    rb_off
1198                } else {
1199                    b.rotation * (c.local_b - b.local_com)
1200                };
1201                let denom = effective_mass(a, b, ra, rb, c.normal);
1202                if denom <= 1e-10 {
1203                    continue;
1204                }
1205                let j = c.normal * ((depth - 0.0005).min(0.2) * 0.4 / denom);
1206                a.position_impulse(-j, ra.cross(-j));
1207                b.position_impulse(j, rb.cross(j));
1208            }
1209            if has_joints {
1210                self.run_joints(JointPhase::Position, 0., &mut StepStats::default());
1211            }
1212        }
1213    }
1214    pub(crate) fn cast_ray(
1215        &self,
1216        origin: Vec3,
1217        direction: Vec3,
1218        max_distance: f32,
1219    ) -> Option<(RigidBodyHandle, ColliderHandle, f32, Vec3, Vec3)> {
1220        self.cast_sphere(origin, direction, max_distance, 0., u32::MAX, None)
1221    }
1222    /// Current-pose sphere sweep. Radius zero preserves the raycast behavior.
1223    pub(crate) fn cast_sphere(
1224        &self,
1225        origin: Vec3,
1226        direction: Vec3,
1227        max_distance: f32,
1228        radius: f32,
1229        mask: u32,
1230        ignore: Option<RigidBodyHandle>,
1231    ) -> Option<(RigidBodyHandle, ColliderHandle, f32, Vec3, Vec3)> {
1232        if !origin.is_finite()
1233            || !direction.is_finite()
1234            || !max_distance.is_finite()
1235            || max_distance < 0.
1236            || !radius.is_finite()
1237            || !(0. ..=1000.).contains(&radius)
1238        {
1239            return None;
1240        }
1241        let direction = direction.try_normalize()?;
1242        let mut best = None;
1243        let mut limit = max_distance;
1244        for (id, c) in self.colliders.iter() {
1245            if c.sensor || c.membership & mask == 0 || c.parent == ignore {
1246                continue;
1247            }
1248            let body = c.parent.unwrap();
1249            let b = self.bodies[body].core();
1250            let pose = c.pose(b);
1251            let (d, n) =
1252                geometry::distance(c.shape, pose.position, pose.rotation, origin, self.planar);
1253            let hit = if d <= radius {
1254                Some((0., n))
1255            } else {
1256                geometry::sweep_ball(
1257                    origin,
1258                    origin + direction * limit,
1259                    radius,
1260                    c.shape,
1261                    pose.position,
1262                    pose.rotation,
1263                    self.planar,
1264                )
1265                .map(|(t, n)| (t * limit, n))
1266            };
1267            if let Some((distance, normal)) = hit {
1268                limit = distance;
1269                best = Some((body, id, distance, origin + direction * distance, normal));
1270            }
1271        }
1272        best
1273    }
1274}
1275fn pair_key(a: ColliderHandle, b: ColliderHandle) -> (ColliderHandle, ColliderHandle) {
1276    if a < b { (a, b) } else { (b, a) }
1277}
1278fn effective_mass(
1279    a: &crate::body::Core,
1280    b: &crate::body::Core,
1281    ra: Vec3,
1282    rb: Vec3,
1283    n: Vec3,
1284) -> f32 {
1285    a.contact_inv_mass()
1286        + b.contact_inv_mass()
1287        + n.dot(
1288            a.contact_inverse_inertia(ra.cross(n)).cross(ra)
1289                + b.contact_inverse_inertia(rb.cross(n)).cross(rb),
1290        )
1291}
1292fn rotation_delta(from: Quat, to: Quat) -> Vec3 {
1293    let mut delta = (to * from.conjugate()).normalize();
1294    if delta.w < 0. {
1295        delta = -delta;
1296    }
1297    let axis = Vec3::new(delta.x, delta.y, delta.z);
1298    let length = axis.length();
1299    if length < 1e-9 {
1300        Vec3::ZERO
1301    } else {
1302        axis * (2. * length.atan2(delta.w) / length)
1303    }
1304}
1305
1306#[cfg(all(test, any(feature = "dim2", feature = "dim3")))]
1307mod journey200_037 {
1308    use super::*;
1309    use crate::PhysicsError;
1310
1311    const DT: f32 = 1. / 120.;
1312
1313    macro_rules! sleep_tests {
1314        ($module:ident, $dimension:ident) => {
1315            mod $module {
1316                use super::*;
1317                use crate::$dimension::{
1318                    ColliderBuilder, JointBuilder, PhysicsWorld, RigidBodyBuilder, Vector,
1319                };
1320
1321                fn world() -> PhysicsWorld {
1322                    let mut world = PhysicsWorld::default();
1323                    world
1324                        .set_solver_settings(SolverSettings {
1325                            sleep_delay: 0.05,
1326                            ..SolverSettings::default()
1327                        })
1328                        .unwrap();
1329                    world
1330                }
1331
1332                fn body(world: &mut PhysicsWorld, x: f32) -> RigidBodyHandle {
1333                    world
1334                        .insert(
1335                            RigidBodyBuilder::dynamic().translation(Vector::X * x),
1336                            ColliderBuilder::ball(1.),
1337                        )
1338                        .0
1339                }
1340
1341                fn settle(world: &mut PhysicsWorld) {
1342                    for _ in 0..20 {
1343                        world.step(DT);
1344                    }
1345                }
1346
1347                #[test]
1348                fn checked_inspection_and_wake_reject_stale_and_nondynamic_bodies() {
1349                    let mut world = world();
1350                    let fixed = world.insert_body(RigidBodyBuilder::fixed()).unwrap();
1351                    let kinematic = world
1352                        .insert_body(RigidBodyBuilder::kinematic_position_based())
1353                        .unwrap();
1354                    let dynamic = body(&mut world, 0.);
1355                    assert_eq!(
1356                        world.sleep_stats(),
1357                        SleepStats {
1358                            awake_bodies: 1,
1359                            sleeping_bodies: 0,
1360                            wake_requests: 1,
1361                        }
1362                    );
1363                    settle(&mut world);
1364                    for h in [fixed, kinematic] {
1365                        let before = world.sleep_state(h).unwrap();
1366                        assert!(!before.dynamic && !before.sleeping && !before.wake_requested);
1367                        assert_eq!(before.quiet_time, 0.);
1368                        assert_eq!(world.wake_body(h), Err(PhysicsError::InvalidBody));
1369                        assert_eq!(world.sleep_state(h), Some(before));
1370                    }
1371                    let sleeping = world.sleep_state(dynamic).unwrap();
1372                    assert!(sleeping.dynamic && sleeping.sleeping && !sleeping.wake_requested);
1373                    assert_eq!(sleeping.quiet_time, world.solver_settings().sleep_delay);
1374                    assert_eq!(world.wake_body(dynamic), Ok(true));
1375                    assert_eq!(world.wake_body(dynamic), Ok(false));
1376                    let awake = world.sleep_state(dynamic).unwrap();
1377                    assert!(!awake.sleeping && awake.wake_requested);
1378                    assert_eq!(awake.quiet_time, 0.);
1379                    assert!(world.remove_body(dynamic));
1380                    let replacement = body(&mut world, 0.);
1381                    assert_eq!(dynamic.index, replacement.index);
1382                    assert_ne!(dynamic, replacement);
1383                    let stats = world.sleep_stats();
1384                    assert_eq!(world.sleep_state(dynamic), None);
1385                    assert_eq!(world.wake_body(dynamic), Err(PhysicsError::InvalidHandle));
1386                    assert_eq!(world.sleep_stats(), stats);
1387                    assert_eq!(stats.awake_bodies, 1);
1388                    assert_eq!(stats.sleeping_bodies, 0);
1389                }
1390
1391                #[test]
1392                fn live_counts_update_before_step_without_consuming_requests_or_events() {
1393                    let mut world = world();
1394                    let a = body(&mut world, 0.);
1395                    let b = body(&mut world, 2.);
1396                    settle(&mut world);
1397                    assert_eq!(world.sleep_stats().sleeping_bodies, 2);
1398                    assert_eq!(world.last_step.sleeping_bodies, 2);
1399                    let ca = world.bodies[a].colliders()[0];
1400                    let cb = world.bodies[b].colliders()[0];
1401                    assert!(world.contact_events().is_empty());
1402                    assert!(world.contact_pair(ca, cb).is_some());
1403                    assert_eq!(world.wake_body(a), Ok(true));
1404                    let stats = world.sleep_stats();
1405                    assert_eq!(stats.awake_bodies, 1);
1406                    assert_eq!(stats.sleeping_bodies, 1);
1407                    assert_eq!(stats.wake_requests, 1);
1408                    assert_eq!(world.last_step.sleeping_bodies, 2);
1409                    assert!(world.sleep_state(b).unwrap().sleeping);
1410                    assert!(world.contact_events().is_empty());
1411                    assert!(
1412                        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1413                            world.step(f32::NAN);
1414                        }))
1415                        .is_err()
1416                    );
1417                    assert_eq!(world.sleep_stats(), stats);
1418                    let step = world.step(DT);
1419                    assert_eq!(step.sleeping_bodies, 0);
1420                    assert_eq!(world.sleep_stats().awake_bodies, 2);
1421                    assert_eq!(world.sleep_stats().wake_requests, 0);
1422                    assert!(world.contact_events().is_empty());
1423                    assert_eq!(world.contacts().count(), 1);
1424                    assert!(world.remove_body(a));
1425                    assert_eq!(world.sleep_stats().awake_bodies, 1);
1426                    world.step(DT);
1427                    assert_eq!(world.contact_events(), &[ContactEvent::Stopped(ca, cb)]);
1428                }
1429
1430                #[test]
1431                fn new_fixed_and_stationary_kinematic_contacts_wake_sleeping_islands() {
1432                    for obstacle in [
1433                        RigidBodyBuilder::fixed(),
1434                        RigidBodyBuilder::kinematic_position_based(),
1435                    ] {
1436                        let mut world = world();
1437                        let a = body(&mut world, 0.);
1438                        let b = body(&mut world, 2.);
1439                        let isolated = body(&mut world, 10.);
1440                        settle(&mut world);
1441                        assert_eq!(world.sleep_stats().sleeping_bodies, 3);
1442                        let ca = world.bodies[a].colliders()[0];
1443                        let (_, obstacle) = world.insert(
1444                            obstacle.translation(-Vector::X * 1.5),
1445                            ColliderBuilder::ball(1.),
1446                        );
1447                        world.step(DT);
1448                        assert!(!world.sleep_state(a).unwrap().sleeping);
1449                        assert!(!world.sleep_state(b).unwrap().sleeping);
1450                        assert!(world.sleep_state(isolated).unwrap().sleeping);
1451                        assert!(world.bodies[a].translation().x > 0.);
1452                        assert_eq!(world.sleep_stats().awake_bodies, 2);
1453                        assert_eq!(world.sleep_stats().sleeping_bodies, 1);
1454                        assert_eq!(world.sleep_stats().wake_requests, 0);
1455                        assert_eq!(
1456                            world.contact_events(),
1457                            &[ContactEvent::Started(ca, obstacle)]
1458                        );
1459                        world.step(DT);
1460                        assert!(world.contact_events().is_empty());
1461                    }
1462                }
1463
1464                #[test]
1465                fn sensor_insertion_and_explicit_wakes_leave_unconnected_sleepers_alone() {
1466                    let mut world = world();
1467                    let a = body(&mut world, 0.);
1468                    let b = body(&mut world, 4.);
1469                    settle(&mut world);
1470                    let (_, sensor) = world.insert(
1471                        RigidBodyBuilder::fixed().translation(Vector::X * 2.),
1472                        ColliderBuilder::ball(4.).sensor(true),
1473                    );
1474                    world.step(DT);
1475                    assert_eq!(world.sleep_stats().sleeping_bodies, 2);
1476                    assert_eq!(world.contacts().count(), 2);
1477                    assert!(world.contacts().all(|c| c.sensor));
1478                    assert_eq!(world.wake_body(a), Ok(true));
1479                    world.step(DT);
1480                    assert!(!world.sleep_state(a).unwrap().sleeping);
1481                    assert!(world.sleep_state(b).unwrap().sleeping);
1482                    assert!(world.contact_events().is_empty());
1483                    assert!(world.remove_collider(sensor).is_ok());
1484                    world.step(DT);
1485                    assert!(world.sleep_state(b).unwrap().sleeping);
1486                }
1487
1488                #[test]
1489                fn explicit_wake_propagates_through_joints_on_the_next_step() {
1490                    let mut world = world();
1491                    let a = body(&mut world, 0.);
1492                    let b = body(&mut world, 4.);
1493                    let isolated = body(&mut world, 10.);
1494                    world.insert_joint(a, b, JointBuilder::fixed()).unwrap();
1495                    settle(&mut world);
1496                    assert_eq!(world.sleep_stats().sleeping_bodies, 3);
1497                    assert_eq!(world.wake_body(a), Ok(true));
1498                    assert!(world.sleep_state(b).unwrap().sleeping);
1499                    world.step(DT);
1500                    assert!(!world.sleep_state(b).unwrap().sleeping);
1501                    assert!(world.sleep_state(isolated).unwrap().sleeping);
1502                    assert_eq!(world.sleep_stats().awake_bodies, 2);
1503                }
1504
1505                #[test]
1506                fn collider_attachment_and_pose_edits_wake_current_contacts() {
1507                    for attach in [false, true] {
1508                        let mut world = world();
1509                        let dynamic = body(&mut world, 0.);
1510                        let (fixed, collider) = world.insert(
1511                            RigidBodyBuilder::fixed().translation(Vector::X * 5.),
1512                            ColliderBuilder::ball(1.),
1513                        );
1514                        settle(&mut world);
1515                        assert!(world.sleep_state(dynamic).unwrap().sleeping);
1516                        if attach {
1517                            world
1518                                .attach_collider(
1519                                    fixed,
1520                                    ColliderBuilder::ball(1.).translation(-Vector::X * 4.),
1521                                )
1522                                .unwrap();
1523                        } else {
1524                            world
1525                                .set_collider_pose(collider, -Vec3::X * 4., Quat::IDENTITY)
1526                                .unwrap();
1527                        }
1528                        world.step(DT);
1529                        assert!(!world.sleep_state(dynamic).unwrap().sleeping);
1530                        assert!(world.bodies[dynamic].translation().x < 0.);
1531                        assert_eq!(world.sleep_stats().awake_bodies, 1);
1532                    }
1533                }
1534
1535                #[test]
1536                fn quiet_time_is_capped_and_disabling_sleep_resets_live_state() {
1537                    let mut world = world();
1538                    let h = body(&mut world, 0.);
1539                    world.step(DT);
1540                    let initial = world.sleep_state(h).unwrap();
1541                    assert!(!initial.sleeping && !initial.wake_requested);
1542                    assert!(initial.quiet_time > 0. && initial.quiet_time < 0.05);
1543                    settle(&mut world);
1544                    assert_eq!(world.sleep_state(h).unwrap().quiet_time, 0.05);
1545                    let settings = world.solver_settings();
1546                    world
1547                        .set_solver_settings(SolverSettings {
1548                            allow_sleep: false,
1549                            ..settings
1550                        })
1551                        .unwrap();
1552                    assert_eq!(world.sleep_stats().awake_bodies, 1);
1553                    assert_eq!(world.sleep_stats().wake_requests, 1);
1554                    settle(&mut world);
1555                    assert_eq!(world.sleep_stats().awake_bodies, 1);
1556                    assert_eq!(world.sleep_stats().sleeping_bodies, 0);
1557                    assert_eq!(world.sleep_state(h).unwrap().quiet_time, 0.);
1558                    world.remove_body(h);
1559                    assert_eq!(world.sleep_stats(), SleepStats::default());
1560                }
1561            }
1562        };
1563    }
1564
1565    #[cfg(feature = "dim2")]
1566    sleep_tests!(planar, d2);
1567    #[cfg(feature = "dim3")]
1568    sleep_tests!(spatial, d3);
1569}
1570
1571#[cfg(test)]
1572mod journey400_221 {
1573    use super::*;
1574    macro_rules! cache_test {
1575        ($module:ident, $dimension:ident) => {
1576            mod $module {
1577                use super::*;
1578                use crate::$dimension::{
1579                    ColliderBuilder, JointBuilder, PhysicsWorld, RigidBodyBuilder, RigidBodyPose,
1580                    TeleportOptions, Vector, VelocityPolicy,
1581                };
1582                #[test]
1583                fn teleport_revision_clears_attached_joint_impulses_at_refresh() {
1584                    let mut world = PhysicsWorld::default();
1585                    let anchor = world.insert_body(RigidBodyBuilder::fixed()).unwrap();
1586                    let (body, _) = world.insert(
1587                        RigidBodyBuilder::dynamic()
1588                            .translation(Vector::X)
1589                            .linvel(Vector::X),
1590                        ColliderBuilder::ball(0.2),
1591                    );
1592                    let joint = world
1593                        .insert_joint(anchor, body, JointBuilder::distance(1.))
1594                        .unwrap();
1595                    world.step(1. / 60.);
1596                    assert!(
1597                        world.joints[joint]
1598                            .cache
1599                            .iter()
1600                            .any(|row| row.impulse != 0.)
1601                    );
1602                    let old_revisions = world.joints[joint].revisions;
1603                    world
1604                        .try_teleport_body(
1605                            body,
1606                            RigidBodyPose {
1607                                translation: Vector::X * 1.1,
1608                                rotation: *world.bodies[body].rotation(),
1609                            },
1610                            TeleportOptions::new(VelocityPolicy::Clear),
1611                        )
1612                        .unwrap();
1613                    // The production pre-solve refresh must discard every cached
1614                    // row while retaining the joint and authored configuration.
1615                    world
1616                        .raw
1617                        .run_joints(JointPhase::Refresh, 1. / 60., &mut StepStats::default());
1618                    assert!(
1619                        world.joints[joint]
1620                            .cache
1621                            .iter()
1622                            .all(|row| row.impulse == 0.)
1623                    );
1624                    assert_eq!(world.joints[joint].dt, 0.);
1625                    assert_ne!(world.joints[joint].revisions, old_revisions);
1626                    assert_eq!(world.joints[joint].bodies(), [anchor, body]);
1627                }
1628            }
1629        };
1630    }
1631    #[cfg(feature = "dim2")]
1632    cache_test!(planar, d2);
1633    #[cfg(feature = "dim3")]
1634    cache_test!(spatial, d3);
1635}