use core::f64::consts::TAU;
use crcbl_core::Pool;
use glam::{DMat3, DQuat, DVec3};
use super::group::{Pass, Plan};
use super::island::Islands;
use super::joint::{self, Prepared};
use super::manifold::{LINEAR_SLOP, MAX_POINTS, orthonormal_basis};
use super::shape::ContactShape;
use super::{
Bodies, ContactPipeline, ContactSettings, KineticContact, KineticSource, WarmImpulses,
};
use crate::components::{RigidBody, Transform};
use crate::integrator::{SemiImplicitEuler, SpinStep, rotation_from_scaled_axis};
use crate::system::{AwakeSet, BodyRecord, StaticSet};
pub(super) const NONE: usize = usize::MAX;
const MIN_PATCH_RADIUS: f64 = 0.1 * LINEAR_SLOP;
fn patch_radius(a: &ContactShape, b: &ContactShape, separation: f64) -> f64 {
let curvature = |shape: &ContactShape| match *shape {
ContactShape::Sphere { radius, .. } | ContactShape::Capsule { radius, .. } => 1.0 / radius,
ContactShape::Box { .. } | ContactShape::Triangle { .. } | ContactShape::Plane { .. } => {
0.0
}
};
let total = curvature(a) + curvature(b);
if total <= 0.0 {
return MIN_PATCH_RADIUS;
}
let radius = 1.0 / total;
(radius * separation.min(0.0).abs())
.sqrt()
.clamp(MIN_PATCH_RADIUS.min(radius), radius)
}
#[derive(Debug, Default)]
pub(crate) struct Scratch {
bodies: Vec<SolverBody>,
constraints: Vec<Constraint>,
bounced: Vec<(usize, usize)>,
carried: Vec<DVec3>,
free_spin: Vec<DVec3>,
touching: Vec<bool>,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct SolverBody {
pub(super) inverse_mass: f64,
pub(super) inverse_inertia: DMat3,
start: DVec3,
pub(super) delta_position: DVec3,
delta_angle: DVec3,
start_rotation: DQuat,
pub(super) delta_rotation: DQuat,
spin: SpinStep,
}
impl SolverBody {
fn new(body: &RigidBody, transform: &Transform) -> Self {
let inverse_inertia = body.inverse_world_inertia(transform.rotation);
Self {
inverse_mass: body.inverse_mass,
inverse_inertia,
start: transform.position,
delta_position: DVec3::ZERO,
delta_angle: DVec3::ZERO,
start_rotation: transform.rotation,
delta_rotation: DQuat::IDENTITY,
spin: SpinStep::default(),
}
}
fn moved(&mut self, transform: &Transform, angular_velocity: DVec3, h: f64) {
self.delta_position = transform.position - self.start;
self.delta_angle += angular_velocity * h;
self.delta_rotation = transform.rotation * self.start_rotation.conjugate();
}
fn coast(&mut self, velocity: DVec3, angular_velocity: DVec3, t: f64) {
self.delta_position = velocity * t;
self.delta_angle = angular_velocity * t;
self.delta_rotation = rotation_from_scaled_axis(angular_velocity * t);
}
fn rewind(&mut self) {
self.delta_position = DVec3::ZERO;
self.delta_angle = DVec3::ZERO;
self.delta_rotation = DQuat::IDENTITY;
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Softness {
pub(crate) bias_rate: f64,
pub(crate) mass_scale: f64,
pub(crate) impulse_scale: f64,
}
impl Softness {
pub(crate) fn new(hertz: f64, zeta: f64, h: f64) -> Self {
if hertz == 0.0 {
return Self {
bias_rate: 0.0,
mass_scale: 1.0,
impulse_scale: 0.0,
};
}
let omega = TAU * hertz;
let a1 = 2.0 * zeta + h * omega;
let a2 = h * omega * a1;
let a3 = 1.0 / (1.0 + a2);
Self {
bias_rate: omega / a1,
mass_scale: a2 * a3,
impulse_scale: a3,
}
}
}
#[derive(Clone, Copy, Debug, Default)]
struct Point {
position: DVec3,
anchor_a: DVec3,
anchor_b: DVec3,
separation: f64,
normal_mass: f64,
normal_impulse: f64,
twist_radius: f64,
max_normal_impulse: f64,
total_normal_impulse: f64,
relative_velocity: f64,
}
#[derive(Clone, Copy, Debug)]
struct Constraint {
slot: usize,
a: usize,
b: usize,
normal: DVec3,
tangents: [DVec3; 2],
friction: f64,
restitution: f64,
softness: Softness,
stiff: bool,
count: usize,
points: [Point; MAX_POINTS],
friction_anchor_a: DVec3,
friction_anchor_b: DVec3,
tangent_mass: [f64; 2],
tangent_impulse: [f64; 2],
twist_mass: f64,
twist_impulse: f64,
entity_a: Option<crcbl_ecs::Entity>,
entity_b: Option<crcbl_ecs::Entity>,
mass_a: f64,
mass_b: f64,
velocity_a: DVec3,
velocity_b: DVec3,
point_velocity: DVec3,
}
fn velocity(bodies: &[RigidBody], index: usize) -> (DVec3, DVec3) {
if index == NONE {
(DVec3::ZERO, DVec3::ZERO)
} else {
(bodies[index].velocity, bodies[index].angular_velocity)
}
}
fn apply(
bodies: &mut [RigidBody],
solver: &[SolverBody],
index: usize,
anchor: DVec3,
impulse: DVec3,
) {
if index == NONE {
return;
}
let s = &solver[index];
let body = &mut bodies[index];
body.velocity += impulse * s.inverse_mass;
body.angular_velocity += s.inverse_inertia * anchor.cross(impulse);
}
fn apply_angular(bodies: &mut [RigidBody], solver: &[SolverBody], index: usize, impulse: DVec3) {
if index == NONE {
return;
}
bodies[index].angular_velocity += solver[index].inverse_inertia * impulse;
}
fn relative_velocity(bodies: &[RigidBody], c: &Constraint, p: &Point) -> DVec3 {
relative_velocity_at(bodies, c, p.anchor_a, p.anchor_b)
}
fn relative_velocity_at(
bodies: &[RigidBody],
c: &Constraint,
anchor_a: DVec3,
anchor_b: DVec3,
) -> DVec3 {
let (va, wa) = velocity(bodies, c.a);
let (vb, wb) = velocity(bodies, c.b);
vb + wb.cross(anchor_b) - va - wa.cross(anchor_a)
}
fn inverse_twist_mass(solver: &[SolverBody], index: usize, normal: DVec3) -> f64 {
if index == NONE {
return 0.0;
}
normal.dot(solver[index].inverse_inertia * normal)
}
fn inverse_mass_along(solver: &[SolverBody], index: usize, anchor: DVec3, direction: DVec3) -> f64 {
if index == NONE {
return 0.0;
}
let s = &solver[index];
let turned = s.inverse_inertia * anchor.cross(direction);
s.inverse_mass + direction.dot(turned.cross(anchor))
}
impl ContactPipeline {
pub(crate) fn solve(
&mut self,
records: &Pool<BodyRecord>,
statics: &StaticSet,
awake: &mut AwakeSet,
islands: &Islands,
dt: f64,
) {
let settings = self.settings;
let substeps = settings.substeps.max(1);
let h = dt / f64::from(substeps);
self.counters.bounces = 0;
self.counters.bounce_ratio_sum = 0.0;
self.counters.restitution_sum = 0.0;
self.kinetic.clear();
let mut scratch = std::mem::take(&mut self.solver);
scratch.bodies.clear();
scratch.bodies.extend(
awake
.bodies
.iter()
.zip(&awake.transforms)
.map(|(body, transform)| SolverBody::new(body, transform)),
);
let world = Bodies {
records,
statics,
awake,
islands,
};
self.prepare(world, &mut scratch, dt, h);
self.joints
.prepare(world, &scratch.bodies, h, settings.warm_starting);
let mut joints = std::mem::take(&mut self.joints.prepared);
let passes = self.plan_passes(records, awake, &mut scratch, &mut joints, dt);
let AwakeSet {
transforms, bodies, ..
} = awake;
for pass in &passes {
run_pass(
pass,
&settings,
&mut scratch,
&mut joints[pass.joints.clone()],
bodies,
transforms,
dt,
);
}
self.restitution(&mut scratch, bodies);
self.store(&scratch, bodies);
self.joints.prepared = joints;
self.joints.store(records);
for body in bodies.iter_mut() {
body.clear_forces();
}
self.solver = scratch;
}
fn plan_passes(
&self,
records: &Pool<BodyRecord>,
awake: &AwakeSet,
scratch: &mut Scratch,
joints: &mut [Prepared],
dt: f64,
) -> Vec<Pass> {
let settings = &self.settings;
let default = settings.substeps.max(1);
let everything = || Pass {
substeps: default,
bodies: (0..awake.ids.len()).collect(),
contacts: 0..scratch.constraints.len(),
joints: 0..joints.len(),
outside: Vec::new(),
};
let requested: Vec<u32> = awake
.ids
.iter()
.map(|&id| records.get(id).map_or(0, |r| r.substeps).max(default))
.collect();
if requested.iter().all(|&n| n == default) {
return vec![everything()];
}
let dynamic: Vec<bool> = awake.bodies.iter().map(RigidBody::is_dynamic).collect();
let edges = scratch
.constraints
.iter()
.map(|c| (c.a, c.b))
.chain(joints.iter().map(Prepared::sides));
let Some(plan) = Plan::new(&requested, &dynamic, default, edges) else {
return vec![everything()];
};
scratch
.constraints
.sort_by_key(|c| plan.rank(c.a, c.b, &dynamic));
joints.sort_by_key(|j| {
let (a, b) = j.sides();
plan.rank(a, b, &dynamic)
});
let contact_sides: Vec<(usize, usize)> =
scratch.constraints.iter().map(|c| (c.a, c.b)).collect();
let joint_sides: Vec<(usize, usize)> = joints.iter().map(Prepared::sides).collect();
let passes = plan.passes(&contact_sides, &joint_sides, &dynamic);
for pass in passes.iter().filter(|pass| pass.substeps != default) {
let n = f64::from(pass.substeps);
let h = dt / n;
let scale = n / f64::from(default);
let hertz = (settings.contact_hertz * scale).min(0.25 * n / dt);
let soft = Softness::new(hertz, settings.damping_ratio, h);
let stiff = Softness::new(2.0 * hertz, settings.damping_ratio, h);
for constraint in &mut scratch.constraints[pass.contacts.clone()] {
constraint.softness = if constraint.stiff { stiff } else { soft };
}
for joint in &mut joints[pass.joints.clone()] {
joint.soften(h, scale);
}
}
passes
}
fn prepare(&self, world: Bodies<'_>, scratch: &mut Scratch, dt: f64, h: f64) {
let settings = &self.settings;
let hertz = settings
.contact_hertz
.min(0.25 * f64::from(settings.substeps.max(1)) / dt);
let soft = Softness::new(hertz, settings.damping_ratio, h);
let stiff = Softness::new(2.0 * hertz, settings.damping_ratio, h);
scratch.constraints.clear();
for (slot, contact) in self.contacts.iter().enumerate() {
let Some(contact) = contact else {
continue;
};
if !contact.touching || !self.solvable(contact.a, contact.b, world) {
continue;
}
let (Some(a), Some(b)) = (self.side(contact.a, world), self.side(contact.b, world))
else {
continue;
};
let material = a.material.combine(&b.material);
let normal = contact.manifold.normal;
let tangents = {
let (t0, t1) = orthonormal_basis(normal);
[t0, t1]
};
let mut constraint = Constraint {
slot,
a: a.awake.unwrap_or(NONE),
b: b.awake.unwrap_or(NONE),
normal,
tangents,
friction: material.friction,
restitution: material.restitution,
stiff: a.inverse_mass == 0.0 || b.inverse_mass == 0.0,
softness: if a.inverse_mass == 0.0 || b.inverse_mass == 0.0 {
stiff
} else {
soft
},
count: contact.manifold.points().len(),
points: [Point::default(); MAX_POINTS],
friction_anchor_a: DVec3::ZERO,
friction_anchor_b: DVec3::ZERO,
tangent_mass: [0.0; 2],
tangent_impulse: [0.0; 2],
twist_mass: 0.0,
twist_impulse: 0.0,
entity_a: a.entity,
entity_b: b.entity,
mass_a: a.mass,
mass_b: b.mass,
velocity_a: a.velocity,
velocity_b: b.velocity,
point_velocity: DVec3::ZERO,
};
let warm = if settings.warm_starting {
contact.impulses
} else {
WarmImpulses::default()
};
let effective = |anchor_a: DVec3, anchor_b: DVec3, direction: DVec3| {
let k = inverse_mass_along(&scratch.bodies, constraint.a, anchor_a, direction)
+ inverse_mass_along(&scratch.bodies, constraint.b, anchor_b, direction);
if k > 0.0 { 1.0 / k } else { 0.0 }
};
let points = contact.manifold.points();
let centroid = points.iter().map(|p| p.point).sum::<DVec3>() / points.len() as f64;
for (k, mp) in points.iter().enumerate() {
let anchor_a = mp.point - a.position;
let anchor_b = mp.point - b.position;
let dv = b.velocity + b.angular_velocity.cross(anchor_b)
- a.velocity
- a.angular_velocity.cross(anchor_a);
if k == 0 {
constraint.point_velocity = dv;
}
constraint.points[k] = Point {
position: mp.point,
anchor_a,
anchor_b,
separation: mp.separation,
normal_mass: effective(anchor_a, anchor_b, normal),
normal_impulse: warm.normal[k],
twist_radius: if points.len() == 1 {
patch_radius(&a.shape, &b.shape, mp.separation)
} else {
(mp.point - centroid).length()
},
max_normal_impulse: 0.0,
total_normal_impulse: 0.0,
relative_velocity: dv.dot(normal),
};
}
let (anchor_a, anchor_b) = (centroid - a.position, centroid - b.position);
constraint.friction_anchor_a = anchor_a;
constraint.friction_anchor_b = anchor_b;
constraint.tangent_mass = [
effective(anchor_a, anchor_b, tangents[0]),
effective(anchor_a, anchor_b, tangents[1]),
];
constraint.tangent_impulse = [
warm.friction.dot(tangents[0]),
warm.friction.dot(tangents[1]),
];
let twist = inverse_twist_mass(&scratch.bodies, constraint.a, normal)
+ inverse_twist_mass(&scratch.bodies, constraint.b, normal);
constraint.twist_mass = if twist > 0.0 { 1.0 / twist } else { 0.0 };
constraint.twist_impulse = warm.twist;
scratch.constraints.push(constraint);
}
}
fn restitution(&mut self, scratch: &mut Scratch, bodies: &mut [RigidBody]) {
let threshold = self.settings.restitution_threshold;
scratch.bounced.clear();
for (index, c) in scratch.constraints.iter_mut().enumerate() {
if c.restitution == 0.0 {
continue;
}
for k in 0..c.count {
let p = c.points[k];
if p.relative_velocity > -threshold || p.max_normal_impulse == 0.0 {
continue;
}
let vn = relative_velocity(bodies, c, &p).dot(c.normal);
let impulse = -p.normal_mass * (vn + c.restitution * p.relative_velocity);
let new = (p.normal_impulse + impulse).max(0.0);
let delta = new - p.normal_impulse;
let point = &mut c.points[k];
point.normal_impulse = new;
point.max_normal_impulse = point.max_normal_impulse.max(delta);
point.total_normal_impulse += delta;
apply(bodies, &scratch.bodies, c.a, p.anchor_a, -c.normal * delta);
apply(bodies, &scratch.bodies, c.b, p.anchor_b, c.normal * delta);
scratch.bounced.push((index, k));
}
}
for &(index, k) in &scratch.bounced {
let c = &scratch.constraints[index];
let p = &c.points[k];
let after = relative_velocity(bodies, c, p).dot(c.normal);
self.counters.bounces += 1;
self.counters.bounce_ratio_sum += after / -p.relative_velocity;
self.counters.restitution_sum += c.restitution;
}
}
fn store(&mut self, scratch: &Scratch, bodies: &[RigidBody]) {
let settings = self.settings;
for c in &scratch.constraints {
if let Some(Some(contact)) = self.contacts.get_mut(c.slot) {
for (k, p) in c.points[..c.count].iter().enumerate() {
contact.impulses.normal[k] = p.normal_impulse;
}
contact.impulses.friction =
c.tangents[0] * c.tangent_impulse[0] + c.tangents[1] * c.tangent_impulse[1];
contact.impulses.twist = c.twist_impulse;
}
let points = &c.points[..c.count];
let approach = points
.iter()
.map(|p| -p.relative_velocity)
.fold(f64::NEG_INFINITY, f64::max);
let impulse: f64 = points.iter().map(|p| p.total_normal_impulse).sum();
if approach < settings.restitution_threshold || impulse < settings.kinetic_impulse {
continue;
}
let a_moves = c.a != NONE && c.mass_a.is_finite();
let b_moves = c.b != NONE && c.mass_b.is_finite();
let impactor_is_a = if !a_moves {
true
} else if !b_moves {
false
} else {
c.velocity_a.dot(c.normal) >= -c.velocity_b.dot(c.normal)
};
let (impactor, struck, impactor_mass, normal, relative) = if impactor_is_a {
(
c.entity_a,
c.entity_b,
c.mass_a,
c.normal,
-c.point_velocity,
)
} else {
(
c.entity_b,
c.entity_a,
c.mass_b,
-c.normal,
c.point_velocity,
)
};
let Some(struck) = struck else {
continue;
};
let energy_deposited = points
.iter()
.map(|p| {
let after = relative_velocity(bodies, c, p).dot(c.normal);
let before = p.relative_velocity;
(0.5 * p.normal_mass * (before * before - after * after)).max(0.0)
})
.sum();
let point = points.iter().map(|p| p.position).sum::<DVec3>() / c.count as f64;
self.kinetic.push(KineticContact {
source: KineticSource::Contact,
impactor,
struck,
point,
normal,
relative_velocity: relative,
impactor_mass,
energy_deposited,
impulse,
});
}
}
}
fn run_pass(
pass: &Pass,
settings: &ContactSettings,
scratch: &mut Scratch,
joints: &mut [Prepared],
bodies: &mut [RigidBody],
transforms: &mut [Transform],
dt: f64,
) {
let h = dt / f64::from(pass.substeps);
let max_angular_speed = settings.max_rotation / h;
let contacts = pass.contacts.clone();
scratch.carried.clear();
scratch.free_spin.clear();
scratch.touching.clear();
if !joints.is_empty() {
scratch.free_spin.resize(bodies.len(), DVec3::ZERO);
scratch.touching.resize(bodies.len(), false);
for c in &scratch.constraints[contacts.clone()] {
for index in [c.a, c.b] {
if index != NONE {
scratch.touching[index] = true;
}
}
}
}
for k in 0..pass.substeps {
for &index in &pass.bodies {
let body = &mut bodies[index];
let spin = SemiImplicitEuler::integrate_velocity(body, transforms[index].rotation, h);
let speed_squared = body.velocity.length_squared();
if speed_squared > settings.max_linear_speed * settings.max_linear_speed {
body.velocity *= settings.max_linear_speed / speed_squared.sqrt();
}
let turn_squared = body.angular_velocity.length_squared();
if turn_squared > max_angular_speed * max_angular_speed {
body.angular_velocity *= max_angular_speed / turn_squared.sqrt();
}
scratch.bodies[index].spin = spin;
if let Some(free) = scratch.free_spin.get_mut(index) {
*free = body.angular_velocity;
}
}
coast(scratch, bodies, &pass.outside, f64::from(k) * h);
if !joints.is_empty() {
scratch.carried.clear();
scratch.carried.resize(bodies.len(), DVec3::ZERO);
}
joint::warm_start(joints, &scratch.bodies, bodies, &mut scratch.carried);
warm_start(
&scratch.constraints[contacts.clone()],
&scratch.bodies,
bodies,
);
joint::solve(
joints,
&scratch.bodies,
bodies,
h,
Some(&mut scratch.carried),
);
solve_pass(
&mut scratch.constraints[contacts.clone()],
&scratch.bodies,
bodies,
h,
Some(settings.push_out_speed),
);
for &index in &pass.bodies {
let body = &mut bodies[index];
let transform = &mut transforms[index];
let s = &mut scratch.bodies[index];
let carried = match scratch.carried.get(index) {
Some(&joint) if scratch.touching[index] => {
let contact = body.angular_velocity - scratch.free_spin[index] - joint;
uncancelled(joint, contact)
}
Some(&joint) => joint,
None => DVec3::ZERO,
};
SemiImplicitEuler::integrate_position_carrying(body, transform, s.spin, carried, h);
s.moved(transform, body.angular_velocity, h);
}
coast(scratch, bodies, &pass.outside, f64::from(k + 1) * h);
joint::solve(joints, &scratch.bodies, bodies, h, None);
solve_pass(
&mut scratch.constraints[contacts.clone()],
&scratch.bodies,
bodies,
h,
None,
);
for constraint in &mut scratch.constraints[contacts.clone()] {
for point in &mut constraint.points[..constraint.count] {
point.total_normal_impulse += point.normal_impulse;
}
}
}
for &index in &pass.outside {
scratch.bodies[index].rewind();
}
}
fn uncancelled(joint: DVec3, contact: DVec3) -> DVec3 {
let length_squared = joint.length_squared();
if length_squared == 0.0 {
return DVec3::ZERO;
}
let cancelled = (-contact.dot(joint) / length_squared).clamp(0.0, 1.0);
joint * (1.0 - cancelled)
}
fn coast(scratch: &mut Scratch, bodies: &[RigidBody], outside: &[usize], t: f64) {
for &index in outside {
let body = &bodies[index];
scratch.bodies[index].coast(body.velocity, body.angular_velocity, t);
}
}
fn warm_start(constraints: &[Constraint], solver: &[SolverBody], bodies: &mut [RigidBody]) {
for c in constraints {
for p in &c.points[..c.count] {
let impulse = c.normal * p.normal_impulse;
apply(bodies, solver, c.a, p.anchor_a, -impulse);
apply(bodies, solver, c.b, p.anchor_b, impulse);
}
let friction = c.tangents[0] * c.tangent_impulse[0] + c.tangents[1] * c.tangent_impulse[1];
apply(bodies, solver, c.a, c.friction_anchor_a, -friction);
apply(bodies, solver, c.b, c.friction_anchor_b, friction);
apply_angular(bodies, solver, c.a, -c.normal * c.twist_impulse);
apply_angular(bodies, solver, c.b, c.normal * c.twist_impulse);
}
}
fn solve_pass(
constraints: &mut [Constraint],
solver: &[SolverBody],
bodies: &mut [RigidBody],
h: f64,
push_out: Option<f64>,
) {
let inverse_h = 1.0 / h;
for c in constraints.iter_mut() {
let (dp_a, da_a) = motion_since_start(solver, c.a);
let (dp_b, da_b) = motion_since_start(solver, c.b);
for k in 0..c.count {
let p = c.points[k];
let moved = (dp_b - dp_a) + (da_b.cross(p.anchor_b) - da_a.cross(p.anchor_a));
let separation = moved.dot(c.normal) + p.separation;
let (bias, mass_scale, impulse_scale) = if separation > 0.0 {
(separation * inverse_h, 1.0, 0.0)
} else if let Some(push_out) = push_out {
(
(c.softness.bias_rate * separation).max(-push_out),
c.softness.mass_scale,
c.softness.impulse_scale,
)
} else {
(0.0, 1.0, 0.0)
};
let vn = relative_velocity(bodies, c, &p).dot(c.normal);
let impulse =
-p.normal_mass * mass_scale * (vn + bias) - impulse_scale * p.normal_impulse;
let new = (p.normal_impulse + impulse).max(0.0);
let delta = new - p.normal_impulse;
let point = &mut c.points[k];
point.normal_impulse = new;
point.max_normal_impulse = point.max_normal_impulse.max(delta);
apply(bodies, solver, c.a, p.anchor_a, -c.normal * delta);
apply(bodies, solver, c.b, p.anchor_b, c.normal * delta);
}
let points = &c.points[..c.count];
let dv = relative_velocity_at(bodies, c, c.friction_anchor_a, c.friction_anchor_b);
let limit = c.friction * points.iter().map(|p| p.normal_impulse).sum::<f64>();
let old = c.tangent_impulse;
let mut new = [
old[0] - c.tangent_mass[0] * dv.dot(c.tangents[0]),
old[1] - c.tangent_mass[1] * dv.dot(c.tangents[1]),
];
let length_squared = new[0] * new[0] + new[1] * new[1];
if length_squared > limit * limit {
let scale = limit / length_squared.sqrt();
new = [new[0] * scale, new[1] * scale];
}
c.tangent_impulse = new;
let impulse = c.tangents[0] * (new[0] - old[0]) + c.tangents[1] * (new[1] - old[1]);
apply(bodies, solver, c.a, c.friction_anchor_a, -impulse);
apply(bodies, solver, c.b, c.friction_anchor_b, impulse);
let (_, wa) = velocity(bodies, c.a);
let (_, wb) = velocity(bodies, c.b);
let spin = (wb - wa).dot(c.normal);
let limit = c.friction
* points
.iter()
.map(|p| p.normal_impulse * p.twist_radius)
.sum::<f64>();
let old = c.twist_impulse;
let new = (old - c.twist_mass * spin).clamp(-limit, limit);
c.twist_impulse = new;
apply_angular(bodies, solver, c.a, -c.normal * (new - old));
apply_angular(bodies, solver, c.b, c.normal * (new - old));
}
}
fn motion_since_start(solver: &[SolverBody], index: usize) -> (DVec3, DVec3) {
if index == NONE {
(DVec3::ZERO, DVec3::ZERO)
} else {
(solver[index].delta_position, solver[index].delta_angle)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_contact_cancels_the_part_of_a_joints_change_it_opposes() {
let joint = DVec3::new(0.0, 2.0, 0.0);
assert_eq!(uncancelled(joint, -joint), DVec3::ZERO);
assert_eq!(uncancelled(joint, -3.0 * joint), DVec3::ZERO);
assert_eq!(uncancelled(joint, -0.25 * joint), 0.75 * joint);
assert_eq!(uncancelled(joint, joint), joint);
assert_eq!(uncancelled(joint, DVec3::X), joint);
assert_eq!(uncancelled(joint, DVec3::new(5.0, -1.0, 0.0)), 0.5 * joint);
assert_eq!(uncancelled(DVec3::ZERO, DVec3::X), DVec3::ZERO);
assert_eq!(
uncancelled(DVec3::new(1.0, 1.0, 0.0), DVec3::new(-1.0, 0.0, 0.0)),
DVec3::new(0.5, 0.5, 0.0)
);
}
#[test]
fn what_a_contact_cancels_does_not_depend_on_the_axes() {
let joint = DVec3::new(0.3, -1.2, 0.7);
let contact = DVec3::new(-0.9, 0.4, 0.2);
let left = uncancelled(joint, contact);
assert!(left.length() > 0.0 && left.length() < joint.length());
let turn = rotation_from_scaled_axis(DVec3::new(0.4, -1.1, 2.3));
let turned = uncancelled(turn * joint, turn * contact);
assert!(
turned.distance(turn * left) < 1e-12,
"{turned} against {}",
turn * left
);
}
#[test]
fn a_zero_hertz_contact_is_rigid() {
assert_eq!(
Softness::new(0.0, 10.0, 1.0 / 240.0),
Softness {
bias_rate: 0.0,
mass_scale: 1.0,
impulse_scale: 0.0,
}
);
}
#[test]
fn the_softness_of_the_defaults_matches_its_formula() {
let h = 1.0 / 240.0;
let soft = Softness::new(30.0, 10.0, h);
let omega = TAU * 30.0;
let a1 = 20.0 + h * omega;
assert!((soft.bias_rate - omega / a1).abs() < 1e-12);
let a2 = h * omega * a1;
assert!((soft.mass_scale - a2 / (1.0 + a2)).abs() < 1e-12);
assert!((soft.impulse_scale + soft.mass_scale - 1.0).abs() < 1e-12);
}
}