ferravex_dynamics/
world.rs

1use crate::{collision::*, math::*, *};
2
3struct Slot<const D: usize> {
4    generation: u32,
5    body: Option<Body<D>>,
6}
7#[derive(Clone, Copy)]
8struct Proxy<const D: usize> {
9    index: u32,
10    min: [f32; D],
11    max: [f32; D],
12}
13#[derive(Clone, Copy)]
14struct Motion<const D: usize> {
15    index: usize,
16    position: [f32; D],
17    velocity: [f32; D],
18}
19#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
20pub struct StepStats {
21    pub bodies: usize,
22    pub broadphase_tests: usize,
23    pub candidate_pairs: usize,
24    pub contacts: usize,
25    pub ccd_impacts: usize,
26    /// Remaining movement was discarded to stay conservative after this body's impact budget.
27    pub ccd_budget_stops: usize,
28}
29
30/// Reuses bounded scratch buffers and returns an error rather than dropping
31/// overflowing collision pairs. Failed steps restore all body motion and forces.
32/// Buffers grow lazily to the configured bounds, then reuse their storage.
33pub struct PhysicsWorld<const D: usize> {
34    config: WorldConfig<D>,
35    slots: Vec<Slot<D>>,
36    free: Vec<usize>,
37    len: usize,
38    proxies: Vec<Proxy<D>>,
39    pairs: Vec<u64>,
40    backup: Vec<Motion<D>>,
41    contacts: Vec<Contact<D>>,
42    next_contacts: Vec<Contact<D>>,
43    events: Vec<ContactEvent<D>>,
44    pending_stops: Vec<ContactEvent<D>>,
45}
46impl<const D: usize> PhysicsWorld<D> {
47    /// Construct a world with default finite work/memory limits.
48    /// Panics for dimensions other than 2/3 or invalid gravity; use `with_config`
49    /// for fallible construction from untrusted settings.
50    pub fn new(gravity: [f32; D]) -> Self {
51        Self::with_config(WorldConfig::new(gravity)).expect("valid physics world configuration")
52    }
53    pub fn with_config(config: WorldConfig<D>) -> Result<Self, PhysicsError> {
54        if D != 2 && D != 3 {
55            return Err(PhysicsError::InvalidDimension);
56        }
57        if !valid(config.gravity)
58            || config.max_bodies == 0
59            || config.max_bodies > 1_000_000
60            || config.max_pairs == 0
61            || config.max_pairs > 10_000_000
62            || config.max_pair_tests == 0
63            || config.max_pair_tests > 100_000_000
64            || !(1..=64).contains(&config.solver_iterations)
65            || !(1..=16).contains(&config.ccd_iterations)
66            || !config.contact_slop.is_finite()
67            || !(1e-6..=0.1).contains(&config.contact_slop)
68        {
69            return Err(PhysicsError::InvalidConfiguration);
70        }
71        Ok(Self {
72            config,
73            slots: Vec::new(),
74            free: Vec::new(),
75            len: 0,
76            proxies: Vec::new(),
77            pairs: Vec::new(),
78            backup: Vec::new(),
79            contacts: Vec::new(),
80            next_contacts: Vec::new(),
81            events: Vec::new(),
82            pending_stops: Vec::new(),
83        })
84    }
85    pub fn config(&self) -> WorldConfig<D> {
86        self.config
87    }
88    pub fn len(&self) -> usize {
89        self.len
90    }
91    pub fn is_empty(&self) -> bool {
92        self.len == 0
93    }
94    pub fn set_gravity(&mut self, gravity: [f32; D]) -> Result<(), PhysicsError> {
95        if !valid(gravity) {
96            return Err(PhysicsError::InvalidConfiguration);
97        }
98        self.config.gravity = gravity;
99        Ok(())
100    }
101    pub fn insert(&mut self, desc: BodyDesc<D>) -> Result<BodyHandle, PhysicsError> {
102        if !desc.valid() || desc.kind == BodyKind::Static && desc.velocity != [0.; D] {
103            return Err(PhysicsError::InvalidBody);
104        }
105        if self.len >= self.config.max_bodies {
106            return Err(PhysicsError::BodyCapacity);
107        }
108        let body = Body {
109            desc,
110            force: [0.; D],
111        };
112        let index = if let Some(index) = self.free.pop() {
113            self.slots[index].body = Some(body);
114            index
115        } else {
116            // Retired generation-overflow slots count against storage capacity.
117            if self.slots.len() >= self.config.max_bodies {
118                return Err(PhysicsError::BodyCapacity);
119            }
120            self.slots.push(Slot {
121                generation: 0,
122                body: Some(body),
123            });
124            self.slots.len() - 1
125        };
126        self.len += 1;
127        Ok(self.handle(index))
128    }
129    fn handle(&self, index: usize) -> BodyHandle {
130        BodyHandle {
131            index: index as u32,
132            generation: self.slots[index].generation,
133        }
134    }
135    pub fn body(&self, handle: BodyHandle) -> Option<&Body<D>> {
136        let slot = self.slots.get(handle.index as usize)?;
137        (slot.generation == handle.generation)
138            .then_some(slot.body.as_ref())
139            .flatten()
140    }
141    pub fn body_mut(&mut self, handle: BodyHandle) -> Option<&mut Body<D>> {
142        let slot = self.slots.get_mut(handle.index as usize)?;
143        (slot.generation == handle.generation)
144            .then_some(slot.body.as_mut())
145            .flatten()
146    }
147    pub fn bodies(&self) -> impl Iterator<Item = (BodyHandle, &Body<D>)> {
148        self.slots
149            .iter()
150            .enumerate()
151            .filter_map(|(i, s)| s.body.as_ref().map(|b| (self.handle(i), b)))
152    }
153    /// Removal invalidates the handle. Its outstanding contacts generate Stopped
154    /// events on the next successful step, once each, including sensor contacts.
155    pub fn remove(&mut self, handle: BodyHandle) -> Option<Body<D>> {
156        let slot = self.slots.get_mut(handle.index as usize)?;
157        if slot.generation != handle.generation {
158            return None;
159        }
160        let body = slot.body.take()?;
161        if slot.generation != u32::MAX {
162            slot.generation += 1;
163            self.free.push(handle.index as usize);
164        }
165        self.len -= 1;
166        self.contacts.retain(|contact| {
167            if contact.a == handle || contact.b == handle {
168                self.pending_stops.push(ContactEvent {
169                    kind: ContactEventKind::Stopped,
170                    contact: *contact,
171                });
172                false
173            } else {
174                true
175            }
176        });
177        Some(body)
178    }
179    pub fn contacts(&self) -> &[Contact<D>] {
180        &self.contacts
181    }
182    /// Started/Stopped transitions from the last successful step. Persistent
183    /// overlaps are available through `contacts`, not repeated Started events.
184    pub fn events(&self) -> &[ContactEvent<D>] {
185        &self.events
186    }
187
188    /// Advance exactly one timestep in (0, 0.1] seconds. Use a fixed dt, commonly
189    /// 1/120, from the caller's fixed clock. Forces last for one successful step.
190    pub fn step(&mut self, dt: f32) -> Result<StepStats, PhysicsError> {
191        if !dt.is_finite() || dt <= 0. || dt > 0.1 {
192            return Err(PhysicsError::InvalidTimestep);
193        }
194        self.backup.clear();
195        for (index, slot) in self.slots.iter().enumerate() {
196            if let Some(body) = &slot.body
197                && body.desc.kind != BodyKind::Static
198            {
199                self.backup.push(Motion {
200                    index,
201                    position: body.desc.position,
202                    velocity: body.desc.velocity,
203                });
204            }
205        }
206        let result = self.advance(dt);
207        if result.is_err() {
208            for m in &self.backup {
209                let b = self.slots[m.index].body.as_mut().unwrap();
210                b.desc.position = m.position;
211                b.desc.velocity = m.velocity;
212            }
213        }
214        result
215    }
216    fn advance(&mut self, dt: f32) -> Result<StepStats, PhysicsError> {
217        let mut stats = StepStats {
218            bodies: self.len,
219            ..StepStats::default()
220        };
221        let mut any_ccd = false;
222        for slot in &mut self.slots {
223            let Some(body) = &mut slot.body else {
224                continue;
225            };
226            let inv_mass = body.inv_mass();
227            if inv_mass > 0. {
228                let acceleration = add(
229                    mul(self.config.gravity, body.desc.gravity_scale),
230                    mul(body.force, inv_mass),
231                );
232                body.desc.velocity = mul(
233                    add(body.desc.velocity, mul(acceleration, dt)),
234                    1. / (1. + body.desc.linear_damping * dt),
235                );
236            }
237            if !valid(body.desc.velocity) {
238                return Err(PhysicsError::NumericalLimit);
239            }
240            if body.desc.kind != BodyKind::Static {
241                if body.desc.ccd
242                    && inv_mass > 0.
243                    && matches!(body.desc.shape, Shape::Ball { .. })
244                    && !body.desc.sensor
245                {
246                    any_ccd = true;
247                } else {
248                    body.desc.position = add(body.desc.position, mul(body.desc.velocity, dt));
249                    if !valid(body.desc.position) {
250                        return Err(PhysicsError::NumericalLimit);
251                    }
252                }
253            } else if !valid(body.desc.position) {
254                return Err(PhysicsError::NumericalLimit);
255            }
256        }
257        if any_ccd {
258            for index in 0..self.slots.len() {
259                let Some(body) = self.slots[index].body.as_ref() else {
260                    continue;
261                };
262                if !body.desc.ccd || body.desc.sensor || body.inv_mass() == 0. {
263                    continue;
264                }
265                let Shape::Ball { radius } = body.desc.shape else {
266                    continue;
267                };
268                let desc = body.desc;
269                let mut p = desc.position;
270                let mut v = desc.velocity;
271                let mut remaining = dt;
272                let skin = self.config.contact_slop * 0.2;
273                for _ in 0..self.config.ccd_iterations {
274                    let displacement = mul(v, remaining);
275                    let distance = length(displacement);
276                    if distance < 1e-8 {
277                        remaining = 0.;
278                        break;
279                    }
280                    let direction = mul(displacement, distance.recip());
281                    let filter = QueryFilter {
282                        exclude: Some(self.handle(index)),
283                        layers: desc.layers,
284                        only_static: true,
285                        ..QueryFilter::default()
286                    };
287                    let Some(hit) = self.cast_ball(p, radius, direction, distance, filter) else {
288                        p = add(p, displacement);
289                        remaining = 0.;
290                        break;
291                    };
292                    stats.ccd_impacts += 1;
293                    p = add(p, mul(direction, (hit.distance - skin).max(0.)));
294                    let target = self.body(hit.body).unwrap();
295                    let normal_speed = dot(v, hit.normal);
296                    if normal_speed < 0. {
297                        let bounce = if normal_speed < -1. {
298                            desc.restitution.max(target.desc.restitution)
299                        } else {
300                            0.
301                        };
302                        let normal_change = -(1. + bounce) * normal_speed;
303                        v = add(v, mul(hit.normal, normal_change));
304                        let tangent = sub(v, mul(hit.normal, dot(v, hit.normal)));
305                        let tangent_speed = length(tangent);
306                        if tangent_speed > 1e-8 {
307                            let friction = (desc.friction * target.desc.friction).sqrt();
308                            v = sub(
309                                v,
310                                mul(tangent, (friction * normal_change / tangent_speed).min(1.)),
311                            );
312                        }
313                    }
314                    remaining *= 1. - (hit.distance / distance).clamp(0., 1.);
315                    // A body initially embedded in terrain is left for the discrete
316                    // penetration solver; repeated zero-time impacts cannot loop.
317                    if hit.distance < skin && dot(v, hit.normal) <= 1e-6 {
318                        break;
319                    }
320                }
321                if remaining > 1e-8 {
322                    stats.ccd_budget_stops += 1;
323                }
324                if !valid(p) {
325                    return Err(PhysicsError::NumericalLimit);
326                }
327                let body = self.slots[index].body.as_mut().unwrap();
328                body.desc.position = p;
329                body.desc.velocity = v;
330            }
331        }
332        self.broadphase(&mut stats)?;
333        let margin = self.config.contact_slop * 2.;
334        let slop = self.config.contact_slop;
335        // Sequential impulses plus iterative mass-weighted penetration correction.
336        // Stop early when an entire pass produces zero pose or velocity updates.
337        for _ in 0..self.config.solver_iterations {
338            let mut changed = false;
339            for &packed in &self.pairs {
340                let a = (packed >> 32) as usize;
341                let b = (packed as u32) as usize;
342                let (left, right) = self.slots.split_at_mut(b);
343                let a = left[a].body.as_mut().unwrap();
344                let b = right[0].body.as_mut().unwrap();
345                if a.desc.sensor || b.desc.sensor {
346                    continue;
347                }
348                let Some(m) = contact(
349                    a.desc.shape,
350                    a.desc.position,
351                    b.desc.shape,
352                    b.desc.position,
353                    margin,
354                ) else {
355                    continue;
356                };
357                if solve(a, b, m, slop) {
358                    changed = true;
359                }
360            }
361            if !changed {
362                break;
363            }
364        }
365        if self.slots.iter().filter_map(|s| s.body.as_ref()).any(|b| {
366            b.desc.kind != BodyKind::Static && (!valid(b.desc.position) || !valid(b.desc.velocity))
367        }) {
368            return Err(PhysicsError::NumericalLimit);
369        }
370        self.next_contacts.clear();
371        for &packed in &self.pairs {
372            let a = (packed >> 32) as usize;
373            let b = (packed as u32) as usize;
374            let aa = self.slots[a].body.as_ref().unwrap();
375            let bb = self.slots[b].body.as_ref().unwrap();
376            let is_sensor = aa.desc.sensor || bb.desc.sensor;
377            if let Some(m) = contact(
378                aa.desc.shape,
379                aa.desc.position,
380                bb.desc.shape,
381                bb.desc.position,
382                if is_sensor { 0. } else { margin },
383            ) {
384                self.next_contacts.push(Contact {
385                    a: self.handle(a),
386                    b: self.handle(b),
387                    normal: m.normal,
388                    penetration: m.penetration,
389                    sensor: is_sensor,
390                });
391            }
392        }
393        // `self.pairs` is sorted by `(a_index, b_index)` and `BodyHandle` orders by
394        // `index` first, so `self.next_contacts` is already sorted by `(c.a, c.b)`.
395        debug_assert!(
396            self.next_contacts
397                .windows(2)
398                .all(|w| (w[0].a, w[0].b) <= (w[1].a, w[1].b))
399        );
400        self.events.clear();
401        self.events.append(&mut self.pending_stops);
402        let mut old = 0;
403        let mut new = 0;
404        while old < self.contacts.len() || new < self.next_contacts.len() {
405            let a = self.contacts.get(old);
406            let b = self.next_contacts.get(new);
407            let order = match (a, b) {
408                (Some(a), Some(b)) => (a.a, a.b).cmp(&(b.a, b.b)),
409                (Some(_), None) => std::cmp::Ordering::Less,
410                (None, Some(_)) => std::cmp::Ordering::Greater,
411                (None, None) => unreachable!(),
412            };
413            match order {
414                std::cmp::Ordering::Less => {
415                    self.events.push(ContactEvent {
416                        kind: ContactEventKind::Stopped,
417                        contact: *a.unwrap(),
418                    });
419                    old += 1;
420                }
421                std::cmp::Ordering::Greater => {
422                    self.events.push(ContactEvent {
423                        kind: ContactEventKind::Started,
424                        contact: *b.unwrap(),
425                    });
426                    new += 1;
427                }
428                std::cmp::Ordering::Equal => {
429                    old += 1;
430                    new += 1;
431                }
432            }
433        }
434        std::mem::swap(&mut self.contacts, &mut self.next_contacts);
435        for body in self.slots.iter_mut().filter_map(|s| s.body.as_mut()) {
436            body.clear_forces();
437        }
438        stats.contacts = self.contacts.len();
439        Ok(stats)
440    }
441    fn broadphase(&mut self, stats: &mut StepStats) -> Result<(), PhysicsError> {
442        self.proxies.clear();
443        self.pairs.clear();
444        let margin = self.config.contact_slop * 2.;
445        let mut sum = [0.; D];
446        let mut squared = [0.; D];
447        for (index, slot) in self.slots.iter().enumerate() {
448            if let Some(b) = &slot.body {
449                let half = b.desc.shape.half().map(|v| v + margin);
450                for axis in 0..D {
451                    let c = b.desc.position[axis];
452                    sum[axis] += c;
453                    squared[axis] += c * c;
454                }
455                self.proxies.push(Proxy {
456                    index: index as u32,
457                    min: sub(b.desc.position, half),
458                    max: add(b.desc.position, half),
459                });
460            }
461        }
462        // Sweep along the axis with greatest center variance to avoid the common
463        // degenerate case of a vertical stack whose every X interval overlaps.
464        let count = self.len.max(1) as f32;
465        let axis = (0..D)
466            .max_by(|&a, &b| {
467                (squared[a] - sum[a] * sum[a] / count)
468                    .total_cmp(&(squared[b] - sum[b] * sum[b] / count))
469            })
470            .unwrap();
471        self.proxies.sort_unstable_by(|a, b| {
472            a.min[axis]
473                .total_cmp(&b.min[axis])
474                .then(a.index.cmp(&b.index))
475        });
476        for i in 0..self.proxies.len() {
477            let a = self.proxies[i];
478            let a_max = a.max[axis];
479            for b in &self.proxies[i + 1..] {
480                if b.min[axis] > a_max {
481                    break;
482                }
483                stats.broadphase_tests += 1;
484                if stats.broadphase_tests > self.config.max_pair_tests {
485                    return Err(PhysicsError::PairCapacity);
486                }
487                if (0..D).any(|ax| a.min[ax] > b.max[ax] || b.min[ax] > a.max[ax]) {
488                    continue;
489                }
490                let ai = a.index as usize;
491                let bi = b.index as usize;
492                let aa = self.slots[ai].body.as_ref().unwrap();
493                let bb = self.slots[bi].body.as_ref().unwrap();
494                if !aa.desc.layers.allows(bb.desc.layers) {
495                    continue;
496                }
497                if aa.desc.kind == BodyKind::Static
498                    && bb.desc.kind == BodyKind::Static
499                    && !aa.desc.sensor
500                    && !bb.desc.sensor
501                {
502                    continue;
503                }
504                if self.pairs.len() == self.config.max_pairs {
505                    return Err(PhysicsError::PairCapacity);
506                }
507                let lo = a.index.min(b.index);
508                let hi = a.index.max(b.index);
509                self.pairs.push((u64::from(lo) << 32) | u64::from(hi));
510            }
511        }
512        // Stable handle order makes solver order independent of the sweep axis.
513        self.pairs.sort_unstable();
514        stats.candidate_pairs = self.pairs.len();
515        Ok(())
516    }
517    fn query_allows(&self, handle: BodyHandle, body: &Body<D>, filter: QueryFilter) -> bool {
518        filter.exclude != Some(handle)
519            && filter.layers.allows(body.desc.layers)
520            && (filter.include_sensors || !body.desc.sensor)
521            && (!filter.only_static || body.desc.kind == BodyKind::Static)
522    }
523    /// Nearest ray hit, reflecting current body transforms immediately. Direction
524    /// is normalized, so `max_distance` and hit distances are in world units.
525    pub fn raycast(
526        &self,
527        origin: [f32; D],
528        direction: [f32; D],
529        max_distance: f32,
530        filter: QueryFilter,
531    ) -> Option<RayHit<D>> {
532        if !valid(origin)
533            || !valid(direction)
534            || !max_distance.is_finite()
535            || !(0. ..=1_000_000.).contains(&max_distance)
536        {
537            return None;
538        }
539        let direction = normalize(direction)?;
540        let mut max = max_distance;
541        let mut result = None;
542        for (handle, body) in self.bodies() {
543            if !self.query_allows(handle, body, filter) {
544                continue;
545            }
546            let hit = match body.desc.shape {
547                Shape::Ball { radius } => {
548                    ray_ball(origin, direction, body.desc.position, radius, max)
549                }
550                Shape::Box { half_extents } => {
551                    ray_box(origin, direction, body.desc.position, half_extents, max)
552                }
553            };
554            if let Some((distance, normal)) = hit {
555                if distance == max && result.is_some() {
556                    continue;
557                }
558                max = distance;
559                result = Some(RayHit {
560                    body: handle,
561                    distance,
562                    point: add(origin, mul(direction, distance)),
563                    normal,
564                });
565            }
566        }
567        result
568    }
569    /// Cast a circle/sphere continuously. `point` is the moving ball's center at
570    /// contact, not its surface point. Exact against boxes' rounded Minkowski
571    /// boundaries. Sensors are excluded by default; filtering is explicit.
572    pub fn cast_ball(
573        &self,
574        origin: [f32; D],
575        radius: f32,
576        direction: [f32; D],
577        max_distance: f32,
578        filter: QueryFilter,
579    ) -> Option<RayHit<D>> {
580        if !valid(origin)
581            || !valid(direction)
582            || !Shape::<D>::ball(radius).valid()
583            || !max_distance.is_finite()
584            || !(0. ..=1_000_000.).contains(&max_distance)
585        {
586            return None;
587        }
588        let direction = normalize(direction)?;
589        let mut max = max_distance;
590        let mut result = None;
591        for (handle, body) in self.bodies() {
592            if !self.query_allows(handle, body, filter) {
593                continue;
594            }
595            let hit = match body.desc.shape {
596                Shape::Ball {
597                    radius: target_radius,
598                } => {
599                    let hit = ray_ball(
600                        origin,
601                        direction,
602                        body.desc.position,
603                        radius + target_radius,
604                        max,
605                    );
606                    hit.filter(|(distance, normal)| {
607                        *distance > 1e-6
608                            || dot(direction, *normal) < 0.
609                            || length(sub(origin, body.desc.position))
610                                < radius + target_radius - 1e-5
611                    })
612                }
613                Shape::Box { half_extents } => sweep_ball_box(
614                    origin,
615                    radius,
616                    direction,
617                    body.desc.position,
618                    half_extents,
619                    max,
620                ),
621            };
622            if let Some((distance, normal)) = hit {
623                if distance == max && result.is_some() {
624                    continue;
625                }
626                max = distance;
627                result = Some(RayHit {
628                    body: handle,
629                    distance,
630                    point: add(origin, mul(direction, distance)),
631                    normal,
632                });
633            }
634        }
635        result
636    }
637}
638
639#[inline]
640fn solve<const D: usize>(a: &mut Body<D>, b: &mut Body<D>, m: Manifold<D>, slop: f32) -> bool {
641    let ma = a.inv_mass();
642    let mb = b.inv_mass();
643    let inverse_mass = ma + mb;
644    if inverse_mass == 0. {
645        return false;
646    }
647    let mut changed = false;
648    let relative = sub(b.desc.velocity, a.desc.velocity);
649    let speed = dot(relative, m.normal);
650    if speed < 0. {
651        changed = true;
652        let restitution = if speed < -1. {
653            a.desc.restitution.max(b.desc.restitution)
654        } else {
655            0.
656        };
657        let impulse = -(1. + restitution) * speed / inverse_mass;
658        a.desc.velocity = sub(a.desc.velocity, mul(m.normal, impulse * ma));
659        b.desc.velocity = add(b.desc.velocity, mul(m.normal, impulse * mb));
660        let tangent = sub(relative, mul(m.normal, speed));
661        let t_sq = dot(tangent, tangent);
662        if t_sq > 1e-16 {
663            let tangent_speed = t_sq.sqrt();
664            let friction = (a.desc.friction * b.desc.friction).sqrt();
665            let friction_impulse = (tangent_speed / inverse_mass).min(friction * impulse);
666            let friction_vector = mul(tangent, friction_impulse / tangent_speed);
667            a.desc.velocity = add(a.desc.velocity, mul(friction_vector, ma));
668            b.desc.velocity = sub(b.desc.velocity, mul(friction_vector, mb));
669        }
670    }
671    if m.penetration > slop {
672        changed = true;
673        let correction = (m.penetration - slop) * 0.75 / inverse_mass;
674        a.desc.position = sub(a.desc.position, mul(m.normal, correction * ma));
675        b.desc.position = add(b.desc.position, mul(m.normal, correction * mb));
676    }
677    changed
678}