pub(crate) mod broadphase;
mod group;
pub(crate) mod ignored;
pub(crate) mod island;
pub(crate) mod joint;
pub mod manifold;
pub mod shape;
pub(crate) mod solver;
pub(crate) mod sweep;
use std::hash::Hasher;
use crcbl_core::Pool;
use crcbl_ecs::Entity;
use glam::DVec3;
use self::broadphase::{Broadphase, PlaneBounds, ProxyId, ProxyKind};
use self::island::{IslandId, Islands};
use self::manifold::{MAX_POINTS, Manifold, SatCache};
use self::shape::ContactShape;
use crate::collider::Aabb;
use crate::material::SurfaceMaterial;
use crate::system::{AwakeSet, BodyId, BodyRecord, BodySet, StaticSet, canonical_bits};
fn filters_collide(records: &Pool<BodyRecord>, a: BodyId, b: BodyId) -> bool {
let filter = |id: BodyId| {
records
.get(id)
.map_or(crate::CollisionFilter::DEFAULT, |record| record.filter)
};
filter(a).collides_with(filter(b))
}
fn bodies_may_touch(
joints: &joint::Joints,
ignored: &ignored::IgnoredPairs,
records: &Pool<BodyRecord>,
a: BodyId,
b: BodyId,
) -> bool {
a != b && !joints.keeps_apart(a, b) && !ignored.contains(a, b) && filters_collide(records, a, b)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContactSettings {
pub substeps: u32,
pub contact_hertz: f64,
pub damping_ratio: f64,
pub push_out_speed: f64,
pub speculative_distance: f64,
pub restitution_threshold: f64,
pub max_linear_speed: f64,
pub max_rotation: f64,
pub warm_starting: bool,
pub kinetic_impulse: f64,
pub sleep: bool,
pub sleep_speed: f64,
pub sleep_angular_speed: f64,
pub time_to_sleep: f64,
pub continuous: bool,
}
impl ContactSettings {
pub const DEFAULT: Self = Self {
substeps: 4,
contact_hertz: 30.0,
damping_ratio: 10.0,
push_out_speed: 3.0,
speculative_distance: 4.0 * 0.005,
restitution_threshold: 1.0,
max_linear_speed: 400.0,
max_rotation: 0.25 * core::f64::consts::PI,
warm_starting: true,
kinetic_impulse: 1.0,
sleep: true,
sleep_speed: 0.05,
sleep_angular_speed: 0.1,
time_to_sleep: 0.5,
continuous: true,
};
}
impl Default for ContactSettings {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct StageTimes {
pub broadphase: f64,
pub narrow_phase: f64,
pub solver: f64,
pub islands: f64,
pub continuous: f64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ContactCounters {
pub bodies: usize,
pub sleeping: usize,
pub islands: usize,
pub sleeping_islands: usize,
pub pairs: usize,
pub touching: usize,
pub points: usize,
pub persisted: usize,
pub begun: u64,
pub ended: u64,
pub worst_penetration: f64,
pub bounces: u64,
pub bounce_ratio_sum: f64,
pub restitution_sum: f64,
pub swept: usize,
pub sweep_candidates: usize,
pub sweep_hits: usize,
pub dropped_time: f64,
pub joints: usize,
pub joint_error: f64,
pub joint_angle_error: f64,
pub broken_joints: usize,
pub stages: Option<StageTimes>,
}
impl ContactCounters {
#[must_use]
pub fn bounce_ratio(&self) -> Option<f64> {
(self.bounces > 0).then(|| self.bounce_ratio_sum / self.bounces as f64)
}
#[must_use]
pub fn points_per_manifold(&self) -> Option<f64> {
(self.touching > 0).then(|| self.points as f64 / self.touching as f64)
}
#[must_use]
pub fn persisted_ratio(&self) -> Option<f64> {
(self.points > 0).then(|| self.persisted as f64 / self.points as f64)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum KineticSource {
Contact,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct KineticContact {
pub source: KineticSource,
pub impactor: Option<Entity>,
pub struck: Entity,
pub point: DVec3,
pub normal: DVec3,
pub relative_velocity: DVec3,
pub impactor_mass: f64,
pub energy_deposited: f64,
pub impulse: f64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PlaneId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContactBody {
Entity(Entity),
Plane(PlaneId),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ContactReport {
pub slot: u32,
pub a: ContactBody,
pub b: ContactBody,
pub part_a: usize,
pub part_b: usize,
pub manifold: Manifold,
pub normal_impulses: [f64; MAX_POINTS],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Owner {
Body(BodyId, usize),
Plane(u32),
}
#[derive(Clone, Copy, Debug)]
struct PlaneRecord {
bounds: PlaneBounds,
material: SurfaceMaterial,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct WarmImpulses {
normal: [f64; MAX_POINTS],
friction: DVec3,
twist: f64,
}
#[derive(Clone, Copy, Debug)]
struct Contact {
a: ProxyId,
b: ProxyId,
manifold: Manifold,
impulses: WarmImpulses,
touching: bool,
cache: SatCache,
}
#[derive(Clone, Copy, Debug)]
struct Side {
shape: ContactShape,
awake: Option<usize>,
entity: Option<Entity>,
material: SurfaceMaterial,
position: DVec3,
velocity: DVec3,
angular_velocity: DVec3,
inverse_mass: f64,
mass: f64,
}
#[derive(Clone, Copy)]
pub(crate) struct Bodies<'a> {
pub(crate) records: &'a Pool<BodyRecord>,
pub(crate) statics: &'a StaticSet,
pub(crate) awake: &'a AwakeSet,
pub(crate) islands: &'a Islands,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Presence {
Dynamic(BodyId),
Moving,
Still,
Asleep(BodyId),
}
impl Presence {
const fn moves(self) -> bool {
matches!(self, Self::Dynamic(_) | Self::Moving)
}
const fn island_body(self) -> Option<BodyId> {
match self {
Self::Dynamic(id) | Self::Asleep(id) => Some(id),
Self::Moving | Self::Still => None,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct IslandEvents {
pub(crate) wake: Vec<BodyId>,
pub(crate) links: Vec<(BodyId, BodyId)>,
pub(crate) unlinks: Vec<BodyId>,
pub(crate) stirred: Vec<BodyId>,
}
impl IslandEvents {
fn clear(&mut self) {
self.wake.clear();
self.links.clear();
self.unlinks.clear();
self.stirred.clear();
}
}
#[derive(Debug)]
pub(crate) struct ContactPipeline {
pub(crate) settings: ContactSettings,
broadphase: Broadphase,
owners: Vec<Option<Owner>>,
planes: Vec<PlaneRecord>,
contacts: Vec<Option<Contact>>,
free_contacts: Vec<u32>,
new_pairs: Vec<(ProxyId, ProxyId)>,
restored: Vec<BodyId>,
ended_between_steps: u64,
pub(crate) counters: ContactCounters,
pub(crate) kinetic: Vec<KineticContact>,
pub(crate) events: IslandEvents,
edges: Vec<(BodyId, BodyId)>,
solver: solver::Scratch,
continuous: sweep::Scratch,
pub(crate) joints: joint::Joints,
pub(crate) ignored: ignored::IgnoredPairs,
}
impl ContactPipeline {
pub(crate) fn new(settings: ContactSettings) -> Self {
Self {
settings,
broadphase: Broadphase::new(),
owners: Vec::new(),
planes: Vec::new(),
contacts: Vec::new(),
free_contacts: Vec::new(),
new_pairs: Vec::new(),
restored: Vec::new(),
ended_between_steps: 0,
counters: ContactCounters::default(),
kinetic: Vec::new(),
events: IslandEvents::default(),
edges: Vec::new(),
solver: solver::Scratch::default(),
continuous: sweep::Scratch::default(),
joints: joint::Joints::default(),
ignored: ignored::IgnoredPairs::default(),
}
}
pub(crate) fn create_body_proxies(&mut self, id: BodyId, bodies: Bodies<'_>) -> Vec<ProxyId> {
let Some(record) = bodies.records.get(id) else {
return Vec::new();
};
let Some((_, component)) = record.collider.as_ref() else {
return Vec::new();
};
let transform = transform_of(record, bodies);
let kind = proxy_kind(record.set);
let mut proxies = Vec::new();
for part in 0..component.part_count() {
let Some(shape) = ContactShape::placed_part(component, part, transform) else {
continue;
};
let proxy = self
.broadphase
.create(kind, shape.aabb().expect("a body's shape is bounded"));
self.set_owner(proxy, Owner::Body(id, part));
proxies.push(proxy);
}
proxies
}
pub(crate) fn add_plane(
&mut self,
normal: DVec3,
offset: f64,
material: SurfaceMaterial,
) -> PlaneId {
let index = self.planes.len() as u32;
let bounds = PlaneBounds { normal, offset };
self.planes.push(PlaneRecord { bounds, material });
let proxy = self.broadphase.create_plane(index, bounds);
self.set_owner(proxy, Owner::Plane(index));
PlaneId(index)
}
pub(crate) fn destroy_proxies(&mut self, proxies: &[ProxyId]) {
let mut rank: Vec<(ProxyId, usize)> = proxies
.iter()
.enumerate()
.map(|(place, &proxy)| (proxy, place))
.collect();
rank.sort_unstable();
let place = |proxy: ProxyId| {
rank.binary_search_by_key(&proxy, |&(p, _)| p)
.ok()
.map(|k| rank[k].1)
};
let mut doomed: Vec<(usize, usize)> = self
.contacts
.iter()
.enumerate()
.filter_map(|(slot, contact)| {
let contact = contact.as_ref()?;
place(contact.a)
.or_else(|| place(contact.b))
.map(|place| (place, slot))
})
.collect();
doomed.sort_unstable();
for (_, slot) in doomed {
if self.destroy_contact(slot) {
self.ended_between_steps += 1;
}
}
for &proxy in proxies {
self.broadphase.destroy(proxy);
if let Some(owner) = self.owners.get_mut(proxy as usize) {
*owner = None;
}
}
}
pub(crate) fn body_changed_set(&mut self, proxy: ProxyId, set: BodySet) {
self.broadphase.set_kind(proxy, proxy_kind(set));
}
pub(crate) fn body_placed(&mut self, id: BodyId, bodies: Bodies<'_>) {
let Some(record) = bodies.records.get(id) else {
return;
};
let Some((_, component)) = record.collider.as_ref() else {
return;
};
let transform = transform_of(record, bodies);
for (part, &proxy) in record.proxies.iter().enumerate() {
if let Some(bounds) =
ContactShape::placed_part(component, part, transform).and_then(|shape| shape.aabb())
{
self.broadphase.update(proxy, bounds);
}
}
}
fn set_owner(&mut self, proxy: ProxyId, owner: Owner) {
let index = proxy as usize;
if index >= self.owners.len() {
self.owners.resize(index + 1, None);
}
self.owners[index] = Some(owner);
}
pub(crate) fn update_pairs(&mut self, bodies: Bodies<'_>, dt: f64) {
self.events.clear();
let awake = bodies.awake;
for index in 0..awake.ids.len() {
let Some(record) = bodies.records.get(awake.ids[index]) else {
continue;
};
let Some((_, component)) = record.collider.as_ref() else {
continue;
};
let transform = &awake.transforms[index];
let body = &awake.bodies[index];
for (part, &proxy) in record.proxies.iter().enumerate() {
let Some(shape) = ContactShape::placed_part(component, part, transform) else {
continue;
};
let Some(tight) = shape.aabb() else {
continue;
};
let travel = body.velocity * dt;
let swept = tight.union(Aabb::new(tight.min + travel, tight.max + travel));
let turn =
body.angular_velocity.length() * dt * shape.reach_from(transform.position);
self.broadphase.update(
proxy,
swept.inflated(self.settings.speculative_distance + turn),
);
}
}
let Self {
broadphase,
owners,
planes,
new_pairs,
joints,
ignored,
..
} = self;
new_pairs.clear();
broadphase.find_new_pairs(
|a, b| {
let body = |proxy: ProxyId| match owners.get(proxy as usize) {
Some(Some(Owner::Body(id, _))) => Some(*id),
_ => None,
};
if let (Some(ba), Some(bb)) = (body(a), body(b))
&& !bodies_may_touch(joints, ignored, bodies.records, ba, bb)
{
return false;
}
let dynamic = |proxy: ProxyId| {
owner_side(owners, planes, proxy, bodies).is_some_and(|s| s.inverse_mass > 0.0)
};
dynamic(a) || dynamic(b)
},
new_pairs,
);
for pair in 0..self.new_pairs.len() {
let (p, q) = self.new_pairs[pair];
let (Some(sp), Some(sq)) = (self.side(p, bodies), self.side(q, bodies)) else {
self.broadphase.remove_pair(p, q);
continue;
};
match (self.presence(p, bodies), self.presence(q, bodies)) {
(Some(Presence::Asleep(id)), Some(Presence::Still))
| (Some(Presence::Still), Some(Presence::Asleep(id)))
if !self.restored.contains(&id) =>
{
self.events.wake.push(id);
}
_ => {}
}
let (a, b) = if sq.shape.rank() < sp.shape.rank() {
(q, p)
} else {
(p, q)
};
let contact = Contact {
a,
b,
manifold: Manifold::EMPTY,
impulses: WarmImpulses::default(),
touching: false,
cache: SatCache::default(),
};
match self.free_contacts.pop() {
Some(slot) => self.contacts[slot as usize] = Some(contact),
None => self.contacts.push(Some(contact)),
}
}
self.restored.clear();
}
pub(crate) fn body_restored_asleep(&mut self, id: BodyId) {
self.restored.push(id);
}
pub(crate) fn collide(&mut self, bodies: Bodies<'_>, dt: f64) {
let counters = &mut self.counters;
counters.touching = 0;
counters.points = 0;
counters.persisted = 0;
counters.begun = 0;
counters.ended = std::mem::take(&mut self.ended_between_steps);
counters.worst_penetration = 0.0;
for slot in 0..self.contacts.len() {
let Some(mut contact) = self.contacts[slot] else {
continue;
};
let (pa, pb) = (
self.presence(contact.a, bodies),
self.presence(contact.b, bodies),
);
if let (Some(pa), Some(pb)) = (pa, pb)
&& !pa.moves()
&& !pb.moves()
&& (matches!(pa, Presence::Asleep(_)) || matches!(pb, Presence::Asleep(_)))
{
continue;
}
let sides = (self.side(contact.a, bodies), self.side(contact.b, bodies));
let (Some(a), Some(b), Some(pa), Some(pb)) = (sides.0, sides.1, pa, pb) else {
self.counters.ended += u64::from(self.destroy_contact(slot));
continue;
};
let island_pair = pa.island_body().zip(pb.island_body());
if !self.broadphase.overlaps(contact.a, contact.b) {
let was_touching = self.destroy_contact(slot);
self.counters.ended += u64::from(was_touching);
if was_touching && let Some((a, _)) = island_pair {
self.events.unlinks.push(a);
}
continue;
}
let manifold = if a.inverse_mass > 0.0 || b.inverse_mass > 0.0 {
let reach = |side: &Side| {
side.velocity.length()
+ side.angular_velocity.length() * side.shape.reach_from(side.position)
};
let speculative = self.settings.speculative_distance + dt * (reach(&a) + reach(&b));
manifold::collide_cached(&a.shape, &b.shape, speculative, &mut contact.cache)
} else {
Manifold::EMPTY
};
let mut impulses = WarmImpulses::default();
let mut manifold = manifold;
let mut persisted = false;
for (k, point) in manifold.points_mut().iter_mut().enumerate() {
if let Some(old) = contact
.manifold
.points()
.iter()
.position(|p| p.id == point.id)
{
impulses.normal[k] = contact.impulses.normal[old];
persisted = true;
self.counters.persisted += 1;
}
self.counters.worst_penetration =
self.counters.worst_penetration.max(-point.separation);
}
if persisted {
impulses.friction = contact.impulses.friction;
impulses.twist = contact.impulses.twist;
}
let touching = !manifold.points().is_empty();
if touching && !contact.touching {
self.counters.begun += 1;
if let Some(pair) = island_pair {
self.events.links.push(pair);
}
} else if !touching && contact.touching {
self.counters.ended += 1;
if let Some((a, _)) = island_pair {
self.events.unlinks.push(a);
}
}
if touching {
self.counters.touching += 1;
self.counters.points += manifold.points().len();
for (this, other) in [(pa, pb), (pb, pa)] {
match (this, other) {
(Presence::Asleep(id), Presence::Dynamic(other)) => {
self.events.wake.push(id);
self.events.links.push((id, other));
}
(Presence::Asleep(id), other) if other.moves() => {
self.events.wake.push(id);
}
(Presence::Dynamic(id), Presence::Moving) => {
self.events.stirred.push(id);
}
_ => {}
}
}
}
self.contacts[slot] = Some(Contact {
manifold,
impulses,
touching,
..contact
});
}
self.counters.pairs = self.broadphase.pair_count();
}
pub(crate) fn touching_bodies(&self, proxies: &[ProxyId], out: &mut Vec<BodyId>) {
let mut sorted = proxies.to_vec();
sorted.sort_unstable();
let owns = |proxy: &ProxyId| sorted.binary_search(proxy).is_ok();
for contact in self.contacts.iter().flatten() {
if !contact.touching {
continue;
}
let other = if owns(&contact.a) {
contact.b
} else if owns(&contact.b) {
contact.a
} else {
continue;
};
if let Some(Some(Owner::Body(id, _))) = self.owners.get(other as usize) {
out.push(*id);
}
}
}
pub(crate) fn island_edges(
&mut self,
records: &Pool<BodyRecord>,
island: IslandId,
) -> &[(BodyId, BodyId)] {
self.edges.clear();
let in_island = |proxy: ProxyId| match self.owners.get(proxy as usize) {
Some(Some(Owner::Body(id, _)))
if records.get(*id).and_then(|record| record.island) == Some(island) =>
{
Some(*id)
}
_ => None,
};
for contact in self.contacts.iter().flatten() {
if contact.touching
&& let (Some(a), Some(b)) = (in_island(contact.a), in_island(contact.b))
{
self.edges.push((a, b));
}
}
self.joints.island_edges(records, island, &mut self.edges);
&self.edges
}
pub(crate) fn destroy_contacts_between(&mut self, a: BodyId, b: BodyId) {
let body = |owners: &[Option<Owner>], proxy: ProxyId| match owners.get(proxy as usize) {
Some(Some(Owner::Body(id, _))) => Some(*id),
_ => None,
};
for slot in 0..self.contacts.len() {
let Some(contact) = self.contacts[slot] else {
continue;
};
let (p, q) = (body(&self.owners, contact.a), body(&self.owners, contact.b));
if (p == Some(a) && q == Some(b)) || (p == Some(b) && q == Some(a)) {
self.ended_between_steps += u64::from(self.destroy_contact(slot));
}
}
}
pub(crate) fn destroy_filtered_contacts_of(&mut self, id: BodyId, records: &Pool<BodyRecord>) {
let body = |owners: &[Option<Owner>], proxy: ProxyId| match owners.get(proxy as usize) {
Some(Some(Owner::Body(id, _))) => Some(*id),
_ => None,
};
for slot in 0..self.contacts.len() {
let Some(contact) = self.contacts[slot] else {
continue;
};
let (p, q) = (body(&self.owners, contact.a), body(&self.owners, contact.b));
let other = match (p, q) {
(Some(p), Some(q)) if p == id => q,
(Some(p), Some(q)) if q == id => p,
_ => continue,
};
if !filters_collide(records, id, other) {
self.ended_between_steps += u64::from(self.destroy_contact(slot));
}
}
}
pub(crate) fn rediscover(&mut self, proxies: &[ProxyId]) {
for &proxy in proxies {
self.broadphase.touch(proxy);
}
}
pub(crate) fn count_joints(&mut self, bodies: Bodies<'_>) {
let counters = &mut self.counters;
counters.joints = self.joints.prepared.len();
counters.joint_error = 0.0;
counters.joint_angle_error = 0.0;
for (_, record) in self.joints.iter() {
let (Some(a), Some(b)) = (bodies.records.get(record.a), bodies.records.get(record.b))
else {
continue;
};
if a.set != BodySet::Awake && b.set != BodySet::Awake {
continue;
}
let drift = joint::drift(
&record.joint,
transform_of(a, bodies),
transform_of(b, bodies),
);
counters.joint_error = counters.joint_error.max(drift.linear);
counters.joint_angle_error = counters.joint_angle_error.max(drift.angular);
}
}
pub(crate) fn reports(&self, records: &Pool<BodyRecord>) -> Vec<ContactReport> {
self.contacts
.iter()
.enumerate()
.filter_map(|(slot, contact)| {
let contact = contact.as_ref()?;
Some(ContactReport {
slot: slot as u32,
a: self.contact_body(contact.a, records)?,
b: self.contact_body(contact.b, records)?,
part_a: self.part(contact.a),
part_b: self.part(contact.b),
manifold: contact.manifold,
normal_impulses: contact.impulses.normal,
})
})
.collect()
}
pub(crate) fn hash_state(&self, records: &Pool<BodyRecord>, hasher: &mut dyn Hasher) {
let write = |hasher: &mut dyn Hasher, value: f64| {
hasher.write(&canonical_bits(value).to_le_bytes());
};
for plane in &self.planes {
for value in plane.bounds.normal.to_array() {
write(hasher, value);
}
write(hasher, plane.bounds.offset);
}
type Key = (u8, u64, u64);
let key = |proxy: ProxyId| -> Key {
match self.contact_body(proxy, records) {
Some(ContactBody::Entity(entity)) => match self.part(proxy) {
0 => (0, entity.to_bits(), 0),
part => (3, entity.to_bits(), part as u64),
},
Some(ContactBody::Plane(PlaneId(index))) => (1, u64::from(index), 0),
None => (2, 0, 0),
}
};
let mut live: Vec<(Key, Key, &Contact)> = self
.contacts
.iter()
.flatten()
.map(|contact| (key(contact.a), key(contact.b), contact))
.collect();
live.sort_unstable_by_key(|(a, b, _)| (*a, *b));
for (a, b, contact) in live {
hasher.write(&[a.0, b.0]);
hasher.write(&a.1.to_le_bytes());
hasher.write(&b.1.to_le_bytes());
for side in [a, b] {
if side.0 == 3 {
hasher.write(&side.2.to_le_bytes());
}
}
let points = contact.manifold.points();
hasher.write(&(points.len() as u32).to_le_bytes());
for value in contact.manifold.normal.to_array() {
write(hasher, value);
}
for (point, &impulse) in points.iter().zip(&contact.impulses.normal) {
hasher.write(&point.id.to_le_bytes());
for value in point.point.to_array() {
write(hasher, value);
}
write(hasher, point.separation);
write(hasher, impulse);
}
for value in contact.impulses.friction.to_array() {
write(hasher, value);
}
write(hasher, contact.impulses.twist);
}
self.joints.hash_state(records, hasher);
self.ignored.hash_state(records, hasher);
}
fn contact_body(&self, proxy: ProxyId, records: &Pool<BodyRecord>) -> Option<ContactBody> {
match (*self.owners.get(proxy as usize)?)? {
Owner::Body(id, _) => Some(ContactBody::Entity(records.get(id)?.entity)),
Owner::Plane(index) => Some(ContactBody::Plane(PlaneId(index))),
}
}
fn part(&self, proxy: ProxyId) -> usize {
match self.owners.get(proxy as usize) {
Some(Some(Owner::Body(_, part))) => *part,
_ => 0,
}
}
fn destroy_contact(&mut self, slot: usize) -> bool {
let Some(contact) = self.contacts[slot].take() else {
return false;
};
self.broadphase.remove_pair(contact.a, contact.b);
self.free_contacts.push(slot as u32);
contact.touching
}
fn side(&self, proxy: ProxyId, bodies: Bodies<'_>) -> Option<Side> {
owner_side(&self.owners, &self.planes, proxy, bodies)
}
fn presence(&self, proxy: ProxyId, bodies: Bodies<'_>) -> Option<Presence> {
match (*self.owners.get(proxy as usize)?)? {
Owner::Plane(_) => Some(Presence::Still),
Owner::Body(id, _) => body_presence(bodies, id),
}
}
fn solvable(&self, a: ProxyId, b: ProxyId, bodies: Bodies<'_>) -> bool {
let dynamic = |proxy| matches!(self.presence(proxy, bodies), Some(Presence::Dynamic(_)));
dynamic(a) || dynamic(b)
}
}
const fn proxy_kind(set: BodySet) -> ProxyKind {
match set {
BodySet::Static => ProxyKind::Static,
BodySet::Awake | BodySet::Sleeping => ProxyKind::Moving,
}
}
fn body_presence(bodies: Bodies<'_>, id: BodyId) -> Option<Presence> {
let record = bodies.records.get(id)?;
Some(match record.set {
BodySet::Static => Presence::Still,
BodySet::Sleeping => Presence::Asleep(id),
BodySet::Awake => {
let body = &bodies.awake.bodies[record.index];
if body.is_dynamic() {
Presence::Dynamic(id)
} else if body.velocity != DVec3::ZERO || body.angular_velocity != DVec3::ZERO {
Presence::Moving
} else {
Presence::Still
}
}
})
}
fn owner_side(
owners: &[Option<Owner>],
planes: &[PlaneRecord],
proxy: ProxyId,
bodies: Bodies<'_>,
) -> Option<Side> {
match (*owners.get(proxy as usize)?)? {
Owner::Plane(index) => {
let plane = planes.get(index as usize)?;
Some(Side {
shape: ContactShape::Plane {
normal: plane.bounds.normal,
offset: plane.bounds.offset,
},
awake: None,
entity: None,
material: plane.material,
position: DVec3::ZERO,
velocity: DVec3::ZERO,
angular_velocity: DVec3::ZERO,
inverse_mass: 0.0,
mass: f64::INFINITY,
})
}
Owner::Body(id, part) => {
let record = bodies.records.get(id)?;
let (_, component) = record.collider.as_ref()?;
let transform = transform_of(record, bodies);
let shape = ContactShape::placed_part(component, part, transform)?;
let (awake, velocity, angular_velocity, inverse_mass, mass) = match record.set {
BodySet::Static => (None, DVec3::ZERO, DVec3::ZERO, 0.0, f64::INFINITY),
BodySet::Sleeping => {
let body = bodies.islands.body(record.island, record.index);
(None, DVec3::ZERO, DVec3::ZERO, body.inverse_mass, body.mass)
}
BodySet::Awake => {
let body = &bodies.awake.bodies[record.index];
(
Some(record.index),
body.velocity,
body.angular_velocity,
body.inverse_mass,
body.mass,
)
}
};
Some(Side {
shape,
awake,
entity: Some(record.entity),
material: record.material,
position: transform.position,
velocity,
angular_velocity,
inverse_mass,
mass,
})
}
}
}
fn transform_of<'a>(record: &BodyRecord, bodies: Bodies<'a>) -> &'a crate::components::Transform {
match record.set {
BodySet::Static => &bodies.statics.transforms[record.index],
BodySet::Awake => &bodies.awake.transforms[record.index],
BodySet::Sleeping => bodies.islands.transform(record.island, record.index),
}
}