1use super::*;
2pub(super) const MAX_POINTS: usize = 8;
3pub(super) struct ImpactMotion {
4 body: RigidBodyHandle,
5 center: Vec3,
6 velocity: Vec3,
7 angular: Vec3,
8}
9
10fn push_manifold(buffer: &mut Vec<Manifold>, manifold: Manifold, limit: usize) {
11 if buffer.len() == buffer.capacity() {
12 let next = (buffer.capacity().max(1) * 2).min(limit);
13 buffer.reserve_exact(next - buffer.len());
14 }
15 buffer.push(manifold);
16}
17#[derive(Clone, Copy, Debug, PartialEq)]
19pub struct SolverSettings {
20 pub velocity_iterations: usize,
21 pub position_iterations: usize,
22 pub warm_start: bool,
23 pub allow_sleep: bool,
24 pub sleep_delay: f32,
25 pub linear_sleep_threshold: f32,
26 pub angular_sleep_threshold: f32,
27 pub contact_match_distance: f32,
28 pub contact_break_distance: f32,
29 pub max_cached_manifolds: usize,
31}
32impl Default for SolverSettings {
33 fn default() -> Self {
34 Self {
35 velocity_iterations: 12,
36 position_iterations: 8,
37 warm_start: true,
38 allow_sleep: true,
39 sleep_delay: 0.8,
40 linear_sleep_threshold: 0.04,
41 angular_sleep_threshold: 0.05,
42 contact_match_distance: 0.05,
43 contact_break_distance: 0.02,
44 max_cached_manifolds: 2048,
45 }
46 }
47}
48impl SolverSettings {
49 fn valid(self) -> bool {
50 (1..=64).contains(&self.velocity_iterations)
51 && self.position_iterations <= 32
52 && self.sleep_delay.is_finite()
53 && (0.05..=10.).contains(&self.sleep_delay)
54 && self.linear_sleep_threshold.is_finite()
55 && (0.001..=1.).contains(&self.linear_sleep_threshold)
56 && self.angular_sleep_threshold.is_finite()
57 && (0.001..=1.).contains(&self.angular_sleep_threshold)
58 && self.contact_match_distance.is_finite()
59 && (0.001..=0.2).contains(&self.contact_match_distance)
60 && self.contact_break_distance.is_finite()
61 && (0.001..=0.1).contains(&self.contact_break_distance)
62 && self.max_cached_manifolds <= 65536
63 }
64}
65#[derive(Clone, Copy, Debug, Default)]
68pub struct ContactPoint {
69 pub id: u64,
70 pub local_anchor1: Vec3,
71 pub local_anchor2: Vec3,
72 pub normal: Vec3,
73 pub normal_impulse: f32,
74 pub tangent_impulse: Vec3,
75}
76#[derive(Clone, Copy)]
77pub(super) struct Manifold {
78 pub key: (ColliderHandle, ColliderHandle),
79 pub revisions: [u64; 4],
80 pub dt: f32,
81 pub points: [ContactPoint; MAX_POINTS],
82 pub len: usize,
83}
84#[derive(Clone, Copy, Debug)]
85pub struct ContactManifold<'a> {
86 pub collider1: ColliderHandle,
87 pub collider2: ColliderHandle,
88 pub points: &'a [ContactPoint],
89}
90impl<B: Access> World<B> {
91 pub fn impact_settings(&self) -> Option<ImpactSettings> {
94 self.impact_settings
95 }
96 pub fn set_impact_settings(
158 &mut self,
159 settings: Option<ImpactSettings>,
160 ) -> Result<(), ImpactRecordingError> {
161 if let Some(settings) = settings {
162 if settings.capacity > MAX_IMPACT_RECORDS
163 || !settings.min_normal_impulse.is_finite()
164 || settings.min_normal_impulse < 0.
165 || !settings.min_approach_speed.is_finite()
166 || settings.min_approach_speed <= 0.
167 {
168 return Err(ImpactRecordingError::InvalidSettings);
169 }
170 self.impacts
171 .try_reserve_exact(settings.capacity.saturating_sub(self.impacts.len()))
172 .map_err(|_| ImpactRecordingError::AllocationFailed)?;
173 self.impact_motions
174 .try_reserve_exact(4096_usize.saturating_sub(self.impact_motions.len()))
175 .map_err(|_| ImpactRecordingError::AllocationFailed)?;
176 }
177 if self.impact_settings != settings {
178 self.impact_settings = settings;
179 self.clear_impacts();
180 self.impact_motions.clear();
181 }
182 Ok(())
183 }
184 pub fn impacts(&self) -> &[ImpactRecord] {
192 &self.impacts
193 }
194 pub fn impact_dropped(&self) -> usize {
201 self.impact_dropped
202 }
203 pub fn clear_impacts(&mut self) {
207 self.impacts.clear();
208 self.impact_dropped = 0;
209 }
210 pub(super) fn capture_impact_motion(&mut self) {
211 self.impact_motions.clear();
212 if self.impact_settings.is_some() {
213 self.impact_motions
214 .extend(self.bodies.iter().map(|(body, b)| {
215 let b = b.core();
216 ImpactMotion {
217 body,
218 center: b.world_com(),
219 velocity: b.velocity,
220 angular: b.angular_velocity,
221 }
222 }));
223 }
224 }
225 fn impact_approach(
226 &self,
227 a: RigidBodyHandle,
228 b: RigidBodyHandle,
229 point: Vec3,
230 normal: Vec3,
231 ) -> f32 {
232 let velocity = |body| {
233 let i = self
236 .impact_motions
237 .binary_search_by_key(&body, |m| m.body)
238 .expect("captured live body motion");
239 let m = &self.impact_motions[i];
240 m.velocity + m.angular.cross(point - m.center)
241 };
242 -(velocity(b) - velocity(a)).dot(normal)
243 }
244 pub(super) fn record_impacts(&mut self) {
245 let Some(settings) = self.impact_settings else {
246 return;
247 };
248 let mut first = 0;
249 while first < self.constraints.len() {
250 let key = self.constraints[first].key;
251 let mut end = first + 1;
252 let mut strongest = first;
253 while end < self.constraints.len() && self.constraints[end].key == key {
254 if self.constraints[end].impact_peak > self.constraints[strongest].impact_peak {
255 strongest = end;
256 }
257 end += 1;
258 }
259 let c = &self.constraints[strongest];
260 if c.impact_peak.is_finite() && c.impact_peak > settings.min_normal_impulse {
261 let record = ImpactRecord {
262 collider1: key.0,
263 collider2: key.1,
264 point: c.point,
265 normal: c.normal,
266 peak_normal_impulse: c.impact_peak,
267 approach_speed: c.impact_approach,
268 };
269 match self
270 .impacts
271 .binary_search_by_key(&key, |r| (r.collider1, r.collider2))
272 {
273 Ok(i) => {
274 if record.peak_normal_impulse > self.impacts[i].peak_normal_impulse {
275 self.impacts[i] = record;
276 }
277 }
278 Err(i) if self.impacts.len() < settings.capacity => {
279 self.impacts.insert(i, record)
280 }
281 Err(_) => self.impact_dropped = self.impact_dropped.saturating_add(1),
282 }
283 }
284 first = end;
285 }
286 }
287 pub fn solver_settings(&self) -> SolverSettings {
288 self.settings
289 }
290 pub fn set_solver_settings(&mut self, settings: SolverSettings) -> Result<(), &'static str> {
292 if !settings.valid() {
293 return Err("invalid rigid solver settings");
294 }
295 if self.settings == settings {
296 return Ok(());
297 }
298 self.settings = settings;
299 self.sleep_cache = None;
300 for (_, j) in self.joints.iter_mut() {
301 j.cache.fill(crate::joints::CachedRow::default());
302 j.dt = 0.;
303 }
304 self.manifolds.clear();
305 self.next_manifolds.clear();
306 self.manifolds.shrink_to(settings.max_cached_manifolds);
307 self.next_manifolds.shrink_to(settings.max_cached_manifolds);
308 for (_, b) in self.bodies.iter_mut() {
309 b.core_mut().wake();
310 }
311 Ok(())
312 }
313 pub fn contact_manifolds(&self) -> impl Iterator<Item = ContactManifold<'_>> {
316 self.manifolds.iter().map(|m| ContactManifold {
317 collider1: m.key.0,
318 collider2: m.key.1,
319 points: &m.points[..m.len],
320 })
321 }
322 pub(super) fn store_manifolds(&mut self, dt: f32) {
323 for c in &self.constraints {
324 if let Some((index, point)) = c.cache {
325 let p = &mut self.next_manifolds[index].points[point];
326 p.normal_impulse = c.normal_impulse;
327 p.tangent_impulse = c.tangent_impulse;
328 }
329 }
330 std::mem::swap(&mut self.manifolds, &mut self.next_manifolds);
331 self.manifolds.sort_unstable_by_key(|m| m.key);
332 self.next_manifolds.clear();
333 for m in &mut self.manifolds {
334 m.dt = dt;
335 }
336 }
337}
338pub(super) fn refreshed(
339 m: &Manifold,
340 a: &crate::body::Core,
341 b: &crate::body::Core,
342 breaking: f32,
343) -> Manifold {
344 let mut out = *m;
345 out.len = 0;
346 for point in &m.points[..m.len] {
347 let pa = a.position + a.rotation * point.local_anchor1;
348 let pb = b.position + b.rotation * point.local_anchor2;
349 let delta = pb - pa;
350 let separation = delta.dot(point.normal);
351 let drift = delta - point.normal * separation;
352 if separation <= breaking
353 && separation >= -breaking * 2.
354 && drift.length_squared() <= breaking * breaking
355 {
356 let mut p = *point;
357 if separation > geometry::MARGIN {
358 p.normal_impulse = 0.;
359 p.tangent_impulse = Vec3::ZERO;
360 }
361 out.points[out.len] = p;
362 out.len += 1;
363 }
364 }
365 out
366}
367impl<B: Access> World<B> {
368 pub(super) fn find_contacts(&mut self, dt: f32, stats: &mut StepStats) {
369 self.proxies.clear();
370 self.constraints.clear();
371 self.next_manifolds.clear();
372 let breaking = self.settings.contact_break_distance;
373 for (collider, c) in self.colliders.iter() {
374 let id = c.parent.unwrap();
375 let b = self.bodies[id].core();
376 let pose = c.pose(b);
377 let bounds = geometry::bounds(c.shape, pose.position, pose.rotation);
378 self.proxies.push(Proxy {
379 body: id,
380 collider,
381 bounds: Bounds {
382 min: bounds.min - Vec3::splat(breaking),
383 max: bounds.max + Vec3::splat(breaking),
384 },
385 membership: c.membership,
386 filter: c.filter,
387 kind: b.kind,
388 sensor: c.sensor,
389 });
390 }
391 self.proxies.sort_unstable_by(|a, b| {
392 a.bounds
393 .min
394 .x
395 .total_cmp(&b.bounds.min.x)
396 .then(a.collider.cmp(&b.collider))
397 });
398 let has_disabled = !self.disabled_joint_pairs.is_empty();
399 for i in 0..self.proxies.len() {
400 let x = self.proxies[i];
401 for j in i + 1..self.proxies.len() {
402 let y = self.proxies[j];
403 if y.bounds.min.x > x.bounds.max.x {
404 break;
405 }
406 if x.bounds.min.y > y.bounds.max.y
407 || x.bounds.max.y < y.bounds.min.y
408 || x.bounds.min.z > y.bounds.max.z
409 || x.bounds.max.z < y.bounds.min.z
410 {
411 continue;
412 }
413 if x.body == y.body || x.membership & y.filter == 0 || y.membership & x.filter == 0
414 {
415 continue;
416 }
417 let sensor = x.sensor || y.sensor;
418 if x.kind != Kind::Dynamic && y.kind != Kind::Dynamic && !sensor {
419 continue;
420 }
421 if has_disabled && self.joint_contacts_disabled(x.body, y.body) {
422 continue;
423 }
424 let (pa, pb) = if x.collider < y.collider {
426 (x, y)
427 } else {
428 (y, x)
429 };
430 let ca = &self.colliders[pa.collider];
431 let cb = &self.colliders[pb.collider];
432 let a = self.bodies[pa.body].core();
433 let b = self.bodies[pb.body].core();
434 stats.broadphase_pairs += 1;
435 let key = (pa.collider, pb.collider);
436 let revisions = [a.revision, b.revision, ca.revision, cb.revision];
437 let old = self
438 .manifolds
439 .binary_search_by_key(&key, |m| m.key)
440 .ok()
441 .map(|i| self.manifolds[i])
442 .filter(|m| m.revisions == revisions);
443 self.points.clear();
444 let immobile = |body: &crate::body::Core| {
445 body.kind == Kind::Fixed
446 || body.sleeping
447 || body.kind == Kind::Kinematic
448 && body.velocity.length_squared()
449 + body.angular_velocity.length_squared()
450 < 1e-12
451 };
452 if !sensor
453 && immobile(a)
454 && immobile(b)
455 && let Some(old) = old
456 {
457 let cached = refreshed(&old, a, b, breaking);
458 for point in &cached.points[..cached.len] {
459 let ap = a.position + a.rotation * point.local_anchor1;
460 let bp = b.position + b.rotation * point.local_anchor2;
461 let separation = (bp - ap).dot(point.normal);
462 if separation <= geometry::MARGIN {
463 self.points.push(Point {
464 point: (ap + bp) * 0.5,
465 normal: point.normal,
466 depth: (-separation).max(0.),
467 });
468 }
469 }
470 stats.reused_manifolds += 1;
471 } else {
472 geometry::contacts(
473 ca.shape,
474 &ca.pose(a),
475 cb.shape,
476 &cb.pose(b),
477 &mut self.points,
478 );
479 }
480 if self.points.is_empty() {
481 if !sensor && let Some(old) = old {
482 let mut cached = refreshed(&old, a, b, breaking);
483 for p in &mut cached.points[..cached.len] {
484 p.normal_impulse = 0.;
485 p.tangent_impulse = Vec3::ZERO;
486 }
487 if cached.len > 0 {
488 if self.next_manifolds.len() < self.settings.max_cached_manifolds {
489 push_manifold(
490 &mut self.next_manifolds,
491 cached,
492 self.settings.max_cached_manifolds,
493 );
494 } else {
495 stats.cache_dropped += 1;
496 }
497 }
498 }
499 continue;
500 }
501 self.next_contacts.push(ContactPair {
502 collider1: key.0,
503 collider2: key.1,
504 normal: self.points[0].normal.to_array(),
505 sensor,
506 });
507 if sensor {
508 continue;
509 }
510 let material = ca.material.pair(cb.material);
511 let friction = material.sliding_friction;
512 let restitution = material.restitution;
513 let cache_index = if self.next_manifolds.len() < self.settings.max_cached_manifolds
514 {
515 Some(self.next_manifolds.len())
516 } else {
517 stats.cache_dropped += 1;
518 None
519 };
520 let mut manifold = Manifold {
521 key,
522 revisions,
523 dt,
524 points: [ContactPoint::default(); MAX_POINTS],
525 len: self.points.len().min(MAX_POINTS),
526 };
527 let mut used = 0u16;
528 let tolerance = self.settings.contact_match_distance.powi(2);
529 for (index, p) in self.points.iter().enumerate() {
530 let local_a =
531 a.rotation.conjugate() * (p.point + p.normal * p.depth * 0.5 - a.position);
532 let local_b =
533 b.rotation.conjugate() * (p.point - p.normal * p.depth * 0.5 - b.position);
534 let speed =
535 (b.point_velocity(p.point) - a.point_velocity(p.point)).dot(p.normal);
536 let matched = old.and_then(|m| {
537 m.points[..m.len]
538 .iter()
539 .enumerate()
540 .filter(|(i, point)| {
541 used & (1 << i) == 0
542 && point.normal.dot(p.normal) > 0.95
543 && point.local_anchor1.distance_squared(local_a) < tolerance
544 && point.local_anchor2.distance_squared(local_b) < tolerance
545 })
546 .min_by(|(_, x), (_, y)| {
547 let distance = |p: &ContactPoint| {
548 p.local_anchor1.distance_squared(local_a)
549 + p.local_anchor2.distance_squared(local_b)
550 };
551 distance(x).total_cmp(&distance(y)).then(x.id.cmp(&y.id))
552 })
553 .map(|(i, p)| (i, *p, m.dt))
554 });
555 let mut normal_impulse = 0.;
556 let mut tangent_impulse = Vec3::ZERO;
557 let feature = if let Some((index, previous, old_dt)) = matched {
558 used |= 1 << index;
559 stats.persisted_points += 1;
560 let ratio = dt / old_dt;
561 if self.settings.warm_start
562 && (0.5..=2.).contains(&ratio)
563 && (-1. ..=0.5).contains(&speed)
564 {
565 normal_impulse = (previous.normal_impulse * ratio).max(0.);
566 tangent_impulse = (previous.tangent_impulse
567 - p.normal * previous.tangent_impulse.dot(p.normal))
568 * ratio;
569 tangent_impulse = tangent_impulse
570 .clamp_length_max(material.static_friction * normal_impulse);
571 }
572 previous.id
573 } else {
574 let id = self.next_feature;
575 self.next_feature = self
576 .next_feature
577 .checked_add(1)
578 .expect("contact identity exhausted");
579 id
580 };
581 if index < MAX_POINTS {
582 manifold.points[index] = ContactPoint {
583 id: feature,
584 local_anchor1: local_a,
585 local_anchor2: local_b,
586 normal: p.normal,
587 normal_impulse,
588 tangent_impulse,
589 };
590 }
591 self.constraints.push(Constraint {
592 a: pa.body,
593 b: pb.body,
594 normal: p.normal,
595 point: p.point,
596 local_a,
597 local_b,
598 normal_impulse,
599 normal_denominator: 0.,
600 ra: Vec3::ZERO,
601 rb: Vec3::ZERO,
602 impact_baseline: normal_impulse,
603 impact_peak: 0.,
604 impact_approach: self.impact_settings.map_or(0., |settings| {
605 let approach = self
606 .impact_approach(pa.body, pb.body, p.point, p.normal)
607 .min(-speed);
608 if approach > settings.min_approach_speed {
609 approach
610 } else {
611 0.
612 }
613 }),
614 tangent_impulse,
615 bounce: if speed < -1. {
616 -speed * restitution
617 } else {
618 0.
619 },
620 friction,
621 static_friction: material.static_friction,
622 rolling_resistance: material.rolling_resistance,
623 rolling_impulse: Vec3::ZERO,
624 key,
625 feature,
626 cache: cache_index
627 .filter(|_| index < MAX_POINTS)
628 .map(|i| (i, index)),
629 });
630 }
631 if cache_index.is_some() {
632 push_manifold(
633 &mut self.next_manifolds,
634 manifold,
635 self.settings.max_cached_manifolds,
636 );
637 }
638 }
639 }
640 self.constraints
641 .sort_unstable_by_key(|c| (c.key, c.feature));
642 stats.contact_points += self.constraints.len();
643 }
644 pub(super) fn warm_start(&mut self, stats: &mut StepStats) {
645 for c in &self.constraints {
646 let (a, b) = self.bodies.two_mut(c.a, c.b);
647 let a = a.core_mut();
648 let b = b.core_mut();
649 if a.contact_inv_mass() + b.contact_inv_mass() == 0. {
650 continue;
651 }
652 let impulse = c.normal * c.normal_impulse + c.tangent_impulse;
653 if impulse.length_squared() > 1e-16 {
654 a.impulse(-impulse, c.point);
655 b.impulse(impulse, c.point);
656 stats.warm_started_points += 1;
657 }
658 }
659 }
660}
661
662#[cfg(test)]
663mod journey400_226 {
664 use super::*;
665
666 macro_rules! solver_observation_tests {
667 ($dimension:ident) => {
668 mod $dimension {
669 use super::*;
670 use crate::$dimension::{ColliderBuilder, PhysicsWorld, RigidBodyBuilder, Vector};
671
672 #[test]
675 fn peak_subtracts_initial_warm_start_and_does_not_sum_iterations() {
676 for (incoming, expected) in [(0., 0.), (2., 0.), (3., 1.)] {
677 for iterations in [1, 12, 64] {
678 let mut world = PhysicsWorld::default();
679 world.set_impact_settings(Some(ImpactSettings {
680 min_approach_speed: 0.01,
681 ..Default::default()
682 })).unwrap();
683 world.set_solver_settings(SolverSettings {
684 velocity_iterations: iterations,
685 ..Default::default()
686 }).unwrap();
687 world.insert(RigidBodyBuilder::fixed(), ColliderBuilder::ball(0.5).friction(0.));
688 let (body, _) = world.insert(
689 RigidBodyBuilder::dynamic().translation(-Vector::X * 0.9)
690 .linvel(Vector::X * incoming),
691 ColliderBuilder::ball(0.5).friction(0.),
692 );
693 let mass = world.bodies[body].mass();
694 world.raw.capture_impact_motion();
695 world.raw.find_contacts(1. / 60., &mut StepStats::default());
696 assert_eq!(world.raw.constraints.len(), 1);
697 let c = &mut world.raw.constraints[0];
698 c.normal_impulse = mass * 2.;
699 c.impact_baseline = mass * 2.;
700 c.impact_approach = 3.;
703 world.raw.warm_start(&mut StepStats::default());
704 world.raw.solve_velocities(&mut StepStats::default());
705 world.raw.record_impacts();
706 if expected == 0. {
707 assert!(world.impacts().is_empty());
708 } else {
709 assert_eq!(world.impacts().len(), 1);
710 assert!((world.impacts()[0].peak_normal_impulse - mass * expected).abs() < 1e-5);
711 }
712 }
713 }
714 }
715
716 #[test]
717 fn stronger_later_substep_updates_at_capacity_ties_keep_first_and_drops_group_points() {
718 let mut world = PhysicsWorld::default();
719 world.set_impact_settings(Some(ImpactSettings { capacity: 1, ..Default::default() })).unwrap();
720 world.insert(RigidBodyBuilder::fixed(), ColliderBuilder::ball(0.5));
721 world.insert(RigidBodyBuilder::dynamic().translation(-Vector::X * 0.9), ColliderBuilder::ball(0.5));
722 world.raw.capture_impact_motion();
723 world.raw.find_contacts(1. / 60., &mut StepStats::default());
724 let mut later = world.raw.constraints[0].clone();
725 world.raw.constraints[0].impact_peak = 4.;
726 later.feature += 1;
727 later.point = Vec3::Y;
728 later.impact_peak = 4.;
729 world.raw.constraints.push(later);
730 world.raw.record_impacts();
731 let first = world.impacts()[0];
732 assert_eq!(first.point, world.raw.constraints[0].point);
733 world.raw.constraints[1].impact_peak = 8.;
734 world.raw.record_impacts();
735 assert_eq!(world.impacts().len(), 1);
736 assert_eq!(world.impacts()[0].point, Vec3::Y);
737 assert_eq!(world.impacts()[0].peak_normal_impulse, 8.);
738 assert_eq!(world.impact_dropped(), 0);
739 world.raw.constraints[0].impact_peak = 8.;
740 world.raw.record_impacts();
741 assert_eq!(world.impacts()[0].point, Vec3::Y);
742 world.raw.impact_settings.as_mut().unwrap().capacity = 0;
743 world.clear_impacts();
744 world.raw.record_impacts();
745 assert_eq!(world.impact_dropped(), 1);
746 world.raw.impact_dropped = usize::MAX;
747 world.raw.record_impacts();
748 assert_eq!(world.impact_dropped(), usize::MAX);
749 }
750
751 #[test]
752 fn default_off_and_reset_retain_prepared_storage_only_when_enabled() {
753 let mut world = PhysicsWorld::default();
754 world.step(1. / 60.);
755 assert_eq!(world.raw.impacts.capacity(), 0);
756 assert_eq!(world.raw.impact_motions.capacity(), 0);
757 world.set_impact_settings(Some(ImpactSettings::default())).unwrap();
758 let capacities = (world.raw.impacts.capacity(), world.raw.impact_motions.capacity());
759 assert!(capacities.0 >= 64 && capacities.1 >= 4096);
760 world.set_impact_settings(None).unwrap();
761 world.clear_impacts();
762 world.step(1. / 60.);
763 assert_eq!((world.raw.impacts.capacity(), world.raw.impact_motions.capacity()), capacities);
764 let err = ImpactRecordingError::InvalidSettings;
765 let error: &dyn std::error::Error = &err;
766 assert!(error.to_string().contains("invalid"));
767 }
768 }
769 };
770 }
771 #[cfg(feature = "dim2")]
772 solver_observation_tests!(d2);
773 #[cfg(feature = "dim3")]
774 solver_observation_tests!(d3);
775}