Files
2026-11-14 15:41:09 -06:00

435 lines
16 KiB
Plaintext

#! Contains joints, which hold two bodies together: a `ball` joint holds them
#! at a point they turn about every way, as a shoulder, within a cone it swings
#! in and how far it twists where it's limited, as a ragdoll's limbs are held; a
#! `hinge` holds them at a point and an axis they turn about alone, as a door,
#! with limits to how far it turns and a motor to turn it; a `fixed` joint holds
#! them as one body, rigidly or springily; a `distance` joint keeps two points
#! apart, rigidly as a rod, within lengths as a rope, or springily; a `slider`
#! lets them slide along an axis, turning together, as a piston; and a
#! `six_dof` joint holds each way they move and turn, along and about its own
#! three axes, locked, limited, or free, as any of the others and more.
#!
#! Joints are solved before contacts in each substep, softly as contacts are:
#! each undoes what has drifted as a stiff, damped spring of the space's joint
#! frequency, and a limit pushes only as far as closes it this substep where
#! it's apart, as a speculative contact does.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
#! What a joint holds.
pub enum joint_kind: u8 {
#! The two at a point, about which they turn every way.
ball,
#! The two at a point, about an axis of each, which they turn about alone.
hinge,
#! The two as one.
fixed,
#! Two points apart, as a rod, a rope, or a spring.
distance,
#! The two sliding along an axis, turning together, as a piston.
slider,
#! Each way the two move and turn held as it says.
six_dof,
}
#! How a six-way joint holds one of the ways its bodies move or turn.
pub enum axis_hold: u8 {
#! Not at all: none of it.
locked,
#! Between its low and its high.
limited,
#! As far as it likes.
free,
}
#! What a joint is made as: its kind, its bodies, where it holds each, of the
#! body's own places, and what each kind asks.
pub struct joint {
pub var kind := joint_kind::ball;
pub var a: body_id;
pub var b: body_id;
pub var anchor_a: vec3;
pub var anchor_b: vec3;
#! Of a hinge, the axis it turns about, of each body's own directions.
pub var axis_a := vec3::up;
pub var axis_b := vec3::up;
#! Of a hinge, a fixed joint, or a slider, how `b` is turned within `a`'s own
#! turn, where it rests.
pub var reference := quat::identity;
#! Of a slider, a ball joint's limits, or a six-way joint, the joint's own
#! axes as each body is turned, where they rest together: its x is the
#! slider's axis, or the axis a ball joint swings from and twists about.
pub var frame_a := quat::identity;
pub var frame_b := quat::identity;
#! Of a ball joint limited, the widest it swings from its axis, in radians,
#! its twist about it limited from `lower` to `upper`.
pub var cone: f32;
#! Of a six-way joint, how it holds each way: sliding along its frame's x,
#! y, and z, then twisting about x and swinging about y and z, each by
#! `holds`, from `lows` to `highs` where it's limited; and each way not
#! locked driven at `drives`, in lengths or radians a second, by no more
#! than `forces`, of force or torque, none where that's 0.
pub var holds: axis_hold[6];
pub var lows: f32[6];
pub var highs: f32[6];
pub var drives: f32[6];
pub var forces: f32[6];
#! Whether the two bodies still meet where their colliders do.
pub var collide: bool;
#! Whether it's limited: a hinge to turning from `lower` to `upper` radians
#! from where it rests, and a distance joint to lengths between them.
pub var limit: bool;
pub var lower: f32;
pub var upper: f32;
#! A motor turning a hinge at a speed, in radians a second, or lengthening a
#! distance joint, in lengths a second, with no more than so much torque or
#! force.
pub var motor: bool;
pub var motor_speed: f32;
pub var max_motor_force: f32;
#! A spring toward a hinge's rest or a distance joint's length, of so many
#! cycles a second, damped so: 1 doesn't spring back. Of a fixed joint, how
#! stiff it holds its place, 0 rigid.
pub var spring: bool;
pub var hertz: f32;
pub var damping: f32 = 1;
#! Of a distance joint, the length it holds.
pub var length: f32 = 1;
#! Of a fixed joint, how stiff it holds its turn, 0 rigid.
pub var angular_hertz: f32;
pub var angular_damping: f32 = 1;
#! A number of its user's.
pub var data: u64;
}
#! A joint of a space, as `space::join` names it.
pub struct joint_id {
pub var index: u32 = 0xFFFFFFFF;
pub var generation: u32;
}
pub def joint_id::equals(&this, other: &joint_id): bool {
return this.index == other.index && this.generation == other.generation;
}
# A joint as the space keeps it, and what a step works out of it.
struct joint_record {
var made: joint;
var generation: u32;
var alive: bool;
var body_a: u32;
var body_b: u32;
var next_a: u32 = 0xFFFFFFFF;
var next_b: u32 = 0xFFFFFFFF;
var slot_a: u32;
var slot_b: u32;
var ma: f32;
var mb: f32;
var ra: vec3; # Each anchor from its body's center, as the step began.
var rb: vec3;
var qa: quat; # Each body's turn as the step began.
var qb: quat;
var delta_center: vec3;
var axial_mass: f32;
var linear: vec3; # Impulses, kept from step to step.
var angular: vec3;
var axial: f32;
var spring_impulse: f32;
var motor_impulse: f32;
var lower_impulse: f32;
var upper_impulse: f32;
var spring_soft: softness;
var linear_soft: softness;
var angular_soft: softness;
var held: f32[24]; # Of a six-way joint, each way's impulses: holding it, at its low, at its high, and driving it.
}
#! Joins two bodies.
pub def space::join(&mut this, made: joint): joint_id {
return joint_id{} if !this.has(made.a) || !this.has(made.b) || made.a.index == made.b.index;
var index: u32 = 0;
if this.free_joints.length > 0 {
index = this.free_joints[this.free_joints.length - 1];
this.free_joints.truncate();
} else {
index = this.joints.length as u32;
this.joints.append(joint_record{});
}
val generation := this.joints[index as u64].generation + 1;
val a := made.a.index;
val b := made.b.index;
this.joints[index as u64] = joint_record{
made = made, generation = generation, alive = true, body_a = a, body_b = b,
next_a = this.bodies[a as u64].joints, next_b = this.bodies[b as u64].joints,
};
this.bodies[a as u64].joints = index;
this.bodies[b as u64].joints = index;
if !made.collide {
this.drop_pairs_between(a, b);
}
this.wake_body(a);
this.wake_body(b);
return joint_id{ index = index, generation = generation };
}
#! Holds two bodies at a place of space, about which they turn every way.
pub def space::ball(&mut this, a: body_id, b: body_id, at: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
return this.join(joint{ kind = joint_kind::ball, a = a, b = b, anchor_a = this.pose_of(a).unapply(at), anchor_b = this.pose_of(b).unapply(at) });
}
#! Holds two bodies at a place of space and about an axis through it, of
#! space's directions, as a door's hinge holds it.
pub def space::hinge(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
val along := axis.normalized();
return this.join(joint{
kind = joint_kind::hinge, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
axis_a = pa.unrotate(along), axis_b = pb.unrotate(along), reference = (pa.turn.inverse() * pb.turn).normalized(),
});
}
# The joint axes, as a body is turned, of a frame whose x is a direction of
# space.
def frame_along(turn: quat, axis: vec3): quat {
val x := axis.normalized();
val y := perpendicular_to(x);
return (turn.inverse() * quat::of_basis(x, y, x.cross(y))).normalized();
}
#! Lets two bodies slide along an axis of space through a place, turning
#! together, as a piston: a slider, its limits, motor, and spring its own to
#! set.
pub def space::slider(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::slider, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
frame_a = frame_along(pa.turn, axis), frame_b = frame_along(pb.turn, axis), reference = (pa.turn.inverse() * pb.turn).normalized(),
});
}
#! Holds two bodies at a place of space, about which they turn, `b` swinging
#! no further than `cone` radians from an axis of space and twisting about it
#! no further than `twist` radians either way, as a shoulder or a hip: a ball
#! joint, limited.
pub def space::cone_twist(&mut this, a: body_id, b: body_id, at: vec3, axis: vec3, cone: f32, twist: f32): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::ball, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
frame_a = frame_along(pa.turn, axis), frame_b = frame_along(pb.turn, axis), limit = true, cone = cone, lower = -twist, upper = twist,
});
}
#! Holds two bodies at a place of space by a six-way joint, its axes those of
#! a rotation of space, each way locked until it's changed, as a fixed joint.
pub def space::six_dof(&mut this, a: body_id, b: body_id, at: vec3, axes: quat = quat::identity): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::six_dof, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
frame_a = (pa.turn.inverse() * axes).normalized(), frame_b = (pb.turn.inverse() * axes).normalized(),
});
}
#! Holds two bodies together as one, about a place of space.
pub def space::fix(&mut this, a: body_id, b: body_id, at: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
val pa := this.pose_of(a);
val pb := this.pose_of(b);
return this.join(joint{
kind = joint_kind::fixed, a = a, b = b, anchor_a = pa.unapply(at), anchor_b = pb.unapply(at),
reference = (pa.turn.inverse() * pb.turn).normalized(),
});
}
#! Keeps two places of space, one of each body, as far apart as they are.
pub def space::tie(&mut this, a: body_id, b: body_id, at_a: vec3, at_b: vec3): joint_id {
return joint_id{} if !this.has(a) || !this.has(b);
return this.join(joint{
kind = joint_kind::distance, a = a, b = b, anchor_a = this.pose_of(a).unapply(at_a), anchor_b = this.pose_of(b).unapply(at_b),
length = (at_b - at_a).length, collide = true,
});
}
#! Whether a joint is of it still.
pub def space::has(&this, id: joint_id): bool {
return id.index < this.joints.length as u32 && this.joints[id.index as u64].alive && this.joints[id.index as u64].generation == id.generation;
}
#! What a joint was made as, or last changed to.
pub def space::joint_of(&this, id: joint_id): &joint {
return &this.joints[id.index as u64].made;
}
#! Changes what a joint asks, as its motor or limits, keeping its bodies, and
#! wakes them. What it no longer asks pushes no more: a motor, limits, or a
#! spring turned off, and a six-way joint's ways held otherwise.
pub def space::change(&mut this, id: joint_id, made: joint): void {
return if !this.has(id);
val j := id.index as u64;
var r := this.joints[j];
val a := r.made.a;
val b := r.made.b;
if !made.motor {
r.motor_impulse = 0;
}
if !made.limit {
r.lower_impulse = 0;
r.upper_impulse = 0;
}
if !made.spring {
r.spring_impulse = 0;
}
for k in 0..6u {
if made.holds[k] != r.made.holds[k] || made.kind != r.made.kind || made.limit != r.made.limit {
r.held = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
r.linear = vec3::zero;
}
if made.forces[k] == 0 {
r.held[18 + k] = 0;
}
}
r.made = made;
r.made.a = a;
r.made.b = b;
this.joints[j] = r;
this.wake_body(a.index);
this.wake_body(b.index);
}
#! How far a hinge is turned from where it rests, in radians, about its axis.
pub def space::angle_of(&this, id: joint_id): f32 {
return 0 if !this.has(id);
val j := &this.joints[id.index as u64];
return hinge_angle(&j.made, this.bodies[j.body_a as u64].at.turn, this.bodies[j.body_b as u64].at.turn);
}
# How far `b` is turned about a hinge's axis from where it rests, within `a`'s
# own turn: the twist of the turn between them.
def hinge_angle(made: &joint, qa: quat, qb: quat): f32 {
val apart := (made.reference.inverse() * (qa.inverse() * qb)).normalized();
val axis := made.axis_a;
val along := apart.x * axis.x + apart.y * axis.y + apart.z * axis.z;
return unwound(2 * math::atan2(along, apart.w));
}
# An angle brought within -π to π.
def unwound(angle: f32): f32 {
val pi := math::pi as f32;
return angle < -pi ? angle + 2 * pi : angle > pi ? angle - 2 * pi : angle;
}
#! Takes a joint away, waking its bodies.
pub def space::unjoin(&mut this, id: joint_id): void {
return if !this.has(id);
this.drop_joint(id.index);
}
def space::drop_joint(&mut this, j: u32): void {
val a := this.joints[j as u64].body_a;
val b := this.joints[j as u64].body_b;
this.unlink_joint(j, a);
this.unlink_joint(j, b);
this.joints[j as u64].alive = false;
this.free_joints.append(j);
this.wake_body(a);
this.wake_body(b);
this.touch_colliders(a);
}
def space::unlink_joint(&mut this, j: u32, body: u32): void {
val next := this.next_joint(j, body);
if this.bodies[body as u64].joints == j {
this.bodies[body as u64].joints = next;
return;
}
var k := this.bodies[body as u64].joints;
while k != none {
val after := this.next_joint(k, body);
if after == j {
if this.joints[k as u64].body_a == body {
this.joints[k as u64].next_a = next;
} else {
this.joints[k as u64].next_b = next;
}
return;
}
k = after;
}
}
def space::next_joint(&this, j: u32, body: u32): u32 {
return this.joints[j as u64].body_a == body ? this.joints[j as u64].next_a : this.joints[j as u64].next_b;
}
# Whether a joint holds two bodies and keeps them from meeting.
def space::joined_apart(&this, a: u32, b: u32): bool {
var j := this.bodies[a as u64].joints;
while j != none {
val joint := &this.joints[j as u64];
val other := joint.body_a == a ? joint.body_b : joint.body_a;
return true if other == b && !joint.made.collide;
j = this.next_joint(j, a);
}
return false;
}
def space::drop_joints_of(&mut this, b: u32): void {
while this.bodies[b as u64].joints != none {
this.drop_joint(this.bodies[b as u64].joints);
}
}
def space::drop_pairs_between(&mut this, a: u32, b: u32): void {
for p in 0..this.pairs.length {
continue if !this.pairs[p].alive;
val ba := this.colliders[this.pairs[p].a as u64].body;
val bb := this.colliders[this.pairs[p].b as u64].body;
if (ba == a && bb == b) || (ba == b && bb == a) {
this.drop_pair(p as u32, false);
}
}
}
def space::touch_colliders(&mut this, b: u32): void {
var c := this.bodies[b as u64].colliders;
while c != none {
if !this.colliders[c as u64].moved {
this.colliders[c as u64].moved = true;
this.moved.append(c);
}
c = this.colliders[c as u64].next;
}
}
def space::join_jointed(&this, parent: &mut vector<u32>): void {
for j in 0..this.joints.length {
val joint := &this.joints[j];
continue if !joint.alive;
if parent[joint.body_a as u64] != none && parent[joint.body_b as u64] != none {
join(parent, joint.body_a, joint.body_b);
}
}
}
#! Visits each joint, as `visit(joint, at_a, at_b)`, where it holds each of its
#! bodies, of space's places, until it gives false, as gizmos draw them.
pub def space::each_joint<F>(&this, visit: F): void where F: invokable<def(joint_id, vec3, vec3): bool> {
for j in 0..this.joints.length {
val r := &this.joints[j];
continue if !r.alive;
val at_a := this.bodies[r.body_a as u64].at.apply(r.made.anchor_a);
val at_b := this.bodies[r.body_b as u64].at.apply(r.made.anchor_b);
return if !visit(joint_id{ index = j as u32, generation = r.generation }, at_a, at_b);
}
}