Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-30 23:21:01 -05:00
commit 323f648aad
64 files changed
+13417

No files matched your search

+142
View File
@@ -0,0 +1,142 @@
#! Contains `body` and `collider`, what a `space` is given to make a body and
#! the shapes it's of, and `body_id` and `collider_id`, which name them there.
import malunal::linear;
module malunal::physics3d;
#! What moves a body.
pub enum body_kind: u8 {
#! Nothing: it stays where it's put, as the ground does.
static,
#! Its velocity alone, as it's set: what it meets doesn't push it, as a
#! moving platform's doesn't.
kinematic,
#! Forces, gravity, and what it meets, as a crate.
dynamic,
}
#! What a body is made as: its kind, its pose, how fast it moves at first,
#! and how it's slowed and pulled.
pub struct body {
pub var kind := body_kind::dynamic;
#! Where its origin is, and which way it's turned; its colliders' shapes are
#! of places about the origin.
pub var at := pose::identity;
#! How fast its center of mass moves, in lengths a second.
pub var velocity: vec3;
#! How fast it turns, about the axis it points along, by its length in
#! radians a second.
pub var spin: vec3;
#! How much of its velocity, and of its spin, it loses each second, as air
#! slows it.
pub var linear_damping: f32;
pub var angular_damping: f32 = 0.05;
#! How much of the space's gravity pulls it: 0 floats.
pub var gravity_scale: f32 = 1;
#! Whether it never turns, as a character standing up doesn't.
pub var fixed_rotation: bool;
#! Whether it may sleep when it and what it rests on are still.
pub var can_sleep: bool = true;
#! A number of its user's, as an entity's bits.
pub var data: u64;
}
#! What a body's collider is made as: its shape, about the body's origin; its
#! density, which sums to the body's mass; how it slides and bounces; and the
#! layers it's on and meets. A collider of a triangle mesh, which
#! `space::attach_mesh` gives a body, has no shape or density of its own.
pub struct collider {
pub var shape: shape;
#! Its mass for each volume of 1.
pub var density: f32 = 1;
#! How hard it is to slide along: 0 slides freely. Two colliders' are mixed
#! as the square root of their product.
pub var friction: f32 = 0.6;
#! How much of its speed toward what it meets it keeps, bounced back: 0
#! stops, 1 bounces as high as it fell. Two colliders' greater is taken.
pub var restitution: f32;
#! The layers it's on, and those it meets: two colliders meet where each is
#! on a layer of the other's mask.
pub var layers: u32 = 1;
pub var mask: u32 = 0xFFFFFFFF;
#! Whether it only notes what it overlaps, pushing nothing.
pub var sensor: bool;
#! A number of its user's, as an entity's bits.
pub var data: u64;
}
#! A body of a space, as `space::add` names it.
pub struct body_id {
pub var index: u32 = 0xFFFFFFFF;
pub var generation: u32;
}
pub def body_id::equals(&this, other: &body_id): bool {
return this.index == other.index && this.generation == other.generation;
}
#! A collider of a body of a space, as `space::attach` names it.
pub struct collider_id {
pub var index: u32 = 0xFFFFFFFF;
pub var generation: u32;
}
pub def collider_id::equals(&this, other: &collider_id): bool {
return this.index == other.index && this.generation == other.generation;
}
# No body, collider, contact, mesh, or joint.
const none: u32 = 0xFFFFFFFF;
# A body as the space keeps it.
struct body_record {
var kind: body_kind;
var generation: u32;
var alive: bool;
var at: pose; # Of its origin.
var center: vec3; # Its center of mass, in space.
var local_center: vec3; # The same, of its own places.
var velocity: vec3;
var spin: vec3;
var force: vec3;
var torque: vec3;
var mass: f32;
var inv_mass: f32;
var inertia: mat3; # About its center of mass, of its own axes.
var inv_inertia: mat3; # The same, inverted.
var linear_damping: f32;
var angular_damping: f32;
var gravity_scale: f32 = 1;
var fixed_rotation: bool;
var can_sleep: bool = true;
var awake: bool = true;
var sleep_time: f32;
var extent: f32; # How far its colliders reach from its center.
var colliders: u32 = 0xFFFFFFFF;
var joints: u32 = 0xFFFFFFFF;
var group: u32 = 0xFFFFFFFF;
var next_in_group: u32 = 0xFFFFFFFF;
var slot: u32;
var data: u64;
}
# A collider as the space keeps it: of a shape, or of a mesh the space holds.
struct collider_record {
var made: collider;
var mesh: u32 = 0xFFFFFFFF;
var body: u32;
var leaf: u32 = 0xFFFFFFFF;
var next: u32 = 0xFFFFFFFF;
var generation: u32;
var alive: bool;
var moved: bool;
}
def body_record::is_dynamic(&this): bool {
return this.kind == body_kind::dynamic;
}
# Whether a collider is of a mesh.
def collider_record::is_mesh(&this): bool {
return this.mesh != none;
}
+707
View File
@@ -0,0 +1,707 @@
#! Contains collision between shapes: whether two meet, where they're placed,
#! and the `manifold` of where and how deep, which way to push them apart.
#!
#! Each shape is taken as a core, with its radius around it: a sphere's a
#! place, a capsule's a segment, and a hull itself, of no radius. Two spheres
#! or capsules meet as their cores near, a capsule lying along another at two
#! points. A sphere or capsule and a hull meet as the core nears the hull's
#! surface, a capsule lying along a face at two points; or, where the core
#! passes within the hull, by the face or edge that holds them furthest apart,
#! as the separating axis theorem finds it. Two hulls meet by the face of
#! either, or the pair of edges, one of each, that holds them furthest apart,
#! edges only where they make a face of the hulls' Minkowski difference, as
#! Gregorius tests them; at a face, the other's face most against it is
#! clipped to it, at as many as four points, and at two edges, at one.
import std::math;
import malunal::linear;
module malunal::physics3d;
#! The most points a manifold holds.
pub const max_contacts: u32 = 4;
#! A point where two shapes meet: midway between their surfaces, how deep the
#! one is within the other there, 0 where they touch, and which of their
#! features met there, the same from one step to the next while they still
#! meet so, by which a solver carries over what it found.
pub struct contact {
pub var point: vec3;
pub var depth: f32;
pub var id: u32;
}
#! Where and how deep two shapes meet: the normal from the first toward the
#! second, along which the second is pushed out of the first, and one to four
#! points, as a box resting flat on another rests on four.
pub struct manifold {
pub var normal: vec3;
pub var points: contact[4];
pub var count: u32;
}
#! The deepest of its points.
pub val manifold::depth: f32 {
get => this.deepest();
}
def manifold::deepest(&this): f32 {
var most := this.count == 0 ? 0f : this.points[0].depth;
for i in 1..this.count {
most = math::max(most, this.points[i].depth);
}
return most;
}
#! The manifold turned around, of the second shape against the first.
pub def manifold::flipped(&this): manifold {
return manifold{ normal = -this.normal, points = this.points, count = this.count };
}
#! Where two shapes meet, each where its pose places it, or nothing where they
#! don't: the manifold's normal from the first toward the second. Within a
#! `margin`, shapes apart are given points too, of depths below 0, as far as
#! they're apart, as a solver keeps what's about to meet from passing through.
pub def collide(a: &shape, at_a: pose, b: &shape, at_b: pose, margin: f32 = 0): maybe<manifold> {
if a.kind != shape_kind::hull && b.kind == shape_kind::hull {
if collide(b, at_b, a, at_a, margin) is some(m) {
return m.flipped();
}
return nothing{};
}
# Everything is worked out as the first shape sees it, then placed.
val rel := at_a.unapply_pose(at_b);
var found: maybe<manifold> = nothing{};
if a.kind != shape_kind::hull {
found = cores(a.a, a.b, a.radius, rel.apply(b.a), rel.apply(b.b), b.radius, margin);
} else if b.kind != shape_kind::hull {
found = hull_and_core(a.as_hull(), rel.apply(b.a), rel.apply(b.b), b.radius, margin);
} else {
found = hulls(a.as_hull(), b.as_hull(), &rel, margin);
}
if found is some(m) {
return placed(m, &at_a);
}
return nothing{};
}
#! Whether two shapes meet, each where its pose places it, touching among it.
pub def overlaps(a: &shape, at_a: pose, b: &shape, at_b: pose): bool {
return collide(a, at_a, b, at_b) is some(_);
}
# A manifold of a shape's own places, in space, where a pose places the shape.
def placed(m: manifold, at: &pose): manifold {
val turn := mat3::rotation(at.turn);
var made := manifold{ normal = turn * m.normal, count = m.count };
for i in 0..m.count {
made.points[i] = contact{ point = at.at + turn * m.points[i].point, depth = m.points[i].depth, id = m.points[i].id };
}
return made;
}
# A manifold of one point, between the surfaces of the first, at `on_a`
# within `radius_a` of it along the normal, and the second's, at `on_b` less
# `radius_b`.
def one_point(normal: vec3, on_a: vec3, radius_a: f32, on_b: vec3, radius_b: f32, depth: f32, id: u32): manifold {
var made := manifold{ normal = normal, count = 1 };
made.points[0] = contact{ point = ((on_a + normal * radius_a) + (on_b - normal * radius_b)) * 0.5, depth = depth, id = id };
return made;
}
# Two spheres or capsules, by their cores, each a segment, a sphere's of one
# place.
def cores(a1: vec3, a2: vec3, ra: f32, b1: vec3, b2: vec3, rb: f32, margin: f32): maybe<manifold> {
val reach := ra + rb;
val pair := nearest_of_segments(a1, a2, b1, b2);
val between := pair[1] - pair[0];
val distance := between.length;
return nothing{} if distance > reach + margin;
val da := a2 - a1;
val db := b2 - b1;
var normal := vec3::up;
if distance > tiny {
normal = between * (1 / distance);
} else {
# Their cores cross: apart along what's at right angles to both, or to
# either, from the first's middle toward the second's.
var across := da.cross(db);
if across.length_squared <= tiny {
across = da.length_squared > tiny ? perpendicular_to(da.normalized()) : db.length_squared > tiny ? perpendicular_to(db.normalized()) : vec3::up;
}
normal = across.normalized();
if normal.dot((b1 + b2) * 0.5 - (a1 + a2) * 0.5) < 0 {
normal = -normal;
}
}
# Two capsules lying along one another meet at the ends of what of the
# second lies beside the first.
val la := da.length_squared;
if la > tiny && db.length_squared > tiny && math::abs(da.normalized().dot(db.normalized())) > 0.99 {
val s1 := (b1 - a1).dot(da) / la;
val s2 := (b2 - a1).dot(da) / la;
var low: f32 = 0;
var high: f32 = 1;
if math::abs(s2 - s1) > tiny {
val u0 := -s1 / (s2 - s1);
val u1 := (1 - s1) / (s2 - s1);
low = math::max(0f, math::min(u0, u1));
high = math::min(1f, math::max(u0, u1));
}
if high - low > 1e-3 {
var made := manifold{ normal = normal };
val ends: f32[2] = [low, high];
for k in 0..2u {
val q := b1 + db * ends[k];
val p := nearest_on_segment(q, a1, a2);
val s := (q - p).dot(normal);
continue if s > reach + margin;
made.points[made.count] = contact{ point = ((p + normal * ra) + (q - normal * rb)) * 0.5, depth = reach - s, id = k as u32 };
made.count++;
}
return made if made.count == 2;
}
}
return one_point(normal, pair[0], ra, pair[1], rb, reach - distance, 0);
}
# A hull and a sphere or capsule, by its core, a segment, a sphere's of one
# place.
def hull_and_core(h: &hull, b1: vec3, b2: vec3, rb: f32, margin: f32): maybe<manifold> {
val point := (b2 - b1).length_squared <= tiny * tiny;
# Whether the core passes within the hull: the part of it within each
# face's side, as Cyrus and Beck clip a line.
val d := b2 - b1;
var low: f32 = 0;
var high: f32 = 1;
for f in 0..h.faces {
val out := h.normal(f).dot(b1) - h.offset(f);
val rate := h.normal(f).dot(d);
if math::abs(rate) <= tiny {
if out > 0 {
high = -1;
break;
}
continue;
}
val t := -out / rate;
if rate < 0 {
low = math::max(low, t);
} else {
high = math::min(high, t);
}
break if low > high;
}
return core_within(h, b1, b2, point, rb, margin) if low <= high;
# Apart: the nearest of the hull to either end, or of its edges to the
# segment.
var best := 1e30f;
var on_hull := b1;
var on_core := b1;
val ends: vec3[2] = [b1, b2];
for k in 0..(point ? 1u : 2u) {
val near := nearest_on_hull(h, ends[k]);
val d2 := (ends[k] - near).length_squared;
if d2 < best {
best = d2;
on_hull = near;
on_core = ends[k];
}
}
if !point {
for e in 0..h.edges {
val corners := h.edge(e);
val pair := nearest_of_segments(h.point(corners[0]), h.point(corners[1]), b1, b2);
val d2 := (pair[1] - pair[0]).length_squared;
if d2 < best {
best = d2;
on_hull = pair[0];
on_core = pair[1];
}
}
}
val distance := math::sqrt(best);
return nothing{} if distance > rb + margin;
return core_within(h, b1, b2, point, rb, margin) if distance <= tiny;
val normal := (on_core - on_hull) * (1 / distance);
if !point {
# Lying along a face, it meets it where it lies over it, at two points.
val face := most_facing(h, normal);
if h.normal(face).dot(normal) > 0.995 {
val along := face_contacts(h, face, b1, b2, rb, margin);
return along if along.count > 0;
}
}
return one_point(normal, on_hull, 0, on_core, rb, rb - distance, 0);
}
# A core passing within a hull: apart along the hull's face, or the axis at
# right angles to an edge of the hull and the segment, holding them furthest
# apart.
def core_within(h: &hull, b1: vec3, b2: vec3, point: bool, rb: f32, margin: f32): maybe<manifold> {
var face: u32 = 0;
var face_apart := -1e30f;
for f in 0..h.faces {
val n := h.normal(f);
val s := math::min(n.dot(b1), n.dot(b2)) - h.offset(f);
if s > face_apart {
face_apart = s;
face = f;
}
}
var edge: u32 = 0;
var edge_apart := -1e30f;
var axis := vec3::zero;
if !point {
val db := b2 - b1;
for e in 0..h.edges {
val corners := h.edge(e);
val ea := h.point(corners[0]);
var l := (h.point(corners[1]) - ea).cross(db);
continue if l.length_squared <= tiny;
l = l.normalized();
if l.dot(ea - h.center) < 0 {
l = -l;
}
val s := math::min(l.dot(b1), l.dot(b2)) - h.point(h.support(l)).dot(l);
if s > edge_apart {
edge_apart = s;
edge = e;
axis = l;
}
}
}
if better_edge(edge_apart, face_apart) {
val corners := h.edge(edge);
val pair := nearest_of_segments(h.point(corners[0]), h.point(corners[1]), b1, b2);
return one_point(axis, pair[0], 0, pair[1], rb, rb - edge_apart, 0x80000000 | edge);
}
val n := h.normal(face);
if !point {
val along := face_contacts(h, face, b1, b2, rb, margin);
return along if along.count > 0;
}
# The deepest end, pushed out by the face.
val q := n.dot(b1) <= n.dot(b2) ? b1 : b2;
val s := n.dot(q) - h.offset(face);
return one_point(n, q - n * s, 0, q, rb, rb - s, 0);
}
# The face whose normal is most along a direction.
def most_facing(h: &hull, direction: vec3): u32 {
var found: u32 = 0;
var most := -2f;
for f in 0..h.faces {
val d := h.normal(f).dot(direction);
if d > most {
most = d;
found = f;
}
}
return found;
}
# The hull's place nearest a place outside it: on a face it's in front of,
# where it lies over the face, else on one of the face's edges.
def nearest_on_hull(h: &hull, q: vec3): vec3 {
var best := 1e30f;
var found := q;
for f in 0..h.faces {
val n := h.normal(f);
val s := n.dot(q) - h.offset(f);
continue if s <= 0;
val on_plane := q - n * s;
if within_face(h, f, on_plane) {
if s * s < best {
best = s * s;
found = on_plane;
}
continue;
}
val size := h.face_size(f);
for k in 0..size {
val p := nearest_on_segment(q, h.point(h.corner(f, k)), h.point(h.corner(f, (k + 1) % size)));
val d2 := (q - p).length_squared;
if d2 < best {
best = d2;
found = p;
}
}
}
return found;
}
# Whether a place in a face's plane lies within its edges.
def within_face(h: &hull, f: u32, p: vec3): bool {
val n := h.normal(f);
val size := h.face_size(f);
for k in 0..size {
val a := h.point(h.corner(f, k));
val b := h.point(h.corner(f, (k + 1) % size));
return false if (b - a).cross(p - a).dot(n) < 0;
}
return true;
}
# A segment clipped to a hull's face, where it lies over it: each end left
# within reach of the face a point.
def face_contacts(h: &hull, face: u32, b1: vec3, b2: vec3, rb: f32, margin: f32): manifold {
val n := h.normal(face);
var ends: vec3[2] = [b1, b2];
var made := manifold{ normal = n };
val size := h.face_size(face);
for k in 0..size {
val a := h.point(h.corner(face, k));
val b := h.point(h.corner(face, (k + 1) % size));
val side := (b - a).cross(n);
return made if !clip_segment(&mut ends, side, side.dot(a));
}
val offset := h.offset(face);
for k in 0..2u {
val q := ends[k];
val s := n.dot(q) - offset;
continue if s > rb + margin;
made.points[made.count] = contact{ point = ((q - n * s) + (q - n * rb)) * 0.5, depth = rb - s, id = k as u32 };
made.count++;
}
return made;
}
# Clips a segment to the side of a plane where `normal.dot(p) <= offset`, as
# Sutherland and Hodgman clip: false where none of it is there.
def clip_segment(ends: &mut vec3[2], normal: vec3, offset: f32): bool {
val d0 := normal.dot(ends[0]) - offset;
val d1 := normal.dot(ends[1]) - offset;
return true if d0 <= 0 && d1 <= 0;
return false if d0 > 0 && d1 > 0;
val crossing := ends[0] + (ends[1] - ends[0]) * (d0 / (d0 - d1));
if d0 > 0 {
ends[0] = crossing;
} else {
ends[1] = crossing;
}
return true;
}
# Whether two edges' arcs on the sphere of directions cross, so the edge
# between faces `a` and `b` of one hull and that between `c` and `d` of the
# other, its normals turned around, make a face of their Minkowski
# difference, as Gregorius tests it: the only pairs of edges whose axis is a
# separating axis worth testing.
def minkowski_face(a: vec3, b: vec3, c: vec3, d: vec3): bool {
val bxa := b.cross(a);
val dxc := d.cross(c);
val cba := c.dot(bxa);
val dba := d.dot(bxa);
val adc := a.dot(dxc);
val bdc := b.dot(dxc);
return cba * dba < 0 && adc * bdc < 0 && cba * bdc > 0;
}
# Whether a separation is better than another by enough to be taken over it,
# so the same pair is met the same way from one step to the next: a face of
# the second hull's over the first's by a millimeter and 2 percent, and an
# edge's over a face's by a millimeter and 5, as an edge's point moves more as
# they turn.
def better(separation: f32, than: f32): bool {
return separation > than + 1e-3 + 0.02 * math::abs(than);
}
def better_edge(separation: f32, than: f32): bool {
return separation > than + 1e-3 + 0.05 * math::abs(than);
}
# Two hulls, the second placed in the first's places by `rel`.
def hulls(a: &hull, b: &hull, rel: &pose, margin: f32): maybe<manifold> {
val turn := mat3::rotation(rel.turn);
var bp: vec3[32];
var bn: vec3[60];
for i in 0..b.count {
bp[i] = rel.at + turn * b.point(i);
}
for f in 0..b.faces {
bn[f] = turn * b.normal(f);
}
val b_center := rel.at + turn * b.center;
# The faces of the first.
var face_a: u32 = 0;
var apart_a := -1e30f;
for f in 0..a.faces {
val n := a.normal(f);
var least := 1e30f;
for j in 0..b.count {
least = math::min(least, n.dot(bp[j]));
}
val s := least - a.offset(f);
if s > apart_a {
apart_a = s;
face_a = f;
}
}
return nothing{} if apart_a > margin;
# The faces of the second.
var face_b: u32 = 0;
var apart_b := -1e30f;
for f in 0..b.faces {
val n := bn[f];
val offset := n.dot(bp[b.corner(f, 0)]);
var least := 1e30f;
for i in 0..a.count {
least = math::min(least, n.dot(a.point(i)));
}
val s := least - offset;
if s > apart_b {
apart_b = s;
face_b = f;
}
}
return nothing{} if apart_b > margin;
# Pairs of edges, one of each.
val flat := a.is_flat || b.is_flat;
var edge_a: u32 = 0;
var edge_b: u32 = 0;
var apart_e := -1e30f;
var axis := vec3::zero;
for ea in 0..a.edges {
val ac := a.edge(ea);
val p1 := a.point(ac[0]);
val da := a.point(ac[1]) - p1;
val af := a.edge_faces(ea);
for eb in 0..b.edges {
# Only pairs whose arcs of the Gauss map cross make a face of the
# Minkowski difference, which is cheaper to ask than the axis is to find.
if !flat {
val bf := b.edge_faces(eb);
continue if !minkowski_face(a.normal(af[0]), a.normal(af[1]), -bn[bf[0]], -bn[bf[1]]);
}
val bc := b.edge(eb);
val q1 := bp[bc[0]];
val db := bp[bc[1]] - q1;
var l := da.cross(db);
val length := l.length;
continue if length <= 1e-4 * math::sqrt(da.length_squared * db.length_squared);
l = l * (1 / length);
var s: f32 = 0;
if flat {
# A flat hull's edges meet the other's anywhere, so each axis is
# tested by how far the hulls reach along it, either way.
var a_low := 1e30f;
var a_high := -1e30f;
for i in 0..a.count {
val x := l.dot(a.point(i));
a_low = math::min(a_low, x);
a_high = math::max(a_high, x);
}
var b_low := 1e30f;
var b_high := -1e30f;
for j in 0..b.count {
val x := l.dot(bp[j]);
b_low = math::min(b_low, x);
b_high = math::max(b_high, x);
}
s = b_low - a_high;
if a_low - b_high > s {
s = a_low - b_high;
l = -l;
}
} else {
if l.dot(p1 - a.center) < 0 {
l = -l;
}
s = l.dot(q1 - p1);
}
if s > apart_e {
apart_e = s;
edge_a = ea;
edge_b = eb;
axis = l;
}
}
}
return nothing{} if apart_e > margin;
val apart_face := math::max(apart_a, apart_b);
if better_edge(apart_e, apart_face) {
val ac := a.edge(edge_a);
val bc := b.edge(edge_b);
val pair := nearest_of_segments(a.point(ac[0]), a.point(ac[1]), bp[bc[0]], bp[bc[1]]);
return one_point(axis, pair[0], 0, pair[1], 0, -apart_e, 0x80000000 | (edge_a << 8) | edge_b);
}
return clipped(a, b, &bp, &bn, face_a, face_b, better(apart_b, apart_a), margin);
}
# The face of the other hull most against the reference face, clipped to the
# reference face's sides: each corner left within the margin of the reference
# face a point, as many as four kept.
def clipped(a: &hull, b: &hull, bp: &vec3[32], bn: &vec3[60], face_a: u32, face_b: u32, flip: bool, margin: f32): maybe<manifold> {
# The reference face's corners and normal, and the incident face's corners.
var reference: vec3[32];
var size: u32 = 0;
var n := vec3::zero;
var polygon: vec3[64];
var ids: u32[64];
var count: u32 = 0;
var incident: u32 = 0;
if !flip {
n = a.normal(face_a);
size = a.face_size(face_a);
for k in 0..size {
reference[k] = a.point(a.corner(face_a, k));
}
var least := 2f;
for f in 0..b.faces {
val d := bn[f].dot(n);
if d < least {
least = d;
incident = f;
}
}
count = b.face_size(incident);
for k in 0..count {
polygon[k] = bp[b.corner(incident, k)];
ids[k] = k;
}
} else {
n = bn[face_b];
size = b.face_size(face_b);
for k in 0..size {
reference[k] = bp[b.corner(face_b, k)];
}
var least := 2f;
for f in 0..a.faces {
val d := a.normal(f).dot(n);
if d < least {
least = d;
incident = f;
}
}
count = a.face_size(incident);
for k in 0..count {
polygon[k] = a.point(a.corner(incident, k));
ids[k] = k;
}
}
# The faces met, in the high bits of each point's id.
val flipped: u32 = flip ? 0x40000000 : 0;
val tag := flipped | ((flip ? face_b : face_a) << 22) | (incident << 16);
# Clipped by the plane through each edge of the reference face, at right
# angles to it.
var next: vec3[64];
var next_ids: u32[64];
for k in 0..size {
val from := reference[k];
val side := (reference[(k + 1) % size] - from).cross(n);
val offset := side.dot(from);
var made: u32 = 0;
for i in 0..count {
val p := polygon[i];
val q := polygon[(i + 1) % count];
val dp := side.dot(p) - offset;
val dq := side.dot(q) - offset;
if dp <= 0 && made < 64 {
next[made] = p;
next_ids[made] = ids[i];
made++;
}
if (dp <= 0) != (dq <= 0) && made < 64 {
next[made] = p + (q - p) * (dp / (dp - dq));
next_ids[made] = ((k + 1) << 8) | i;
made++;
}
}
count = made;
for i in 0..count {
polygon[i] = next[i];
ids[i] = next_ids[i];
}
break if count == 0;
}
# What's within the margin of the reference face, midway between it and
# the incident face.
val offset := n.dot(reference[0]);
var found: contact[64];
var kept: u32 = 0;
for i in 0..count {
val s := n.dot(polygon[i]) - offset;
continue if s > margin;
found[kept] = contact{ point = polygon[i] - n * (s * 0.5), depth = -s, id = tag | ids[i] };
kept++;
}
return nothing{} if kept == 0;
var made := manifold{ normal = flip ? -n : n };
if kept <= max_contacts {
for i in 0..kept {
made.points[i] = found[i];
}
made.count = kept;
return made;
}
return reduced(&found, kept, n, made);
}
# Four of many points, holding the most of the area they hold: the deepest,
# the one furthest from it, the one making the largest triangle of those, and
# the one adding the most to the triangle.
def reduced(found: &contact[64], count: u32, n: vec3, into: manifold): manifold {
var made := into;
var first: u32 = 0;
for i in 1..count {
if found[i].depth > found[first].depth {
first = i;
}
}
val p1 := found[first].point;
var second := first;
var best: f32 = -1;
for i in 0..count {
val d := (found[i].point - p1).length_squared;
if d > best {
best = d;
second = i;
}
}
val p2 := found[second].point;
var third := first;
var area: f32 = 0;
for i in 0..count {
val a := (p2 - p1).cross(found[i].point - p1).dot(n);
if math::abs(a) > math::abs(area) {
area = a;
third = i;
}
}
# Counterclockwise about the normal.
if area < 0 {
val swapped := second;
second = third;
third = swapped;
}
val q1 := found[first].point;
val q2 := found[second].point;
val q3 := found[third].point;
var fourth := first;
var added: f32 = 0;
for i in 0..count {
val q := found[i].point;
val a1 := (q1 - q).cross(q2 - q).dot(n);
val a2 := (q2 - q).cross(q3 - q).dot(n);
val a3 := (q3 - q).cross(q1 - q).dot(n);
val least := math::min(a1, math::min(a2, a3));
if least < added {
added = least;
fourth = i;
}
}
made.points[0] = found[first];
made.points[1] = found[second];
made.points[2] = found[third];
made.count = 3;
if fourth != first {
made.points[3] = found[fourth];
made.count = 4;
}
return made;
}
+378
View File
@@ -0,0 +1,378 @@
#! Contains how a space finds which colliders are near one another, by the
#! boxes of its tree, and where those meet, as contacts kept from one step to
#! the next, so each begins with the impulses that held its bodies apart last.
#! Two shapes have one contact; a shape and a triangle mesh one for each
#! triangle they meet, named by the triangle, so it's kept as they slide.
import std::containers;
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Two colliders that began or stopped touching in a step: sensors among
#! them, which touch where they overlap.
pub struct contact_event {
pub var a: collider_id;
pub var b: collider_id;
#! Whether they began touching, or stopped.
pub var began: bool;
#! Whether either is a sensor.
pub var sensor: bool;
}
# Two colliders whose grown boxes meet, the first's index the lesser, and
# their contacts, a list of them: none of sensors, which only note whether
# they overlap.
struct pair_record {
var a: u32;
var b: u32;
var contacts: u32 = 0xFFFFFFFF;
var touching: bool;
var sensor: bool;
var mesh: bool;
var alive: bool;
}
# Where two colliders meet, or a shape and one triangle of a mesh: the
# manifold, and the impulses that held them apart at each of its points last
# step, along the normal and the two tangents.
struct contact_record {
var pair: u32;
var child: u32; # The triangle, of a mesh's.
var next: u32 = 0xFFFFFFFF;
var body_a: u32;
var body_b: u32;
var manifold: manifold;
var normal_impulse: f32[4];
var tangent_impulse: vec3[4]; # Along the first tangent, then the second.
var friction: f32;
var restitution: f32;
var touching: bool;
var seen: bool;
var alive: bool;
}
# A triangle a shape met, and how.
struct met_triangle {
var triangle: u32;
var manifold: manifold;
}
# A manifold's points and another's of the same normal, as four of them that
# hold the most of the area they hold.
def merge_into(into: &mut manifold, other: &manifold): void {
var found: contact[64];
var count: u32 = 0;
for i in 0..into.count {
found[count] = into.points[i];
count++;
}
for i in 0..other.count {
found[count] = other.points[i];
count++;
}
if count <= max_contacts {
for i in 0..count {
into.points[i] = found[i];
}
into.count = count;
return;
}
val kept := reduced(&found, count, into.normal, manifold{ normal = into.normal });
into.points = kept.points;
into.count = kept.count;
}
def pair_key(a: u32, b: u32): u64 {
val low := math::min(a, b) as u64;
val high := math::max(a, b) as u64;
return (low << 32) | high;
}
# Whether two colliders may meet: of two bodies, one of them dynamic, on
# layers each other's masks hold, not both meshes, and not of bodies a joint
# keeps apart.
def space::may_meet(&this, a: u32, b: u32): bool {
val ca := &this.colliders[a as u64];
val cb := &this.colliders[b as u64];
return false if ca.body == cb.body || (ca.is_mesh() && cb.is_mesh());
return false if !this.bodies[ca.body as u64].is_dynamic() && !this.bodies[cb.body as u64].is_dynamic();
return false if (ca.made.layers & cb.made.mask) == 0 || (cb.made.layers & ca.made.mask) == 0;
return !this.joined_apart(ca.body, cb.body);
}
# Pairs each collider whose leaf moved with those its grown box newly meets.
def space::find_pairs(&mut this): void {
return if this.moved.length == 0;
var near := move(this.near);
for m in 0..this.moved.length {
val c := this.moved[m];
continue if !this.colliders[c as u64].alive;
near.clear();
this.tree.query(this.tree.box_of(this.colliders[c as u64].leaf), def(leaf: u32, data: u64): bool {
val other := data as u32;
if other != c && !(this.colliders[data].moved && other < c) {
near.append(other);
}
return true;
});
for k in 0..near.length {
val other := near[k];
val key := pair_key(c, other);
if this.may_meet(c, other) && !this.pair_keys.contains(&key) {
this.make_pair(math::min(c, other), math::max(c, other));
}
}
}
for m in 0..this.moved.length {
this.colliders[this.moved[m] as u64].moved = false;
}
this.moved.clear();
this.near = move(near);
}
def space::make_pair(&mut this, a: u32, b: u32): void {
var p: u32 = 0;
if this.free_pairs.length > 0 {
p = this.free_pairs[this.free_pairs.length - 1];
this.free_pairs.truncate();
} else {
p = this.pairs.length as u32;
this.pairs.append(pair_record{});
}
val sensor := this.colliders[a as u64].made.sensor || this.colliders[b as u64].made.sensor;
val mesh := this.colliders[a as u64].is_mesh() || this.colliders[b as u64].is_mesh();
this.pairs[p as u64] = pair_record{ a = a, b = b, sensor = sensor, mesh = mesh, alive = true };
this.pair_keys.set(pair_key(a, b), p);
if !sensor && !mesh {
this.pairs[p as u64].contacts = this.make_contact(p, 0);
}
}
# A new contact of a pair, put first of its list.
def space::make_contact(&mut this, p: u32, child: u32): u32 {
var k: u32 = 0;
if this.free_contacts.length > 0 {
k = this.free_contacts[this.free_contacts.length - 1];
this.free_contacts.truncate();
} else {
k = this.contacts.length as u32;
this.contacts.append(contact_record{});
}
val a := this.pairs[p as u64].a;
val b := this.pairs[p as u64].b;
val ma := &this.colliders[a as u64].made;
val mb := &this.colliders[b as u64].made;
this.contacts[k as u64] = contact_record{
pair = p, child = child, next = this.pairs[p as u64].contacts,
body_a = this.colliders[a as u64].body, body_b = this.colliders[b as u64].body,
friction = math::sqrt(ma.friction * mb.friction), restitution = math::max(ma.restitution, mb.restitution), alive = true,
};
return k;
}
def space::free_contact(&mut this, k: u32): void {
this.contacts[k as u64].alive = false;
this.free_contacts.append(k);
}
# Frees a pair and its contacts, noting it stopped where it touched, and
# waking its bodies then where `wake` is given.
def space::drop_pair(&mut this, p: u32, wake: bool): void {
val pair := this.pairs[p as u64];
if pair.touching {
this.note(p, false);
if wake {
this.wake_body(this.colliders[pair.a as u64].body);
this.wake_body(this.colliders[pair.b as u64].body);
}
}
var k := pair.contacts;
while k != none {
val next := this.contacts[k as u64].next;
this.free_contact(k);
k = next;
}
this.pair_keys.remove(&pair_key(pair.a, pair.b));
this.pairs[p as u64].alive = false;
this.free_pairs.append(p);
}
def space::note(&mut this, p: u32, began: bool): void {
val a := this.pairs[p as u64].a;
val b := this.pairs[p as u64].b;
this.noted.append(contact_event{
a = collider_id{ index = a, generation = this.colliders[a as u64].generation },
b = collider_id{ index = b, generation = this.colliders[b as u64].generation },
began = began, sensor = this.pairs[p as u64].sensor,
});
}
# Whether a body moves this step: dynamic or kinematic, and awake.
def space::moves(&this, b: u32): bool {
val body := &this.bodies[b as u64];
return body.kind != body_kind::static && body.awake;
}
# Finds where each pair of a moving body meets, dropping those whose grown
# boxes no longer meet.
def space::update_contacts(&mut this): void {
for p in 0..this.pairs.length {
continue if !this.pairs[p].alive;
val a := this.pairs[p].a;
val b := this.pairs[p].b;
val ba := this.colliders[a as u64].body;
val bb := this.colliders[b as u64].body;
continue if !this.moves(ba) && !this.moves(bb);
if !this.tree.box_of(this.colliders[a as u64].leaf).overlaps(this.tree.box_of(this.colliders[b as u64].leaf)) {
this.drop_pair(p as u32, false);
continue;
}
var touching := false;
if this.pairs[p].sensor {
touching = this.sensed(a, b);
} else if this.pairs[p].mesh {
touching = this.update_mesh_contacts(p as u32);
} else {
touching = this.update_contact(this.pairs[p].contacts, this.manifold_of(a, b, this.speculative));
}
if touching != this.pairs[p].touching {
this.pairs[p].touching = touching;
this.note(p as u32, touching);
}
if touching {
this.wake_if_pushed(ba, bb);
this.wake_if_pushed(bb, ba);
}
}
}
# Wakes a sleeping dynamic body where what touches it is awake and moves it: a
# dynamic body, or a kinematic one moving.
def space::wake_if_pushed(&mut this, b: u32, by: u32): void {
return if this.bodies[b as u64].awake || this.bodies[b as u64].kind != body_kind::dynamic;
val other := &this.bodies[by as u64];
if other.awake && (other.kind == body_kind::dynamic || other.velocity.length_squared > 0 || other.spin.length_squared > 0) {
this.wake_body(b);
}
}
# Where two colliders' shapes meet, within a margin.
def space::manifold_of(&this, a: u32, b: u32, margin: f32): manifold {
val ca := &this.colliders[a as u64];
val cb := &this.colliders[b as u64];
if collide(&ca.made.shape, this.bodies[ca.body as u64].at, &cb.made.shape, this.bodies[cb.body as u64].at, margin) is some(m) {
return m;
}
return manifold{};
}
# Whether a sensor's pair overlaps: a shape and a shape, or a shape and a
# mesh.
def space::sensed(&this, a: u32, b: u32): bool {
val ca := &this.colliders[a as u64];
val cb := &this.colliders[b as u64];
val at_a := this.bodies[ca.body as u64].at;
val at_b := this.bodies[cb.body as u64].at;
return this.meshes[ca.mesh as u64].overlaps(at_a, &cb.made.shape, at_b) if ca.is_mesh();
return this.meshes[cb.mesh as u64].overlaps(at_b, &ca.made.shape, at_a) if cb.is_mesh();
return overlaps(&ca.made.shape, at_a, &cb.made.shape, at_b);
}
# Gives a contact a manifold, each point beginning with the impulses of last
# step's point of the same features.
# @returns Whether it touches, within the speculative margin.
def space::update_contact(&mut this, k: u32, found: manifold): bool {
val c := &mut this.contacts[k as u64];
var normal: f32[4] = [0, 0, 0, 0];
var tangent: vec3[4];
for i in 0..found.count {
for j in 0..c.manifold.count {
if found.points[i].id == c.manifold.points[j].id {
normal[i] = c.normal_impulse[j];
tangent[i] = c.tangent_impulse[j];
}
}
}
c.manifold = found;
c.normal_impulse = normal;
c.tangent_impulse = tangent;
c.touching = found.count > 0;
c.seen = true;
return c.touching;
}
# Finds the triangles a shape meets of a mesh, a contact for each, keeping
# those it met last step and dropping those it no longer meets.
# @returns Whether any touches.
def space::update_mesh_contacts(&mut this, p: u32): bool {
val a := this.pairs[p as u64].a;
val b := this.pairs[p as u64].b;
# The mesh as the first, its normals from each triangle toward the shape,
# turned back where the shape is the pair's first.
val mesh_first := this.colliders[a as u64].is_mesh();
val m := mesh_first ? a : b;
val s := mesh_first ? b : a;
var met := move(this.met);
met.clear();
val held := &this.colliders[m as u64];
val shaped := &this.colliders[s as u64];
this.meshes[held.mesh as u64].collide(this.bodies[held.body as u64].at, &shaped.made.shape, this.bodies[shaped.body as u64].at, this.speculative, def(t: u32, found: manifold): bool {
# Triangles facing one way are met as one, their points together, as Jolt
# meets them, so a box resting across a seam is pushed as on one face,
# not one triangle's after the other's, which would edge it aside. Each
# point's id is mixed with its triangle, so points of two are told apart.
var made := mesh_first ? found : found.flipped();
val mixed := ((t as u64 * 0x9E3779B1) & 0xFFFFFFFF) as u32;
for i in 0..made.count {
made.points[i].id = made.points[i].id ^ mixed;
}
for k in 0..met.length {
if met[k].manifold.normal.dot(made.normal) > 0.999 {
merge_into(&mut met[k].manifold, &made);
return true;
}
}
met.append(met_triangle{ triangle = t, manifold = made });
return true;
});
var k := this.pairs[p as u64].contacts;
while k != none {
this.contacts[k as u64].seen = false;
k = this.contacts[k as u64].next;
}
var touching := false;
for i in 0..met.length {
var found := this.pairs[p as u64].contacts;
while found != none && this.contacts[found as u64].child != met[i].triangle {
found = this.contacts[found as u64].next;
}
if found == none {
found = this.make_contact(p, met[i].triangle);
this.pairs[p as u64].contacts = found;
}
if this.update_contact(found, met[i].manifold) {
touching = true;
}
}
this.met = move(met);
# Those not met this step are dropped.
var previous: u32 = none;
k = this.pairs[p as u64].contacts;
while k != none {
val next := this.contacts[k as u64].next;
if !this.contacts[k as u64].seen {
if previous == none {
this.pairs[p as u64].contacts = next;
} else {
this.contacts[previous as u64].next = next;
}
this.free_contact(k);
} else {
previous = k;
}
k = next;
}
return touching;
}
+509
View File
@@ -0,0 +1,509 @@
#! Contains `hull`, a convex polyhedron: its corners; its faces, each a convex
#! polygon of its corners, counterclockwise as it's seen from outside, its
#! normal facing out; and its edges, each between two faces. It's made as a box,
#! as a triangle, flat, with a face each way, or around places, as the least
#! hull holding them, each of its faces as many of their triangles as lie in one
#! plane.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
#! The most corners a hull has.
pub const max_hull_points: u32 = 32;
# The most faces and edges a hull of so many corners has, as Euler's formula
# bounds them: 2V - 4 faces and 3V - 6 edges, each edge a corner of two faces.
const max_hull_faces: u32 = 60;
const max_hull_edges: u32 = 90;
# Faces whose normals are nearer one another than this are one face.
const coplanar: f32 = 0.9999;
#! A convex polyhedron, about the origin of its body, as plain data, so a shape
#! holding one is copied whole.
pub struct hull {
var _count: u32;
var _faces: u32;
var _edges: u32;
var _points: vec3[32];
var _normals: vec3[60];
var _first: u8[60]; # Of each face, where its corners begin in `_corners`.
var _sizes: u8[60]; # Of each face, how many corners.
var _corners: u8[180]; # Each face's corners, counterclockwise from outside.
var _ends: u8[180]; # Each edge's two corners.
var _sides: u8[180]; # Each edge's two faces.
var _center: vec3;
}
#! A box reaching so far each way from its middle, about a place, turned by a
#! rotation.
pub def hull::box(half: vec3, center: vec3 = vec3::zero, turn: quat = quat::identity): hull {
var made := hull{ _count = 8, _faces = 6 };
val m := mat3::rotation(turn);
# Corner `i` is on the high side of x where bit 0 is set, of y where bit 1
# is, and of z where bit 2 is.
for i in 0..8u {
val corner := vec3{ (i & 1) != 0 ? half.x : -half.x, (i & 2) != 0 ? half.y : -half.y, (i & 4) != 0 ? half.z : -half.z };
made._points[i] = center + m * corner;
}
val loops: u8[24] = [1, 3, 7, 5, 0, 4, 6, 2, 2, 6, 7, 3, 0, 1, 5, 4, 4, 5, 7, 6, 0, 2, 3, 1];
for i in 0..24u {
made._corners[i] = loops[i];
}
for f in 0..6u {
made._first[f] = (f * 4) as u8;
made._sizes[f] = 4;
}
made.finish();
return made;
}
#! A triangle of three places, flat: a face each way, the first facing where
#! they turn counterclockwise, and three edges, each between the two faces.
pub def hull::triangle(a: vec3, b: vec3, c: vec3): hull {
var made := hull{ _count = 3, _faces = 2 };
made._points[0] = a;
made._points[1] = b;
made._points[2] = c;
val loops: u8[6] = [0, 1, 2, 0, 2, 1];
for i in 0..6u {
made._corners[i] = loops[i];
}
made._first[1] = 3;
made._sizes[0] = 3;
made._sizes[1] = 3;
made.finish();
return made;
}
# A triangle of the hull being made, by its corners' indices among the places.
struct building {
var a: u32;
var b: u32;
var c: u32;
var normal: vec3;
var offset: f32;
var alive: bool;
}
def building_of(places: span<vec3>, a: u32, b: u32, c: u32): building {
val normal := (places[b] - places[a]).cross(places[c] - places[a]).normalized();
return building{ a = a, b = b, c = c, normal = normal, offset = normal.dot(places[a]), alive = true };
}
# A place, and how far it is from the middle of the first four corners, by
# which the furthest are put on first.
struct by_reach {
var reach: f32;
var index: u32;
}
def further(x: &by_reach, y: &by_reach): bool {
return x.reach > y.reach;
}
#! The least convex hull holding places: what's within it, or on its faces,
#! left out. Nothing where the places hold no volume, or their hull has more
#! than `max_hull_points` corners.
pub def hull::of(places: span<vec3>): maybe<hull> {
return nothing{} if places.length < 4;
# How near a place is to a face to be taken as on it, of the places' size.
var low := places[0];
var high := places[0];
for i in 1..places.length {
low = low.min(places[i]);
high = high.max(places[i]);
}
val reach := low.abs().max(high.abs());
val near := (reach.x + reach.y + reach.z) * 4e-6 + tiny;
# The first four corners: the place furthest left, the one furthest from
# it, the one furthest from the line of those, and the one furthest from
# the plane of the three.
var i0: u32 = 0;
for i in 1..places.length {
if places[i].x < places[i0 as u64].x {
i0 = i as u32;
}
}
var i1 := i0;
var best: f32 = 0;
for i in 0..places.length {
val d := (places[i] - places[i0 as u64]).length;
if d > best {
best = d;
i1 = i as u32;
}
}
return nothing{} if best <= near;
val along := (places[i1 as u64] - places[i0 as u64]).normalized();
var i2 := i0;
best = 0;
for i in 0..places.length {
val d := (places[i] - places[i0 as u64]).cross(along).length;
if d > best {
best = d;
i2 = i as u32;
}
}
return nothing{} if best <= near;
val facing := (places[i1 as u64] - places[i0 as u64]).cross(places[i2 as u64] - places[i0 as u64]).normalized();
var i3 := i0;
best = 0;
var side: f32 = 0;
for i in 0..places.length {
val d := facing.dot(places[i] - places[i0 as u64]);
if math::abs(d) > best {
best = math::abs(d);
side = d;
i3 = i as u32;
}
}
return nothing{} if best <= near;
# The first face faces away from the fourth corner.
var a := i0;
var b := i1;
var c := i2;
if side > 0 {
b = i2;
c = i1;
}
var faces := vector::<building>::new();
faces.append(building_of(places, a, b, c));
faces.append(building_of(places, a, i3, b));
faces.append(building_of(places, b, i3, c));
faces.append(building_of(places, c, i3, a));
# The rest, the furthest from the middle first, each outside the hull so
# far replacing the faces it sees with faces from their horizon to it.
val middle := (places[i0 as u64] + places[i1 as u64] + places[i2 as u64] + places[i3 as u64]) * 0.25;
var order := vector::<by_reach>::new();
for i in 0..places.length {
order.append(by_reach{ reach = (places[i] - middle).length_squared, index = i as u32 });
}
order.sort_by(further);
var seen := vector::<u64>::new();
for k in 0..order.length {
val p := order[k].index;
val place := places[p as u64];
# The directed edges of the faces it sees.
seen.clear();
for f in 0..faces.length {
continue if !faces[f].alive || faces[f].normal.dot(place) - faces[f].offset <= near;
faces[f].alive = false;
seen.append(edge_key(faces[f].a, faces[f].b));
seen.append(edge_key(faces[f].b, faces[f].c));
seen.append(edge_key(faces[f].c, faces[f].a));
}
continue if seen.is_empty;
# An edge seen one way only is on the horizon.
val count := seen.length;
for e in 0..count {
val key := seen[e];
val from := (key >> 32) as u32;
val to := (key & 0xFFFFFFFF) as u32;
var shared := false;
for o in 0..count {
if seen[o] == edge_key(to, from) {
shared = true;
break;
}
}
if !shared {
faces.append(building_of(places, from, to, p));
}
}
}
return hull::of_triangles(places, faces.view());
}
def edge_key(from: u32, to: u32): u64 {
return ((from as u64) << 32) | to as u64;
}
# The hull of the triangles left: those in one plane made one face, the
# corners they use numbered from 0.
def hull::of_triangles(places: span<vec3>, faces: span<building>): maybe<hull> {
# Which triangle lies across each directed edge.
var across := dict::<u64, u64>::new();
var alive := vector::<u64>::new();
for f in 0..faces.length {
continue if !faces[f].alive;
alive.append(f);
across.set(edge_key(faces[f].a, faces[f].b), f);
across.set(edge_key(faces[f].b, faces[f].c), f);
across.set(edge_key(faces[f].c, faces[f].a), f);
}
# Each triangle's face: those reached from it across edges, facing as it
# does.
var group := vector::<i64>::new();
for f in 0..faces.length {
group.append(-1);
}
var made := hull{};
var numbered := dict::<u32, u32>::new();
var corners: u32 = 0;
var pending := vector::<u64>::new();
var edges := vector::<u64>::new();
var ring := dict::<u32, u32>::new();
for k in 0..alive.length {
val seed := alive[k];
# A triangle of no area takes the face of one beside it.
continue if group[seed] >= 0 || faces[seed].normal.length_squared < 0.25;
return nothing{} if made._faces >= max_hull_faces;
val face := made._faces;
val normal := faces[seed].normal;
group[seed] = face as i64;
pending.clear();
pending.append(seed);
edges.clear();
while !pending.is_empty {
val t := pending[pending.length - 1];
pending.truncate();
val keys: u64[3] = [edge_key(faces[t].a, faces[t].b), edge_key(faces[t].b, faces[t].c), edge_key(faces[t].c, faces[t].a)];
for e in 0..3u {
edges.append(keys[e]);
val reverse := edge_key((keys[e] & 0xFFFFFFFF) as u32, (keys[e] >> 32) as u32);
if across.get(&reverse) is some(&other) {
val o: u64 = other;
if group[o] < 0 && (faces[o].normal.dot(normal) > coplanar || faces[o].normal.length_squared < 0.25) {
group[o] = face as i64;
pending.append(o);
}
}
}
}
# The face's boundary: its triangles' edges whose reverse isn't among
# them, walked from one to the next.
ring.clear();
var start: u32 = 0;
var length: u32 = 0;
for e in 0..edges.length {
val from := (edges[e] >> 32) as u32;
val to := (edges[e] & 0xFFFFFFFF) as u32;
var inner := false;
for o in 0..edges.length {
if edges[o] == edge_key(to, from) {
inner = true;
break;
}
}
if !inner {
ring.set(from, to);
start = from;
length++;
}
}
val first := made.corner_total();
return nothing{} if first + length > max_hull_edges * 2;
var at := start;
var walked: u32 = 0;
var newell := vec3::zero;
while walked < length {
if numbered.get(&at) is none {
return nothing{} if corners >= max_hull_points;
made._points[corners] = places[at as u64];
numbered.set(at, corners);
corners++;
}
if numbered.get(&at) is some(&n) {
val number: u32 = n;
made._corners[first + walked] = number as u8;
}
var next := at;
if ring.get(&at) is some(&n) {
next = n;
} else {
return nothing{};
}
newell = newell + places[at as u64].cross(places[next as u64]);
at = next;
walked++;
break if at == start;
}
return nothing{} if walked != length || walked < 3;
made._first[face] = first as u8;
made._sizes[face] = walked as u8;
made._normals[face] = newell.normalized();
made._faces++;
}
made._count = corners;
return nothing{} if !made.find_edges();
made.find_center();
return made;
}
# How many corners its faces have in all.
def hull::corner_total(&this): u32 {
var total: u32 = 0;
for f in 0..this._faces {
total += this._sizes[f] as u32;
}
return total;
}
# Finds its normals, edges, and middle, of its corners and faces.
def hull::finish(&mut this): void {
for f in 0..this._faces {
var newell := vec3::zero;
for k in 0..this.face_size(f) {
newell = newell + this.point(this.corner(f, k)).cross(this.point(this.corner(f, (k + 1) % this.face_size(f))));
}
this._normals[f] = newell.normalized();
}
_ = this.find_edges();
this.find_center();
}
# Finds its edges, each once, and the two faces either side, of its faces'
# corners: an edge from a lesser corner to a greater in one face, and back in
# the other. Gives false where one isn't, as a hull with a hole.
def hull::find_edges(&mut this): bool {
this._edges = 0;
for f in 0..this._faces {
val size := this.face_size(f);
for k in 0..size {
val from := this.corner(f, k);
val to := this.corner(f, (k + 1) % size);
continue if from > to;
return false if this._edges >= max_hull_edges;
val e := this._edges;
this._ends[e * 2] = from as u8;
this._ends[e * 2 + 1] = to as u8;
this._sides[e * 2] = f as u8;
this._sides[e * 2 + 1] = 0xFF;
this._edges++;
}
}
for f in 0..this._faces {
val size := this.face_size(f);
for k in 0..size {
val from := this.corner(f, k);
val to := this.corner(f, (k + 1) % size);
continue if from < to;
for e in 0..this._edges {
if this._ends[e * 2] as u32 == to && this._ends[e * 2 + 1] as u32 == from {
this._sides[e * 2 + 1] = f as u8;
break;
}
}
}
}
for e in 0..this._edges {
return false if this._sides[e * 2 + 1] == 0xFF;
}
return true;
}
def hull::find_center(&mut this): void {
var sum := vec3::zero;
for i in 0..this._count {
sum = sum + this._points[i];
}
this._center = sum * (1 / this._count as f32);
}
#! How many corners it has.
pub val hull::count: u32 {
get => this._count;
}
#! A corner.
pub def hull::point(&this, i: u32): vec3 {
return this._points[i];
}
#! How many faces it has.
pub val hull::faces: u32 {
get => this._faces;
}
#! A face's normal, facing out.
pub def hull::normal(&this, face: u32): vec3 {
return this._normals[face];
}
#! How many corners a face has.
pub def hull::face_size(&this, face: u32): u32 {
return this._sizes[face] as u32;
}
#! Which corner is a face's `k`th, counterclockwise from outside.
pub def hull::corner(&this, face: u32, k: u32): u32 {
return this._corners[this._first[face] as u32 + k] as u32;
}
#! How far its plane is along a face's normal from the origin.
pub def hull::offset(&this, face: u32): f32 {
return this._normals[face].dot(this.point(this.corner(face, 0)));
}
#! How many edges it has.
pub val hull::edges: u32 {
get => this._edges;
}
#! An edge's corners, the lesser first.
pub def hull::edge(&this, e: u32): u32[2] {
return [this._ends[e * 2] as u32, this._ends[e * 2 + 1] as u32];
}
#! The faces either side of an edge.
pub def hull::edge_faces(&this, e: u32): u32[2] {
return [this._sides[e * 2] as u32, this._sides[e * 2 + 1] as u32];
}
#! The middle of its corners, which is within it.
pub val hull::center: vec3 {
get => this._center;
}
#! Whether it's flat, of two faces, as a triangle is.
pub val hull::is_flat: bool {
get => this._faces == 2;
}
#! The corner furthest along a direction.
pub def hull::support(&this, direction: vec3): u32 {
var found: u32 = 0;
var most := this._points[0].dot(direction);
for i in 1..this._count {
val d := this._points[i].dot(direction);
if d > most {
most = d;
found = i;
}
}
return found;
}
#! The hull scaled along each axis, as a transform scales what it holds: its
#! normals turned as the faces they're of are.
pub def hull::scaled(&this, by: vec3): hull {
var made: hull = this;
for i in 0..this._count {
made._points[i] = this._points[i] * by;
}
for f in 0..this._faces {
made._normals[f] = (this._normals[f] / by).normalized();
}
made._center = this._center * by;
return made;
}
#! The hull moved and turned as a pose places it.
pub def hull::moved(&this, by: pose): hull {
var made: hull = this;
val m := mat3::rotation(by.turn);
for i in 0..this._count {
made._points[i] = by.at + m * this._points[i];
}
for f in 0..this._faces {
made._normals[f] = m * this._normals[f];
}
made._center = by.at + m * this._center;
return made;
}
+314
View File
@@ -0,0 +1,314 @@
#! Contains how a step solves joints, as Box2D's soft step solves them: each
#! is prepared as the step begins, begins each substep with the impulses it
#! ended the last with, and pushes its bodies' velocities toward holding it,
#! undoing drift softly where `use_bias` asks.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
def space::prepare_joints(&mut this, s: &mut solver_scratch, h: f32): void {
s.joints.clear();
s.joint_soft = soft_of(this.joint_hertz, this.joint_damping, h);
for j in 0..this.joints.length {
continue if !this.joints[j].alive;
var r := this.joints[j];
val a := &this.bodies[r.body_a as u64];
val b := &this.bodies[r.body_b as u64];
continue if a.slot == 0 && b.slot == 0;
s.joints.append(j as u32);
r.slot_a = a.slot;
r.slot_b = b.slot;
r.ma = a.inv_mass;
r.mb = b.inv_mass;
r.qa = a.at.turn;
r.qb = b.at.turn;
r.ra = a.at.turn * (r.made.anchor_a - a.local_center);
r.rb = b.at.turn * (r.made.anchor_b - b.local_center);
r.delta_center = b.center - a.center;
val ia := s.inertias[a.slot as u64];
val ib := s.inertias[b.slot as u64];
if r.made.kind == joint_kind::distance {
r.axial_mass = mass_along((r.rb - r.ra + r.delta_center).normalized(), r.ra, r.rb, r.ma, r.mb, ia, ib);
} else {
# A hinge turns each body about its axis through the anchor, not about
# its center, as the point it's held at keeps it: how hard that is is its
# moment about the axis, and its mass as far from the axis as its center
# is, so a limit stops a door outright rather than leaving the point to
# turn it back.
val axis := r.qa * r.made.axis_a;
val k := about_hinge(a, axis, r.ra) + about_hinge(b, axis, r.rb);
r.axial_mass = k > 0 ? 1 / k : 0f;
}
r.spring_soft = soft_of(r.made.hertz, r.made.damping, h);
r.linear_soft = r.made.hertz == 0 ? s.joint_soft : soft_of(r.made.hertz, r.made.damping, h);
r.angular_soft = r.made.angular_hertz == 0 ? s.joint_soft : soft_of(r.made.angular_hertz, r.made.angular_damping, h);
this.joints[j] = r;
}
}
# How easily a body turns about an axis through a place `r` from its center:
# the inverse of its moment about it.
def about_hinge(b: &body_record, axis: vec3, r: vec3): f32 {
return 0 if b.inv_mass == 0 || b.fixed_rotation;
val turn := mat3::rotation(b.at.turn);
val inertia := turn * b.inertia * turn.transposed();
val across := r.length_squared - r.dot(axis) * r.dot(axis);
val moment := axis.dot(inertia * axis) + b.mass * across;
return moment > 0 ? 1 / moment : 0f;
}
# A hinge's axis as each body is turned now, and two directions across it.
struct hinge_axes {
var a1: vec3;
var a2: vec3;
var u1: vec3;
var u2: vec3;
}
def axes_of(r: &joint_record, sa: &body_state, sb: &body_state): hinge_axes {
val a1 := (sa.dq * r.qa).normalized() * r.made.axis_a;
val a2 := (sb.dq * r.qb).normalized() * r.made.axis_b;
val u1 := perpendicular_to(a1);
return hinge_axes{ a1 = a1, a2 = a2, u1 = u1, u2 = a1.cross(u1) };
}
def space::warm_joints(&mut this, s: &mut solver_scratch): void {
for i in 0..s.joints.length {
val r := &this.joints[s.joints[i] as u64];
var sa := s.states[r.slot_a as u64];
var sb := s.states[r.slot_b as u64];
val ia := s.inertias[r.slot_a as u64];
val ib := s.inertias[r.slot_b as u64];
val ra := sa.dq * r.ra;
val rb := sb.dq * r.rb;
var p := r.linear;
var turn := vec3::zero;
if r.made.kind == joint_kind::hinge {
val axes := axes_of(r, &sa, &sb);
turn = axes.u1 * r.angular.x + axes.u2 * r.angular.y + axes.a1 * (r.spring_impulse + r.motor_impulse + r.lower_impulse - r.upper_impulse);
} else if r.made.kind == joint_kind::fixed {
turn = r.angular;
} else if r.made.kind == joint_kind::distance {
val axis := ((sb.dp - sa.dp) + r.delta_center + (rb - ra)).normalized();
p = axis * (r.axial + r.spring_impulse + r.lower_impulse - r.upper_impulse + r.motor_impulse);
}
sa.v = sa.v - p * r.ma;
sa.w = sa.w - ia * (ra.cross(p) + turn);
sb.v = sb.v + p * r.mb;
sb.w = sb.w + ib * (rb.cross(p) + turn);
s.states[r.slot_a as u64] = sa;
s.states[r.slot_b as u64] = sb;
}
}
def space::solve_joints(&mut this, s: &mut solver_scratch, h: f32, use_bias: bool): void {
for i in 0..s.joints.length {
val j := s.joints[i] as u64;
var r := this.joints[j];
var sa := s.states[r.slot_a as u64];
var sb := s.states[r.slot_b as u64];
val ia := s.inertias[r.slot_a as u64];
val ib := s.inertias[r.slot_b as u64];
if r.made.kind == joint_kind::ball {
solve_point(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, use_bias);
} else if r.made.kind == joint_kind::hinge {
solve_hinge(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias);
solve_point(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, use_bias);
} else if r.made.kind == joint_kind::fixed {
solve_fixed_turn(&mut r, &mut sa, &mut sb, ia, ib, use_bias);
solve_point(&mut r, &mut sa, &mut sb, ia, ib, &r.linear_soft, use_bias || r.made.hertz > 0);
} else {
solve_distance(&mut r, &mut sa, &mut sb, ia, ib, &s.joint_soft, h, use_bias);
}
this.joints[j] = r;
s.states[r.slot_a as u64] = sa;
s.states[r.slot_b as u64] = sb;
}
}
# The matrix taking a vector to `r`'s cross product with it.
def skew(r: vec3): mat3 {
return mat3{ vec3{ 0, r.z, -r.y }, vec3{ -r.z, 0, r.x }, vec3{ r.y, -r.x, 0 } };
}
# Turns the two apart by an angular impulse.
def turn_apart(sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, impulse: vec3): void {
sa.w = sa.w - ia * impulse;
sb.w = sb.w + ib * impulse;
}
# Pushes the two apart by an impulse at their anchors.
def push_apart(r: &joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, ra: vec3, rb: vec3, p: vec3): void {
sa.v = sa.v - p * r.ma;
sa.w = sa.w - ia * ra.cross(p);
sb.v = sb.v + p * r.mb;
sb.w = sb.w + ib * rb.cross(p);
}
# A one-sided limit's impulse, as a contact's: of `c` how far it is from
# closing, and `cdot` how fast it closes.
def limit_impulse(c: f32, cdot: f32, mass: f32, held: f32, soft: &softness, inv_h: f32, use_bias: bool): f32 {
var bias: f32 = 0;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if c > 0 {
bias = c * inv_h;
} else if use_bias {
bias = soft.bias_rate * c;
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
val impulse := -mass * mass_scale * (cdot + bias) - impulse_scale * held;
return math::max(held + impulse, 0f) - held;
}
# Holds two anchors at one point.
def solve_point(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, use_bias: bool): void {
val ra := sa.dq * r.ra;
val rb := sb.dq * r.rb;
val cdot := sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra);
var bias := vec3::zero;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias {
bias = ((sb.dp - sa.dp) + (rb - ra) + r.delta_center) * soft.bias_rate;
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
val sa_skew := skew(ra);
val sb_skew := skew(rb);
val k := sa_skew * ia * sa_skew.transposed() + sb_skew * ib * sb_skew.transposed()
+ mat3{ vec3{ r.ma + r.mb, 0, 0 }, vec3{ 0, r.ma + r.mb, 0 }, vec3{ 0, 0, r.ma + r.mb } };
return if k.determinant == 0;
val impulse := (k.inverse() * (cdot + bias)) * -mass_scale - r.linear * impulse_scale;
r.linear = r.linear + impulse;
push_apart(r, sa, sb, ia, ib, ra, rb, impulse);
}
# Holds a hinge's axes together, and turns it by its spring, its motor, and
# its limits.
def solve_hinge(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void {
val made := &r.made;
val axes := axes_of(r, sa, sb);
if made.spring || made.motor || made.limit {
val angle := hinge_angle(made, (sa.dq * r.qa).normalized(), (sb.dq * r.qb).normalized());
if made.spring && made.hertz > 0 {
val bias := r.spring_soft.bias_rate * angle;
val impulse := -r.spring_soft.mass_scale * r.axial_mass * ((sb.w - sa.w).dot(axes.a1) + bias) - r.spring_soft.impulse_scale * r.spring_impulse;
r.spring_impulse += impulse;
turn_apart(sa, sb, ia, ib, axes.a1 * impulse);
}
if made.motor {
val most := h * made.max_motor_force;
val held := r.motor_impulse;
r.motor_impulse = math::clamp(held - r.axial_mass * ((sb.w - sa.w).dot(axes.a1) - made.motor_speed), -most, most);
turn_apart(sa, sb, ia, ib, axes.a1 * (r.motor_impulse - held));
}
if made.limit {
val lower := limit_impulse(angle - made.lower, (sb.w - sa.w).dot(axes.a1), r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias);
r.lower_impulse += lower;
turn_apart(sa, sb, ia, ib, axes.a1 * lower);
val upper := limit_impulse(made.upper - angle, (sa.w - sb.w).dot(axes.a1), r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias);
r.upper_impulse += upper;
turn_apart(sa, sb, ia, ib, axes.a1 * -upper);
}
}
# The axes held together: no turning across them, and what they've drifted
# apart undone.
val both := ia + ib;
val k11 := axes.u1.dot(both * axes.u1);
val k12 := axes.u1.dot(both * axes.u2);
val k22 := axes.u2.dot(both * axes.u2);
val turning := sb.w - sa.w;
var cx := turning.dot(axes.u1);
var cy := turning.dot(axes.u2);
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias {
val drift := axes.a1.cross(axes.a2);
cx += soft.bias_rate * drift.dot(axes.u1);
cy += soft.bias_rate * drift.dot(axes.u2);
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
var det := k11 * k22 - k12 * k12;
return if det == 0;
det = 1 / det;
val ix := -mass_scale * det * (k22 * cx - k12 * cy) - impulse_scale * r.angular.x;
val iy := -mass_scale * det * (k11 * cy - k12 * cx) - impulse_scale * r.angular.y;
r.angular = vec3{ r.angular.x + ix, r.angular.y + iy, 0 };
turn_apart(sa, sb, ia, ib, axes.u1 * ix + axes.u2 * iy);
}
# Holds a fixed joint's turn: `b` turned within `a` as it rests.
def solve_fixed_turn(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, use_bias: bool): void {
val turning := sb.w - sa.w;
var bias := vec3::zero;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias || r.made.angular_hertz > 0 {
val target := (sa.dq * r.qa).normalized() * r.made.reference;
var off := ((sb.dq * r.qb).normalized() * target.inverse()).normalized();
if off.w < 0 {
off = quat{ -off.x, -off.y, -off.z, -off.w };
}
bias = vec3{ 2 * off.x, 2 * off.y, 2 * off.z } * r.angular_soft.bias_rate;
mass_scale = r.angular_soft.mass_scale;
impulse_scale = r.angular_soft.impulse_scale;
}
val k := ia + ib;
return if k.determinant == 0;
val impulse := (k.inverse() * (turning + bias)) * -mass_scale - r.angular * impulse_scale;
r.angular = r.angular + impulse;
turn_apart(sa, sb, ia, ib, impulse);
}
def solve_distance(r: &mut joint_record, sa: &mut body_state, sb: &mut body_state, ia: mat3, ib: mat3, soft: &softness, h: f32, use_bias: bool): void {
val made := &r.made;
val ra := sa.dq * r.ra;
val rb := sb.dq * r.rb;
val d := (sb.dp - sa.dp) + r.delta_center + (rb - ra);
val length := d.length;
val axis := d.normalized();
if made.spring && (!made.limit || made.lower < made.upper) {
if made.hertz > 0 {
val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
val bias := r.spring_soft.bias_rate * (length - made.length);
val impulse := -r.spring_soft.mass_scale * r.axial_mass * (cdot + bias) - r.spring_soft.impulse_scale * r.spring_impulse;
r.spring_impulse += impulse;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * impulse);
}
} else {
val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
var bias: f32 = 0;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if use_bias {
bias = soft.bias_rate * (length - made.length);
mass_scale = soft.mass_scale;
impulse_scale = soft.impulse_scale;
}
val impulse := -mass_scale * r.axial_mass * (cdot + bias) - impulse_scale * r.axial;
r.axial += impulse;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * impulse);
}
if made.limit && made.lower < made.upper {
val closing := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
val lower := limit_impulse(length - made.lower, closing, r.axial_mass, r.lower_impulse, soft, 1 / h, use_bias);
r.lower_impulse += lower;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * lower);
val opening := axis.dot(sa.v + sa.w.cross(ra) - sb.v - sb.w.cross(rb));
val upper := limit_impulse(made.upper - length, opening, r.axial_mass, r.upper_impulse, soft, 1 / h, use_bias);
r.upper_impulse += upper;
push_apart(r, sa, sb, ia, ib, ra, rb, axis * -upper);
}
if made.motor {
val most := h * made.max_motor_force;
val held := r.motor_impulse;
val cdot := axis.dot(sb.v + sb.w.cross(rb) - sa.v - sa.w.cross(ra));
r.motor_impulse = math::clamp(held + r.axial_mass * (made.motor_speed - cdot), -most, most);
push_apart(r, sa, sb, ia, ib, ra, rb, axis * (r.motor_impulse - held));
}
}
+317
View File
@@ -0,0 +1,317 @@
#! Contains joints, which hold two bodies together: a `ball` joint holds them
#! at a point they turn about every way, as a shoulder; 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; and a `distance` joint keeps two points apart, rigidly
#! as a rod, within lengths as a rope, or springily.
#!
#! 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,
}
#! 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 or a fixed joint, how `b` is turned within `a`'s own turn,
#! where it rests.
pub var reference := quat::identity;
#! 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;
}
#! 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(),
});
}
#! 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.
pub def space::change(&mut this, id: joint_id, made: joint): void {
return if !this.has(id);
val j := id.index as u64;
val a := this.joints[j].made.a;
val b := this.joints[j].made.b;
this.joints[j].made = made;
this.joints[j].made.a = a;
this.joints[j].made.b = b;
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);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
#! Contains `mass_data`: how heavy a shape is of a density, where its mass is
#! centered, and how hard it is to turn about each axis, its inertia tensor,
#! as a body's colliders sum to it.
import std::math;
import malunal::linear;
module malunal::physics3d;
#! How heavy something is, where its mass is centered, of its body's own
#! places, and its inertia tensor about that center, of the body's own axes.
pub struct mass_data {
pub var mass: f32;
pub var center: vec3;
pub var inertia: mat3;
}
#! It and another together: their masses summed about their joint center.
pub def mass_data::add(&this, other: &mass_data): mass_data {
val mass := this.mass + other.mass;
return mass_data{ inertia = this.inertia + other.inertia } if mass <= 0;
val center := (this.center * this.mass + other.center * other.mass) * (1 / mass);
val inertia := this.inertia + shifted(this.mass, this.center - center) + other.inertia + shifted(other.mass, other.center - center);
return mass_data{ mass = mass, center = center, inertia = inertia };
}
# What a mass adds to an inertia tensor, turning about a center as far off as
# `d`, as the parallel axis theorem finds.
def shifted(mass: f32, d: vec3): mat3 {
val dd := d.dot(d);
return mat3{
vec3{ mass * (dd - d.x * d.x), -mass * d.x * d.y, -mass * d.x * d.z },
vec3{ -mass * d.y * d.x, mass * (dd - d.y * d.y), -mass * d.y * d.z },
vec3{ -mass * d.z * d.x, -mass * d.z * d.y, mass * (dd - d.z * d.z) },
};
}
# A tensor of `across` about every axis but `along` about the axis `u`.
def about_axis(across: f32, along: f32, u: vec3): mat3 {
val k := along - across;
return mat3{
vec3{ across + k * u.x * u.x, k * u.x * u.y, k * u.x * u.z },
vec3{ k * u.y * u.x, across + k * u.y * u.y, k * u.y * u.z },
vec3{ k * u.z * u.x, k * u.z * u.y, across + k * u.z * u.z },
};
}
#! Its mass of a density, a mass for each volume of 1.
pub def shape::mass(&this, density: f32): mass_data {
val pi := math::pi as f32;
val r := this.radius;
if this.kind == shape_kind::sphere {
val mass := density * 4f / 3f * pi * r * r * r;
val i := 0.4 * mass * r * r;
return mass_data{ mass = mass, center = this.a, inertia = about_axis(i, i, vec3::up) };
}
if this.kind == shape_kind::capsule {
# A cylinder between its ends, and a sphere of its two round halves, each
# half's own center 3r/8 past the cylinder's end.
val length := (this.b - this.a).length;
val cylinder := density * pi * r * r * length;
val ball := density * 4f / 3f * pi * r * r * r;
val along := cylinder * r * r * 0.5 + ball * 0.4 * r * r;
val across := cylinder * (length * length / 12 + r * r / 4) + ball * (0.4 * r * r + length * length / 4 + 3 * length * r / 8);
return mass_data{ mass = cylinder + ball, center = (this.a + this.b) * 0.5, inertia = about_axis(across, along, (this.b - this.a).normalized()) };
}
return hull_mass(this.as_hull(), density);
}
# A hull's, as the tetrahedra of each face's triangles and a place within it
# sum it.
def hull_mass(h: &hull, density: f32): mass_data {
val origin := h.center;
var volume: f32 = 0;
var center := vec3::zero;
# The covariance of the hull's places about the origin.
var xx: f32 = 0;
var yy: f32 = 0;
var zz: f32 = 0;
var xy: f32 = 0;
var xz: f32 = 0;
var yz: f32 = 0;
for f in 0..h.faces {
val a := h.point(h.corner(f, 0)) - origin;
for k in 1..h.face_size(f) - 1 {
val b := h.point(h.corner(f, k)) - origin;
val c := h.point(h.corner(f, k + 1)) - origin;
val det := a.dot(b.cross(c));
volume += det / 6;
center = center + (a + b + c) * (det / 24);
val s := a + b + c;
val w := det / 120;
xx += w * (a.x * a.x + b.x * b.x + c.x * c.x + s.x * s.x);
yy += w * (a.y * a.y + b.y * b.y + c.y * c.y + s.y * s.y);
zz += w * (a.z * a.z + b.z * b.z + c.z * c.z + s.z * s.z);
xy += w * (a.x * a.y + b.x * b.y + c.x * c.y + s.x * s.y);
xz += w * (a.x * a.z + b.x * b.z + c.x * c.z + s.x * s.z);
yz += w * (a.y * a.z + b.y * b.z + c.y * c.z + s.y * s.z);
}
}
return mass_data{} if volume <= tiny;
center = center * (1 / volume);
val mass := density * volume;
# Of the covariance about the center of mass, the tensor.
xx = density * xx - mass * center.x * center.x;
yy = density * yy - mass * center.y * center.y;
zz = density * zz - mass * center.z * center.z;
xy = density * xy - mass * center.x * center.y;
xz = density * xz - mass * center.x * center.z;
yz = density * yz - mass * center.y * center.z;
val inertia := mat3{
vec3{ yy + zz, -xy, -xz },
vec3{ -xy, xx + zz, -yz },
vec3{ -xz, -yz, xx + yy },
};
return mass_data{ mass = mass, center = origin + center, inertia = inertia };
}
+281
View File
@@ -0,0 +1,281 @@
#! Contains `triangle_mesh`, the triangles of a surface, as a level's ground and
#! walls are: kept in a tree of their boxes, and met a triangle at a time by
#! shapes and rays.
#!
#! A shape meeting a triangle by an edge or a corner is pushed out as the
#! triangle's face pushes it, where that edge is one two triangles share flat,
#! or hollow, as a floor's seams and a room's corners are, as Jolt's active
#! edges keep: so a body slides along a floor of many triangles as along one,
#! never caught on the seams between them. An edge two triangles share at a
#! ridge, turning more than 5 degrees, and an edge of one triangle alone, push
#! as they meet.
import std::containers;
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
# Two triangles sharing an edge turning less than this, the cosine of 5
# degrees, are as one.
const ridge: f32 = 0.9962;
#! The triangles of a surface, of places of its own, as a pose places it.
pub struct triangle_mesh {
var _points: vector<vec3>;
var _indices: vector<u32>;
var _normals: vector<vec3>;
var _active: vector<u8>; # Of each triangle, bit `k` where edge `k`, from corner `k` to the next, pushes as it meets.
var _tree: aabb_tree;
}
#! Where a ray met a mesh: how far along it, where, which way the triangle it
#! met faces, toward the ray's beginning, and which triangle.
pub struct mesh_hit {
pub var distance: f32;
pub var point: vec3;
pub var normal: vec3;
pub var triangle: u32;
}
# An edge, and the triangles using it, each as its index times 3 and the
# edge's place in it.
struct edge_use {
var first: u64;
var second: u64;
var count: u32;
}
#! The mesh of places and triangles of them, three indices each,
#! counterclockwise as their front is seen: those of no area, or of an index
#! past the places, left out.
pub def triangle_mesh::new(points: span<vec3>, indices: span<u32>): triangle_mesh {
var made := triangle_mesh{
_points = vector::<vec3>::new(), _indices = vector::<u32>::new(), _normals = vector::<vec3>::new(),
_active = vector::<u8>::new(), _tree = aabb_tree::new(0),
};
made._points.extend(points);
var t: u64 = 0;
while t + 2 < indices.length {
val a := indices[t];
val b := indices[t + 1];
val c := indices[t + 2];
t += 3;
continue if a as u64 >= points.length || b as u64 >= points.length || c as u64 >= points.length;
val facing := (points[b as u64] - points[a as u64]).cross(points[c as u64] - points[a as u64]);
continue if facing.length_squared <= tiny * tiny;
made._indices.append(a);
made._indices.append(b);
made._indices.append(c);
made._normals.append(facing.normalized());
made._active.append(7);
}
made.find_edges();
for i in 0..made._normals.length {
val c := made.triangle(i as u32);
_ = made._tree.insert(bounds{ c[0].min(c[1]).min(c[2]), c[0].max(c[1]).max(c[2]) }, i);
}
return made;
}
# Finds which edges push as they meet: those two triangles share, turning
# less than 5 degrees or hollow, don't.
def triangle_mesh::find_edges(&mut this): void {
var uses := vector::<edge_use>::new();
var found := dict::<u64, u64>::new();
for t in 0..this._normals.length {
for k in 0..3u {
val from := this._indices[t * 3 + k];
val to := this._indices[t * 3 + (k + 1) % 3];
val key := ((math::min(from, to) as u64) << 32) | math::max(from, to) as u64;
if found.get(&key) is some(&at) {
val index: u64 = at;
if uses[index].count == 1 {
uses[index].second = t * 3 + k;
}
uses[index].count++;
} else {
found.set(key, uses.length);
uses.append(edge_use{ first = t * 3 + k, count = 1 });
}
}
}
for i in 0..uses.length {
continue if uses[i].count != 2;
val t1 := uses[i].first / 3;
val k1 := uses[i].first % 3;
val t2 := uses[i].second / 3;
val k2 := uses[i].second % 3;
val n1 := this._normals[t1];
val n2 := this._normals[t2];
# The corner of the second triangle off the edge, below the first's plane
# where the edge is a ridge.
val off := this._points[this._indices[t2 * 3 + (k2 + 2) % 3] as u64];
val on := this._points[this._indices[t1 * 3 + k1] as u64];
val ridged := n1.dot(off - on) < 0 && n1.dot(n2) < ridge;
continue if ridged;
this._active[t1] = without_bit(this._active[t1], k1);
this._active[t2] = without_bit(this._active[t2], k2);
}
}
# Bits of three edges, but one.
def without_bit(bits: u8, k: u64): u8 {
val bit: u32 = 1;
return ((bits as u32) & (7 - (bit << k as u32))) as u8;
}
#! How many triangles it has.
pub val triangle_mesh::length: u64 {
get => this._normals.length;
}
#! A triangle's corners.
pub def triangle_mesh::triangle(&this, t: u32): vec3[3] {
val at := t as u64 * 3;
return [
this._points[this._indices[at] as u64], this._points[this._indices[at + 1] as u64], this._points[this._indices[at + 2] as u64],
];
}
#! The way a triangle's front faces.
pub def triangle_mesh::normal(&this, t: u32): vec3 {
return this._normals[t as u64];
}
#! Whether a triangle's edge `k`, from its corner `k` to the next, pushes as it
#! meets a shape, rather than as the triangle's face.
pub def triangle_mesh::is_active(&this, t: u32, k: u32): bool {
return (this._active[t as u64] & (1 << k) as u8) != 0;
}
#! The box holding it, of its own places.
pub def triangle_mesh::bounds(&this): bounds {
var made := bounds::empty;
for i in 0..this._points.length {
made = made.including(this._points[i]);
}
return made;
}
#! Visits the manifold of a shape against each triangle it meets, as
#! `visit(triangle, m)`, until it gives false: `at` places the mesh, and `at_s`
#! the shape, and each manifold's normal is from the triangle toward the shape,
#! in space. Within a `margin`, as `collide` gives them, triangles apart are
#! visited too.
pub def triangle_mesh::collide<F>(&this, at: pose, s: &shape, at_s: pose, margin: f32, visit: F): void
where F: invokable<def(u32, manifold): bool> {
val local := at.unapply_pose(at_s);
this._tree.query(grown(s.bounds(local), margin), def(leaf: u32, data: u64): bool {
val c := this.triangle(data as u32);
val face := shape::of_hull(hull::triangle(c[0], c[1], c[2]));
val found := collide(&face, pose::identity, s, local, margin) else { return true; };
return visit(data as u32, placed(this.faced(data, found, s.radius), &at));
});
}
#! Whether a shape meets any triangle, `at` placing the mesh and `at_s` the
#! shape.
pub def triangle_mesh::overlaps(&this, at: pose, s: &shape, at_s: pose): bool {
var met := false;
this.collide(at, s, at_s, 0, def(t: u32, m: manifold): bool {
met = true;
return false;
});
return met;
}
# A manifold of a triangle, as its face pushes where it met an edge, or a
# corner, of the triangle that doesn't push: its normal the face's, and each
# point as deep below the face's plane as the shape is there, of a radius
# around its core.
def triangle_mesh::faced(&this, t: u64, met: manifold, radius: f32): manifold {
val n := this._normals[t];
val along := met.normal.dot(n);
return met if math::abs(along) > 0.9998 || this._active[t] == 7;
var deepest: u32 = 0;
for i in 1..met.count {
if met.points[i].depth > met.points[deepest].depth {
deepest = i;
}
}
# Where the deepest point is on the triangle: half its depth along the
# normal from midway.
val c := this.triangle(t as u32);
val on := met.points[deepest].point + met.normal * (met.points[deepest].depth * 0.5);
val region := region_of(on, c[0], c[1], c[2]);
# Within the face, or by a corner or edge that pushes, it pushes as it met.
return met if region == 6;
if region >= 3 {
return met if this.is_active(t as u32, region - 3);
} else if this.is_active(t as u32, region) || this.is_active(t as u32, (region + 2) % 3) {
return met;
}
# Each point's place on the shape's surface, half its depth back along the
# normal, and its core within; then the shape's deepest there along the
# face's normal.
val facing := along >= 0 ? n : -n;
var made := met;
made.normal = facing;
for i in 0..met.count {
val surface := met.points[i].point - met.normal * (met.points[i].depth * 0.5);
val deepest := surface + met.normal * radius - facing * radius;
val depth := facing.dot(c[0] - deepest);
made.points[i].point = deepest + facing * (depth * 0.5);
made.points[i].depth = depth;
}
return made;
}
# Which part of a triangle a place on it is on, within a ten-thousandth of
# its longest edge: a corner, 0 to 2; an edge, 3 to 5, of edge `k` from corner
# `k` to the next; or within its face, 6.
def region_of(p: vec3, a: vec3, b: vec3, c: vec3): u32 {
val corners: vec3[3] = [a, b, c];
val longest := math::max((b - a).length, math::max((c - b).length, (a - c).length));
val near := longest * 1e-4 + tiny;
for k in 0..3u {
return k as u32 if (p - corners[k]).length <= near;
}
for k in 0..3u {
return (3 + k) as u32 if (p - nearest_on_segment(p, corners[k], corners[(k + 1) % 3])).length <= near;
}
return 6;
}
#! Where a ray first meets a triangle, `at` placing the mesh: from a place,
#! along a direction of length 1, as far as `reach`, from either side.
pub def triangle_mesh::ray_cast(&this, at: pose, origin: vec3, direction: vec3, reach: f32): maybe<mesh_hit> {
val o := at.unapply(origin);
val d := at.unrotate(direction);
var best: maybe<mesh_hit> = nothing{};
this._tree.ray_cast(o, d, reach, def(leaf: u32, data: u64, so_far: f32): f32 {
val c := this.triangle(data as u32);
val t := ray_triangle(o, d, c[0], c[1], c[2]) else { return so_far; };
return so_far if t > so_far;
val n := this._normals[data];
best = mesh_hit{ distance = t, point = at.apply(o + d * t), normal = at.rotate(n.dot(d) <= 0 ? n : -n), triangle = data as u32 };
return math::max(t, tiny);
});
return best;
}
# How far along a ray it meets a triangle, from either side, as Möller and
# Trumbore find it.
def ray_triangle(o: vec3, d: vec3, a: vec3, b: vec3, c: vec3): maybe<f32> {
val e1 := b - a;
val e2 := c - a;
val p := d.cross(e2);
val det := e1.dot(p);
return nothing{} if math::abs(det) < 1e-12;
val inverse := 1 / det;
val s := o - a;
val u := s.dot(p) * inverse;
return nothing{} if u < 0 || u > 1;
val q := s.cross(e1);
val v := d.dot(q) * inverse;
return nothing{} if v < 0 || u + v > 1;
val t := e2.dot(q) * inverse;
return nothing{} if t < 0;
return t;
}
+83
View File
@@ -0,0 +1,83 @@
#! Contains `physics3d`: what collides and moves in space, as a game of three
#! dimensions asks it. Shapes, spheres, capsules, and convex hulls, boxes among
#! them, each about the origin of its body and placed by a `pose`; whether two
#! meet, and the `manifold` of where and how deep, which way to push them
#! apart; where a ray first meets one; an `aabb_tree` of many, which finds those
#! near a box or along a ray without passing over the rest; and a
#! `triangle_mesh`, as a level's ground and walls are, met a triangle at a
#! time, but for the edges two triangles share flat or hollow, so a body slides
#! along a floor of many triangles as along one.
#!
#! And a `space` of bodies, as `physics2d`'s in a plane: each made of
#! colliders, of shapes or a triangle mesh, pulled by gravity, pushed by forces
#! and by what it meets, held to others by joints, and stepped forward in time
#! as Box2D's soft step solves it, sleeping where it and all it rests on are
#! still.
#!
#! Space is `linear`'s: right-handed, y up, and rotations as quaternions. A
#! hull's faces are counterclockwise as they're seen from outside, each normal
#! facing out. A shape's surface is within it, so two shapes touching meet, at a
#! depth of 0.
import std::math;
import malunal::linear;
module malunal::physics3d;
# How near two numbers are taken as one, as lengths in a game's units are.
const tiny: f32 = 1e-6;
# How far a feature may be past another and still be taken as as good, so the
# same pair gives the same face from one frame to the next.
const tolerance: f32 = 1e-3;
# The point of a segment nearest a place.
def nearest_on_segment(p: vec3, a: vec3, b: vec3): vec3 {
val e := b - a;
val length_squared := e.dot(e);
return a if length_squared <= tiny * tiny;
val t := math::clamp((p - a).dot(e) / length_squared, 0f, 1f);
return a + e * t;
}
# The points of two segments nearest one another: on `a1`-`a2` first, then on
# `b1`-`b2`, as Ericson's Real-Time Collision Detection finds them.
def nearest_of_segments(a1: vec3, a2: vec3, b1: vec3, b2: vec3): vec3[2] {
val d1 := a2 - a1;
val d2 := b2 - b1;
val r := a1 - b1;
val a := d1.dot(d1);
val e := d2.dot(d2);
val f := d2.dot(r);
var s: f32 = 0;
var t: f32 = 0;
if a <= tiny && e <= tiny {
return [a1, b1];
}
if a <= tiny {
t = math::clamp(f / e, 0f, 1f);
} else {
val c := d1.dot(r);
if e <= tiny {
s = math::clamp(-c / a, 0f, 1f);
} else {
val b := d1.dot(d2);
val denominator := a * e - b * b;
s = denominator > tiny ? math::clamp((b * f - c * e) / denominator, 0f, 1f) : 0;
t = (b * s + f) / e;
if t < 0 {
t = 0;
s = math::clamp(-c / a, 0f, 1f);
} else if t > 1 {
t = 1;
s = math::clamp((b - c) / a, 0f, 1f);
}
}
}
return [a1 + d1 * s, b1 + d2 * t];
}
# A direction at right angles to another, of length 1.
def perpendicular_to(v: vec3): vec3 {
val other := math::abs(v.x) < 0.57 ? vec3::right : vec3::up;
return v.cross(other).normalized();
}
+65
View File
@@ -0,0 +1,65 @@
#! Contains `pose`, where a body is in space and which way it's turned, which
#! places its shapes.
import std::serial;
import malunal::linear;
module malunal::physics3d;
#! Where a body is in space, and which way it's turned: what a place of its own,
#! as its shapes' corners are, is in space.
@serial
pub struct pose {
@serial pub var at: vec3;
@serial pub var turn := quat::identity;
}
#! At the origin, unturned.
pub val pose::identity := pose{};
#! A pose at a place, turned by a rotation.
pub def pose::of(at: vec3, turn: quat = quat::identity): pose {
return pose{ at = at, turn = turn };
}
pub def pose::equals(&this, other: &pose): bool {
return this.at == other.at && this.turn == other.turn;
}
#! Where a place of the body's own is in space.
pub def pose::apply(&this, local: vec3): vec3 {
return this.at + this.turn * local;
}
#! Where a place of space is in the body's own.
pub def pose::unapply(&this, place: vec3): vec3 {
return this.turn.inverse() * (place - this.at);
}
#! A direction of the body's own, turned as it's turned.
pub def pose::rotate(&this, direction: vec3): vec3 {
return this.turn * direction;
}
#! A direction of space, as the body's own.
pub def pose::unrotate(&this, direction: vec3): vec3 {
return this.turn.inverse() * direction;
}
#! It after another: the pose of what's placed by `other` within what this
#! places.
pub def pose::mul(&this, other: &pose): pose {
return pose{ at = this.apply(other.at), turn = (this.turn * other.turn).normalized() };
}
#! The pose undoing it: a place it puts somewhere, put back.
pub def pose::inverse(&this): pose {
val back := this.turn.inverse();
return pose{ at = back * -this.at, turn = back };
}
#! Another pose of space, as one within what this places, of its own places:
#! what `this * found` is `other` of.
pub def pose::unapply_pose(&this, other: pose): pose {
val back := this.turn.inverse();
return pose{ at = back * (other.at - this.at), turn = (back * other.turn).normalized() };
}
+246
View File
@@ -0,0 +1,246 @@
#! Contains `shape`: a sphere, a capsule, or a convex hull, about the origin of
#! its body; the box holding it where a pose places it; whether it holds a
#! place; and where a ray first meets it.
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! What a shape is.
pub enum shape_kind: u8 {
#! The places within its radius of its middle.
sphere,
#! The places within its radius of a segment, between its two ends, as a
#! pill.
capsule,
#! A convex polyhedron, as a box.
hull,
}
#! A shape of a body, about the body's origin, as a pose places it: a sphere,
#! a capsule, or a convex hull. A sphere is its middle and a radius around it,
#! a capsule its two ends and a radius around the segment between them, and a
#! hull its corners and faces.
pub struct shape {
var _kind: shape_kind;
var _radius: f32;
var _a: vec3;
var _b: vec3;
var _hull: hull;
}
#! Where a ray met a shape: how far along it, where, and which way the shape
#! faces there.
pub struct ray_hit {
pub var distance: f32;
pub var point: vec3;
pub var normal: vec3;
}
#! A sphere of a radius, about a middle, the body's origin at first.
pub def shape::sphere(radius: f32, center: vec3 = vec3::zero): shape {
return shape{ _kind = shape_kind::sphere, _radius = radius, _a = center, _b = center };
}
#! A capsule of a radius about the segment between two places: a sphere of the
#! radius, where they're one place.
pub def shape::capsule(a: vec3, b: vec3, radius: f32): shape {
return shape::sphere(radius, a) if (b - a).length_squared <= tiny * tiny;
return shape{ _kind = shape_kind::capsule, _radius = radius, _a = a, _b = b };
}
#! A capsule standing up, along y, as a character's body: so wide and so high
#! in all, its ends round, about a middle. Narrower than it's high, or a
#! sphere.
pub def shape::pill(width: f32, height: f32, center: vec3 = vec3::zero): shape {
val radius := width / 2;
val reach := math::max(height / 2 - radius, 0f);
return shape::capsule(center - vec3{ 0, reach, 0 }, center + vec3{ 0, reach, 0 }, radius);
}
#! A box reaching so far each way from its middle, about a place, turned by a
#! rotation.
pub def shape::box(half: vec3, center: vec3 = vec3::zero, turn: quat = quat::identity): shape {
return shape::of_hull(hull::box(half, center, turn));
}
#! The convex hull around places, as `hull::of` makes it: nothing where they
#! hold no volume, or their hull has too many corners.
pub def shape::hull_of(places: span<vec3>): maybe<shape> {
if hull::of(places) is some(made) {
return shape::of_hull(made);
}
return nothing{};
}
#! A shape of a hull.
pub def shape::of_hull(h: hull): shape {
return shape{ _kind = shape_kind::hull, _a = h.center, _b = h.center, _hull = h };
}
pub val shape::kind: shape_kind {
get => this._kind;
}
#! How far around its middle or segment it reaches: a sphere's or a capsule's
#! radius, and none of a hull.
pub val shape::radius: f32 {
get => this._radius;
}
#! A sphere's middle, or a capsule's first end.
pub val shape::a: vec3 {
get => this._a;
}
#! A capsule's second end, or a sphere's middle.
pub val shape::b: vec3 {
get => this._b;
}
#! A hull's corners and faces.
pub def shape::as_hull(&this): &hull {
return &this._hull;
}
#! The box holding it, where a pose places it.
pub def shape::bounds(&this, at: pose): bounds {
if this._kind == shape_kind::hull {
val m := mat3::rotation(at.turn);
var low := m * this._hull.point(0);
var high := low;
for i in 1..this._hull.count {
val p := m * this._hull.point(i);
low = low.min(p);
high = high.max(p);
}
return bounds{ at.at + low, at.at + high };
}
val a := at.apply(this._a);
val b := at.apply(this._b);
val r := vec3{ this._radius, this._radius, this._radius };
return bounds{ a.min(b) - r, a.max(b) + r };
}
#! Whether it holds a place of space, where a pose places it, its surface
#! among it.
pub def shape::contains(&this, at: pose, p: vec3): bool {
val local := at.unapply(p);
if this._kind == shape_kind::hull {
for f in 0..this._hull.faces {
return false if this._hull.normal(f).dot(local) > this._hull.offset(f);
}
return true;
}
val nearest := nearest_on_segment(local, this._a, this._b);
return (local - nearest).length_squared <= this._radius * this._radius;
}
#! Where a ray first meets it, where a pose places it: from a place, along a
#! direction of length 1, as far as `reach`. A ray beginning within it meets
#! it at 0, facing back along the ray.
pub def shape::ray_cast(&this, at: pose, origin: vec3, direction: vec3, reach: f32): maybe<ray_hit> {
val o := at.unapply(origin);
val d := at.unrotate(direction);
var found: maybe<ray_hit> = nothing{};
if this._kind == shape_kind::hull {
found = ray_hull(&this._hull, o, d, reach);
} else if this._kind == shape_kind::capsule {
found = ray_capsule(o, d, reach, this._a, this._b, this._radius);
} else {
found = ray_sphere(o, d, reach, this._a, this._radius);
}
if found is some(hit) {
return ray_hit{ distance = hit.distance, point = at.apply(hit.point), normal = at.rotate(hit.normal) };
}
return nothing{};
}
# A ray, of the shape's own places, meeting a sphere.
def ray_sphere(o: vec3, d: vec3, reach: f32, center: vec3, radius: f32): maybe<ray_hit> {
val s := o - center;
val c := s.dot(s) - radius * radius;
return ray_hit{ distance = 0, point = o, normal = -d } if c <= 0;
val b := s.dot(d);
return nothing{} if b > 0;
val disc := b * b - c;
return nothing{} if disc < 0;
val t := -b - math::sqrt(disc);
return nothing{} if t > reach;
val p := o + d * t;
return ray_hit{ distance = t, point = p, normal = (p - center) * (1 / radius) };
}
# A ray meeting a capsule: its round side, where it meets it between its ends,
# as an infinite cylinder's, else its round ends.
def ray_capsule(o: vec3, d: vec3, reach: f32, a: vec3, b: vec3, radius: f32): maybe<ray_hit> {
val nearest := nearest_on_segment(o, a, b);
return ray_hit{ distance = 0, point = o, normal = -d } if (o - nearest).length_squared <= radius * radius;
# The cylinder, as Ericson's Real-Time Collision Detection meets one: where
# the ray's distance from its axis is the radius.
val axis := b - a;
val m := o - a;
val dd := axis.dot(axis);
val md := m.dot(axis);
val nd := d.dot(axis);
val qa := dd - nd * nd;
if qa > tiny {
val qb := dd * m.dot(d) - nd * md;
val qc := dd * (m.dot(m) - radius * radius) - md * md;
val disc := qb * qb - qa * qc;
if disc >= 0 {
val t := (-qb - math::sqrt(disc)) / qa;
val along := md + t * nd;
if t >= 0 && t <= reach && along >= 0 && along <= dd {
val p := o + d * t;
val on_axis := a + axis * (along / dd);
return ray_hit{ distance = t, point = p, normal = (p - on_axis) * (1 / radius) };
}
}
}
var best: maybe<ray_hit> = nothing{};
val first := ray_sphere(o, d, reach, a, radius);
val second := ray_sphere(o, d, reach, b, radius);
if first is some(hit) {
best = hit;
}
if second is some(hit) {
if best is some(held) {
if hit.distance < held.distance {
best = hit;
}
} else {
best = hit;
}
}
return best;
}
# A ray meeting a hull, clipped by each face's side in turn, as Cyrus and Beck
# clip a line: where it enters the last side it crosses into is where it meets
# the hull.
def ray_hull(h: &hull, o: vec3, d: vec3, reach: f32): maybe<ray_hit> {
var lower: f32 = 0;
var upper := reach;
var entered: i64 = -1;
for f in 0..h.faces {
val n := h.normal(f);
val numerator := h.offset(f) - n.dot(o);
val denominator := n.dot(d);
if denominator == 0 {
return nothing{} if numerator < 0;
continue;
}
val t := numerator / denominator;
if denominator < 0 && t > lower {
lower = t;
entered = f as i64;
} else if denominator > 0 && t < upper {
upper = t;
}
return nothing{} if upper < lower;
}
return ray_hit{ distance = 0, point = o, normal = -d } if entered < 0;
return ray_hit{ distance = lower, point = o + d * lower, normal = h.normal(entered as u32) };
}
+119
View File
@@ -0,0 +1,119 @@
#! Contains how a space's bodies sleep: those that touch, or a joint holds
#! together, are an island, found anew each step, and an island sleeps when
#! all its bodies have been still for half a second, so a settled pile costs
#! nothing until something wakes it. A kinematic body sleeps alone, when it
#! has been still as long.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
# How long, in seconds, a body is still before it may sleep.
const time_to_sleep: f32 = 0.5;
# The first body of the island a body is of, each body passed on the way
# pointed nearer it, so the next finding is shorter.
def root_of(parent: &mut vector<u32>, b: u32): u32 {
var x := b;
while parent[x as u64] != x {
val up := parent[parent[x as u64] as u64];
parent[x as u64] = up;
x = up;
}
return x;
}
def join(parent: &mut vector<u32>, a: u32, b: u32): void {
val ra := root_of(parent, a);
val rb := root_of(parent, b);
if ra != rb {
parent[math::max(ra, rb) as u64] = math::min(ra, rb);
}
}
# Finds the islands of awake dynamic bodies, and puts to sleep those all of
# whose bodies have been still long enough.
def space::sleep_islands(&mut this, dt: f32): void {
var parent := move(this.islands);
parent.clear();
parent.resize(this.bodies.length, none);
for b in 0..this.bodies.length {
val body := &this.bodies[b];
if body.alive && body.awake && body.kind == body_kind::dynamic {
parent[b] = b as u32;
}
}
for k in 0..this.contacts.length {
val c := &this.contacts[k];
continue if !c.alive || !c.touching;
val a := c.body_a;
val b := c.body_b;
if parent[a as u64] != none && parent[b as u64] != none {
join(&mut parent, a, b);
} else if parent[a as u64] != none && this.bodies[b as u64].kind == body_kind::kinematic {
this.keep_awake_on(a, b);
} else if parent[b as u64] != none && this.bodies[a as u64].kind == body_kind::kinematic {
this.keep_awake_on(b, a);
}
}
this.join_jointed(&mut parent);
# Each island's least time still, kept at its root.
for b in 0..this.bodies.length {
continue if parent[b] == none;
val root := root_of(&mut parent, b as u32) as u64;
this.bodies[root].sleep_time = math::min(this.bodies[root].sleep_time, this.bodies[b].sleep_time);
}
for b in 0..this.bodies.length {
continue if parent[b] == none;
val root := root_of(&mut parent, b as u32);
continue if this.bodies[root as u64].sleep_time < time_to_sleep;
# Linked after its root, which heads the group.
this.bodies[b].awake = false;
this.bodies[b].velocity = vec3::zero;
this.bodies[b].spin = vec3::zero;
this.bodies[b].group = root;
if b as u32 != root {
this.bodies[b].next_in_group = this.bodies[root as u64].next_in_group;
this.bodies[root as u64].next_in_group = b as u32;
}
}
# A kinematic body still long enough sleeps alone.
for b in 0..this.bodies.length {
val body := &this.bodies[b];
if body.alive && body.awake && body.kind == body_kind::kinematic && body.sleep_time >= time_to_sleep {
this.bodies[b].awake = false;
this.bodies[b].group = b as u32;
}
}
this.islands = move(parent);
}
# Keeps a dynamic body awake where it rests on a kinematic body that moves.
def space::keep_awake_on(&mut this, b: u32, kinematic: u32): void {
val k := &this.bodies[kinematic as u64];
if k.velocity.length_squared > 0 || k.spin.length_squared > 0 {
this.bodies[b as u64].sleep_time = 0;
}
}
# Wakes a body, and every body of the group it sleeps with, and marks it as
# having been still for no time.
def space::wake_body(&mut this, b: u32): void {
return if this.bodies[b as u64].kind == body_kind::static;
this.bodies[b as u64].sleep_time = 0;
return if this.bodies[b as u64].awake;
var m := this.bodies[b as u64].group;
if m == none {
this.bodies[b as u64].awake = true;
return;
}
while m != none {
val next := this.bodies[m as u64].next_in_group;
this.bodies[m as u64].awake = true;
this.bodies[m as u64].sleep_time = 0;
this.bodies[m as u64].group = none;
this.bodies[m as u64].next_in_group = none;
m = next;
}
}
+421
View File
@@ -0,0 +1,421 @@
#! Contains how a space solves a step, as Box2D's soft step solves one: in
#! substeps, each of which moves velocities by forces, pushes apart what meets,
#! softly, moves the bodies, and pushes again without undoing overlaps; then
#! bounces what met fast enough, and keeps each contact's impulses for the
#! next step to begin with.
#!
#! A contact pushes as a stiff, damped spring of the space's frequency, so an
#! overlap is undone over a few substeps, no faster than the push speed, and a
#! stack doesn't jitter. Points apart within the speculative margin push only
#! as much as would close the gap in a substep, so what falls stops at what's
#! below it rather than in it. Friction holds each point along two tangents at
#! once, no harder in all than its share of what pushes it, as a cone allows.
import std::containers;
import std::math;
import malunal::linear;
module malunal::physics3d;
# How soft a constraint is, as a damped spring of a frequency is: how much of
# its error it undoes each second, and how much of its impulse it gives.
struct softness {
var bias_rate: f32;
var mass_scale: f32 = 1;
var impulse_scale: f32;
}
def soft_of(hertz: f32, damping: f32, h: f32): softness {
return softness{} if hertz == 0;
val omega := 2 * math::pi as f32 * hertz;
val a1 := 2 * damping + h * omega;
val a2 := h * omega * a1;
val a3 := 1 / (1 + a2);
return softness{ bias_rate = omega / a1, mass_scale = a2 * a3, impulse_scale = a3 };
}
# A body as a step moves it: its velocities, and how far its center has moved
# and it has turned since the step began.
struct body_state {
var v: vec3;
var w: vec3;
var dp: vec3;
var dq: quat;
}
# How a body's velocities change each substep: by its forces and gravity, and
# what its damping keeps of them.
struct body_motion {
var dv: vec3;
var dw: vec3;
var linear_keep: f32 = 1;
var angular_keep: f32 = 1;
}
# A point of a contact as the solver pushes at it: where it is from each
# body's center, how far apart the two are there but for how far they've
# moved, and the impulses pushing them apart and along each tangent.
struct point_constraint {
var anchor_a: vec3;
var anchor_b: vec3;
var base_separation: f32;
var normal_impulse: f32;
var tangent_impulse: vec3;
var max_impulse: f32;
var normal_mass: f32;
var tangent_mass: vec3;
var relative_velocity: f32;
}
struct contact_constraint {
var a: u32; # States.
var b: u32;
var contact: u32;
var normal: vec3;
var t1: vec3;
var t2: vec3;
var friction: f32;
var restitution: f32;
var ma: f32;
var mb: f32;
var soft: softness;
var count: u32;
var points: point_constraint[4];
}
# What a step works in, kept from one to the next so it isn't made anew: the
# first state is of what doesn't move, of no mass and turning by nothing.
struct solver_scratch {
var states: vector<body_state>;
var motions: vector<body_motion>;
var inertias: vector<mat3>; # Each state's inverse inertia, of space's axes.
var bodies: vector<u32>;
var constraints: vector<contact_constraint>;
var joints: vector<u32>;
var joint_soft: softness;
}
# The most a body turns in a substep, a quarter of a half turn, so a fast spin
# doesn't skip through what it meets.
const most_turn: f32 = 0.25 * 3.14159265;
# A rotation turned further by a spin over a time, kept of length 1.
def turned(q: quat, w: vec3, h: f32): quat {
val spin := quat{ w.x, w.y, w.z, 0 } * q;
val half := 0.5 * h;
return quat{ q.x + half * spin.x, q.y + half * spin.y, q.z + half * spin.z, q.w + half * spin.w }.normalized();
}
# How hard it is to push the two along a direction at their anchors.
def mass_along(d: vec3, ra: vec3, rb: vec3, ma: f32, mb: f32, ia: mat3, ib: mat3): f32 {
val rda := ra.cross(d);
val rdb := rb.cross(d);
val k := ma + mb + rda.dot(ia * rda) + rdb.dot(ib * rdb);
return k > 0 ? 1 / k : 0f;
}
def space::solve(&mut this, dt: f32): void {
val n: u32 = this.substeps > 0 ? this.substeps : 1;
val h := dt / n as f32;
val inv_h := 1 / h;
var s := move(this.solver);
this.gather(&mut s, h);
this.prepare_contacts(&mut s, h);
this.prepare_joints(&mut s, h);
val max_spin := most_turn * inv_h;
for i in 0..n {
integrate_velocities(&mut s, this.max_speed, max_spin);
this.warm_joints(&mut s);
warm_contacts(&mut s);
this.solve_joints(&mut s, h, true);
solve_contacts(&mut s, inv_h, this.push_speed, true);
integrate_positions(&mut s, h);
this.solve_joints(&mut s, h, false);
solve_contacts(&mut s, inv_h, this.push_speed, false);
}
bounce(&mut s, this.restitution_threshold);
this.keep_impulses(&s);
this.finish(&s, dt);
this.solver = move(s);
}
# Gives each moving body a state, its inverse inertia as it's turned, and how
# its forces move it each substep.
def space::gather(&mut this, s: &mut solver_scratch, h: f32): void {
s.states.clear();
s.motions.clear();
s.inertias.clear();
s.bodies.clear();
s.states.append(body_state{ dq = quat::identity });
s.motions.append(body_motion{});
s.inertias.append(mat3{});
s.bodies.append(none);
for b in 0..this.bodies.length {
if !this.bodies[b].alive || !this.moves(b as u32) {
this.bodies[b].slot = 0;
continue;
}
this.bodies[b].slot = s.states.length as u32;
val inverse := this.world_inverse_inertia(b as u32);
val body := &this.bodies[b];
s.states.append(body_state{ v = body.velocity, w = body.spin, dq = quat::identity });
s.inertias.append(inverse);
if body.kind == body_kind::dynamic {
s.motions.append(body_motion{
dv = (this.gravity * body.gravity_scale + body.force * body.inv_mass) * h,
dw = (inverse * body.torque) * h,
linear_keep = 1 / (1 + h * body.linear_damping),
angular_keep = 1 / (1 + h * body.angular_damping),
});
} else {
s.motions.append(body_motion{});
}
s.bodies.append(b as u32);
}
}
def space::prepare_contacts(&this, s: &mut solver_scratch, h: f32): void {
s.constraints.clear();
val hertz := math::min(this.contact_hertz, 0.25 / h);
val soft := soft_of(hertz, this.contact_damping, h);
# Against what doesn't move, twice as stiff.
val stiff := soft_of(2 * hertz, this.contact_damping, h);
for k in 0..this.contacts.length {
val c := &this.contacts[k];
continue if !c.alive || !c.touching;
val a := &this.bodies[c.body_a as u64];
val b := &this.bodies[c.body_b as u64];
continue if a.slot == 0 && b.slot == 0;
val ia := s.inertias[a.slot as u64];
val ib := s.inertias[b.slot as u64];
val n := c.manifold.normal;
val t1 := perpendicular_to(n);
val t2 := n.cross(t1);
var made := contact_constraint{
a = a.slot, b = b.slot, contact = k as u32, normal = n, t1 = t1, t2 = t2, friction = c.friction, restitution = c.restitution,
ma = a.inv_mass, mb = b.inv_mass, soft = a.inv_mass == 0 || b.inv_mass == 0 ? stiff : soft, count = c.manifold.count,
};
for j in 0..c.manifold.count {
val mp := &c.manifold.points[j];
val ra := mp.point - a.center;
val rb := mp.point - b.center;
val vra := a.velocity + a.spin.cross(ra);
val vrb := b.velocity + b.spin.cross(rb);
# The tangents' impulses kept as they were along last step's tangents,
# which turn with the normal: what of them lies along these.
made.points[j] = point_constraint{
anchor_a = ra, anchor_b = rb,
base_separation = -mp.depth - (rb - ra).dot(n),
normal_impulse = c.normal_impulse[j], tangent_impulse = c.tangent_impulse[j],
normal_mass = mass_along(n, ra, rb, made.ma, made.mb, ia, ib),
tangent_mass = vec3{ mass_along(t1, ra, rb, made.ma, made.mb, ia, ib), mass_along(t2, ra, rb, made.ma, made.mb, ia, ib), 0 },
relative_velocity = n.dot(vrb - vra),
};
}
s.constraints.append(made);
}
}
def integrate_velocities(s: &mut solver_scratch, max_speed: f32, max_spin: f32): void {
for i in 1..s.states.length {
val m := &s.motions[i];
val st := &mut s.states[i];
var v := st.v * m.linear_keep + m.dv;
var w := st.w * m.angular_keep + m.dw;
val speed_squared := v.length_squared;
if speed_squared > max_speed * max_speed {
v = v * (max_speed / math::sqrt(speed_squared));
}
val spin_squared := w.length_squared;
if spin_squared > max_spin * max_spin {
w = w * (max_spin / math::sqrt(spin_squared));
}
st.v = v;
st.w = w;
}
}
def integrate_positions(s: &mut solver_scratch, h: f32): void {
for i in 1..s.states.length {
val st := &mut s.states[i];
st.dq = turned(st.dq, st.w, h);
st.dp = st.dp + st.v * h;
}
}
def warm_contacts(s: &mut solver_scratch): void {
for i in 0..s.constraints.length {
val c := &s.constraints[i];
val ia := s.inertias[c.a as u64];
val ib := s.inertias[c.b as u64];
var va := s.states[c.a as u64].v;
var wa := s.states[c.a as u64].w;
var vb := s.states[c.b as u64].v;
var wb := s.states[c.b as u64].w;
for j in 0..c.count {
val cp := &c.points[j];
val p := c.normal * cp.normal_impulse + c.t1 * cp.tangent_impulse.x + c.t2 * cp.tangent_impulse.y;
va = va - p * c.ma;
wa = wa - ia * cp.anchor_a.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * cp.anchor_b.cross(p);
}
s.states[c.a as u64].v = va;
s.states[c.a as u64].w = wa;
s.states[c.b as u64].v = vb;
s.states[c.b as u64].w = wb;
}
}
def solve_contacts(s: &mut solver_scratch, inv_h: f32, push: f32, use_bias: bool): void {
val states := s.states.slice();
val constraints := s.constraints.slice();
for i in 0..constraints.length {
val c := &mut constraints[i];
val a := c.a as u64;
val b := c.b as u64;
val ia := s.inertias[a];
val ib := s.inertias[b];
var va := states[a].v;
var wa := states[a].w;
var vb := states[b].v;
var wb := states[b].w;
val dp := states[b].dp - states[a].dp;
val qa := mat3::rotation(states[a].dq);
val qb := mat3::rotation(states[b].dq);
val n := c.normal;
for j in 0..c.count {
val cp := &mut c.points[j];
val ra := cp.anchor_a;
val rb := cp.anchor_b;
# How far apart they are now: as they began, and as far as each anchor
# has moved and turned since.
val d := dp + (qb * rb - qa * ra);
val separation := d.dot(n) + cp.base_separation;
var bias: f32 = 0;
var mass_scale: f32 = 1;
var impulse_scale: f32 = 0;
if separation > 0 {
bias = separation * inv_h;
} else if use_bias {
bias = c.soft.bias_rate * separation;
if bias < -push {
bias = -push;
}
mass_scale = c.soft.mass_scale;
impulse_scale = c.soft.impulse_scale;
}
val vn := (vb + wb.cross(rb) - va - wa.cross(ra)).dot(n);
val before := cp.normal_impulse;
var sum := before - cp.normal_mass * mass_scale * (vn + bias) - impulse_scale * before;
if sum < 0 {
sum = 0;
}
val impulse := sum - before;
cp.normal_impulse = sum;
if impulse > cp.max_impulse {
cp.max_impulse = impulse;
}
val p := n * impulse;
va = va - p * c.ma;
wa = wa - ia * ra.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * rb.cross(p);
}
# Friction along both tangents, of no more in all than its share of what
# pushes them apart.
for j in 0..c.count {
val cp := &mut c.points[j];
val ra := cp.anchor_a;
val rb := cp.anchor_b;
val dv := vb + wb.cross(rb) - va - wa.cross(ra);
val before := cp.tangent_impulse;
var sum := vec3{ before.x - cp.tangent_mass.x * dv.dot(c.t1), before.y - cp.tangent_mass.y * dv.dot(c.t2), 0 };
val most := c.friction * cp.normal_impulse;
val squared := sum.x * sum.x + sum.y * sum.y;
if squared > most * most {
sum = sum * (most / math::sqrt(squared));
}
cp.tangent_impulse = sum;
val p := c.t1 * (sum.x - before.x) + c.t2 * (sum.y - before.y);
va = va - p * c.ma;
wa = wa - ia * ra.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * rb.cross(p);
}
states[a].v = va;
states[a].w = wa;
states[b].v = vb;
states[b].w = wb;
}
}
# Bounces what met faster than the threshold, as much as its restitution
# keeps of how fast it met: only at points that pushed, so a speculative
# point that never closed doesn't bounce.
def bounce(s: &mut solver_scratch, threshold: f32): void {
for i in 0..s.constraints.length {
val c := &mut s.constraints[i];
continue if c.restitution == 0;
val ia := s.inertias[c.a as u64];
val ib := s.inertias[c.b as u64];
var va := s.states[c.a as u64].v;
var wa := s.states[c.a as u64].w;
var vb := s.states[c.b as u64].v;
var wb := s.states[c.b as u64].w;
val n := c.normal;
for j in 0..c.count {
val cp := &mut c.points[j];
continue if cp.relative_velocity > -threshold || cp.max_impulse == 0;
val vn := (vb + wb.cross(cp.anchor_b) - va - wa.cross(cp.anchor_a)).dot(n);
var impulse := -cp.normal_mass * (vn + c.restitution * cp.relative_velocity);
val sum := math::max(cp.normal_impulse + impulse, 0f);
impulse = sum - cp.normal_impulse;
cp.normal_impulse = sum;
cp.max_impulse = math::max(cp.max_impulse, impulse);
val p := n * impulse;
va = va - p * c.ma;
wa = wa - ia * cp.anchor_a.cross(p);
vb = vb + p * c.mb;
wb = wb + ib * cp.anchor_b.cross(p);
}
s.states[c.a as u64].v = va;
s.states[c.a as u64].w = wa;
s.states[c.b as u64].v = vb;
s.states[c.b as u64].w = wb;
}
}
def space::keep_impulses(&mut this, s: &solver_scratch): void {
for i in 0..s.constraints.length {
val c := &s.constraints[i];
for j in 0..c.count {
this.contacts[c.contact as u64].normal_impulse[j] = c.points[j].normal_impulse;
this.contacts[c.contact as u64].tangent_impulse[j] = c.points[j].tangent_impulse;
}
}
}
# Puts each moving body where its state moved it, its colliders' leaves with
# it, and times how long it's been still.
def space::finish(&mut this, s: &solver_scratch, dt: f32): void {
val still := 0.05 * this.unit;
for i in 1..s.states.length {
val b := s.bodies[i] as u64;
val st := &s.states[i];
val center := this.bodies[b].center + st.dp;
val turn := (st.dq * this.bodies[b].at.turn).normalized();
this.bodies[b].center = center;
this.bodies[b].at = pose{ at = center - turn * this.bodies[b].local_center, turn = turn };
this.bodies[b].velocity = st.v;
this.bodies[b].spin = st.w;
this.bodies[b].force = vec3::zero;
this.bodies[b].torque = vec3::zero;
val speed := st.v.length + st.w.length * this.bodies[b].extent;
if !this.bodies[b].can_sleep || speed > still {
this.bodies[b].sleep_time = 0;
} else {
this.bodies[b].sleep_time += dt;
}
this.place_colliders(b as u32);
}
}
+462
View File
@@ -0,0 +1,462 @@
#! Contains `space`, where bodies move: each made of colliders, pulled by
#! gravity, pushed by forces and by what they meet, and stepped forward in
#! time, as `physics2d`'s space steps them in a plane.
#!
#! A step finds the colliders newly near one another, by the boxes of its
#! tree; where those near meet, as contacts kept from the last step, a
#! triangle mesh's one for each triangle met; and then solves them, in
#! substeps, as Box2D's soft step does: each substep moves the bodies'
#! velocities by their forces, pushes them apart where they meet, softly so a
#! deep overlap is undone over a few steps rather than at once, moves them, and
#! pushes again without undoing overlaps, so what was pushed apart doesn't fly.
#! Each contact begins a step with the impulses it ended the last with, so a
#! stack settles and stays still. Bodies that rest long enough, with all they
#! touch, sleep until something wakes them.
#!
#! Lengths are a game's units, and its tolerances are made for a unit of a
#! meter: a space of another unit is made with how many units a meter is.
import std::containers;
import std::math;
import std::time;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Where bodies move, as one step after another moves them.
pub struct space {
#! The pull on every dynamic body, in lengths a second each second.
pub var gravity := vec3{ 0, -10, 0 };
#! How many substeps each step is solved in: more is stiffer and slower.
pub var substeps: u32 = 4;
#! How stiff contacts are, as a spring of so many cycles a second, and how
#! much they're damped: past 1, they don't spring back.
pub var contact_hertz: f32 = 30;
pub var contact_damping: f32 = 10;
#! The same of joints.
pub var joint_hertz: f32 = 60;
pub var joint_damping: f32 = 2;
#! The fastest a contact pushes overlapping bodies apart, in lengths a
#! second.
pub var push_speed: f32 = 3;
#! How fast bodies must meet, in lengths a second, to bounce.
pub var restitution_threshold: f32 = 1;
#! The fastest a body moves, in lengths a second.
pub var max_speed: f32 = 400;
#! Whether bodies at rest sleep.
pub var sleeping: bool = true;
#! How long the last step took, and each of its parts.
pub var profile: step_profile;
var unit: f32 = 1;
var bodies: vector<body_record>;
var colliders: vector<collider_record>;
var meshes: vector<triangle_mesh>;
var pairs: vector<pair_record>;
var contacts: vector<contact_record>;
var joints: vector<joint_record>;
var free_bodies: vector<u32>;
var free_colliders: vector<u32>;
var free_meshes: vector<u32>;
var free_pairs: vector<u32>;
var free_contacts: vector<u32>;
var free_joints: vector<u32>;
var tree: aabb_tree;
var pair_keys: dict<u64, u32>;
var moved: vector<u32>;
var near: vector<u32>;
var met: vector<met_triangle>;
var noted: vector<contact_event>;
var solver: solver_scratch;
var islands: vector<u32>;
}
#! How long a step took, in milliseconds, and each of its parts: finding what
#! newly nears, where it meets, solving it, and finding what sleeps.
pub struct step_profile {
pub var pairs: f64;
pub var contacts: f64;
pub var solve: f64;
pub var sleep: f64;
pub var step: f64;
}
#! A space of no bodies, pulled by a gravity: `unit` is how many of its lengths
#! a meter is, which its tolerances, push speed, bounce threshold, and top
#! speed are scaled by.
pub def space::new(gravity: vec3 = vec3{ 0, -10, 0 }, unit: f32 = 1): space {
return space{
gravity = gravity, unit = unit, push_speed = 3 * unit, restitution_threshold = unit, max_speed = 400 * unit,
tree = aabb_tree::new(0.1 * unit), pair_keys = dict::<u64, u32>::new(),
};
}
# How near two surfaces are taken as touching: what contacts let them overlap
# by, and what they meet at before touching.
val space::slop: f32 {
get => 0.005 * this.unit;
}
val space::speculative: f32 {
get => 4 * this.slop;
}
#! How many bodies it holds.
pub val space::body_count: u64 {
get => this.bodies.length - this.free_bodies.length;
}
#! How many contacts it holds: pairs of shapes, or a shape and a triangle,
#! near enough to meet.
pub val space::contact_count: u64 {
get => this.contacts.length - this.free_contacts.length;
}
#! The contacts that began and ended touching in the last step.
pub def space::events(&this): span<contact_event> {
return this.noted.view();
}
#! Adds a body, of no colliders yet.
pub def space::add(&mut this, made: body): body_id {
var index: u32 = 0;
if this.free_bodies.length > 0 {
index = this.free_bodies[this.free_bodies.length - 1];
this.free_bodies.truncate();
} else {
index = this.bodies.length as u32;
this.bodies.append(body_record{});
}
val generation := this.bodies[index as u64].generation + 1;
val moving := made.kind != body_kind::static;
this.bodies[index as u64] = body_record{
kind = made.kind, generation = generation, alive = true, at = made.at, center = made.at.at,
velocity = moving ? made.velocity : vec3::zero, spin = moving ? made.spin : vec3::zero,
linear_damping = made.linear_damping, angular_damping = made.angular_damping, gravity_scale = made.gravity_scale,
fixed_rotation = made.fixed_rotation, can_sleep = made.can_sleep, data = made.data,
};
this.find_mass(index);
return body_id{ index = index, generation = generation };
}
#! Whether a body is of it still.
pub def space::has(&this, id: body_id): bool {
return id.index < this.bodies.length as u32 && this.bodies[id.index as u64].alive && this.bodies[id.index as u64].generation == id.generation;
}
#! Removes a body, its colliders, the contacts they're of, and the joints it's
#! of, waking what it touched.
pub def space::remove(&mut this, id: body_id): void {
return if !this.has(id);
this.wake_body(id.index);
var c := this.bodies[id.index as u64].colliders;
while c != none {
val next := this.colliders[c as u64].next;
this.drop_collider(c);
c = next;
}
this.drop_joints_of(id.index);
this.bodies[id.index as u64].alive = false;
this.bodies[id.index as u64].colliders = none;
this.bodies[id.index as u64].group = none;
this.free_bodies.append(id.index);
}
#! Gives a body a collider, its mass summed again of its colliders'.
pub def space::attach(&mut this, to: body_id, made: collider): collider_id {
return collider_id{} if !this.has(to);
return this.attach_record(to, collider_record{ made = made, body = to.index });
}
#! Gives a static body the triangles of a mesh, as a level's ground and walls,
#! which push what meets each as its face does, but at the edges two don't
#! fold at, so what slides across them doesn't catch. Its shape and density
#! are passed over; a mesh meets shapes, not another mesh.
pub def space::attach_mesh(&mut this, to: body_id, mesh: triangle_mesh, made: collider): collider_id {
var held := move(mesh);
return collider_id{} if !this.has(to);
var m: u32 = 0;
if this.free_meshes.length > 0 {
m = this.free_meshes[this.free_meshes.length - 1];
this.free_meshes.truncate();
this.meshes[m as u64] = move(held);
} else {
m = this.meshes.length as u32;
this.meshes.append(move(held));
}
return this.attach_record(to, collider_record{ made = made, mesh = m, body = to.index });
}
def space::attach_record(&mut this, to: body_id, record: collider_record): collider_id {
var index: u32 = 0;
if this.free_colliders.length > 0 {
index = this.free_colliders[this.free_colliders.length - 1];
this.free_colliders.truncate();
} else {
index = this.colliders.length as u32;
this.colliders.append(collider_record{});
}
val generation := this.colliders[index as u64].generation + 1;
var made := record;
made.next = this.bodies[to.index as u64].colliders;
made.generation = generation;
made.alive = true;
made.moved = true;
this.colliders[index as u64] = made;
val box := this.box_of(index, this.bodies[to.index as u64].at);
this.colliders[index as u64].leaf = this.tree.insert(box, index as u64);
this.bodies[to.index as u64].colliders = index;
this.moved.append(index);
this.find_mass(to.index);
this.wake_body(to.index);
return collider_id{ index = index, generation = generation };
}
# The box holding a collider, where a pose places its body.
def space::box_of(&this, c: u32, at: pose): bounds {
val record := &this.colliders[c as u64];
return record.made.shape.bounds(at) if !record.is_mesh();
val own := this.meshes[record.mesh as u64].bounds();
var made := bounds::empty;
for k in 0..8u {
val corner := vec3{ (k & 1) != 0 ? own.max.x : own.min.x, (k & 2) != 0 ? own.max.y : own.min.y, (k & 4) != 0 ? own.max.z : own.min.z };
made = made.including(at.apply(corner));
}
return made;
}
#! Whether a collider is of it still.
pub def space::has(&this, id: collider_id): bool {
return id.index < this.colliders.length as u32 && this.colliders[id.index as u64].alive && this.colliders[id.index as u64].generation == id.generation;
}
#! Takes a collider from its body, its mass summed again of the rest.
pub def space::detach(&mut this, id: collider_id): void {
return if !this.has(id);
val b := this.colliders[id.index as u64].body;
var c := this.bodies[b as u64].colliders;
if c == id.index {
this.bodies[b as u64].colliders = this.colliders[c as u64].next;
} else {
while c != none {
val next := this.colliders[c as u64].next;
if next == id.index {
this.colliders[c as u64].next = this.colliders[next as u64].next;
break;
}
c = next;
}
}
this.drop_collider(id.index);
this.find_mass(b);
this.wake_body(b);
}
# Frees a collider, its leaf, its mesh, and its pairs.
def space::drop_collider(&mut this, c: u32): void {
for p in 0..this.pairs.length {
if this.pairs[p].alive && (this.pairs[p].a == c || this.pairs[p].b == c) {
this.drop_pair(p as u32, true);
}
}
this.tree.remove(this.colliders[c as u64].leaf);
if this.colliders[c as u64].is_mesh() {
val m := this.colliders[c as u64].mesh;
this.meshes[m as u64] = triangle_mesh::new(span::<vec3>::empty(), span::<u32>::empty());
this.free_meshes.append(m);
}
this.colliders[c as u64].alive = false;
this.free_colliders.append(c);
}
#! The body a collider is of.
pub def space::body_of(&this, id: collider_id): body_id {
return body_id{} if !this.has(id);
val b := this.colliders[id.index as u64].body;
return body_id{ index = b, generation = this.bodies[b as u64].generation };
}
#! What a collider was made as.
pub def space::collider_of(&this, id: collider_id): &collider {
return &this.colliders[id.index as u64].made;
}
#! The number its user gave a body.
pub def space::data_of(&this, id: body_id): u64 {
return this.bodies[id.index as u64].data;
}
#! What kind of body it is.
pub def space::kind_of(&this, id: body_id): body_kind {
return this.bodies[id.index as u64].kind;
}
#! Where a body is, and which way it's turned.
pub def space::pose_of(&this, id: body_id): pose {
return this.bodies[id.index as u64].at;
}
#! How fast a body's center of mass moves, and how fast it turns.
pub def space::velocity_of(&this, id: body_id): vec3 {
return this.bodies[id.index as u64].velocity;
}
pub def space::spin_of(&this, id: body_id): vec3 {
return this.bodies[id.index as u64].spin;
}
#! A body's mass, its center of its own places, and its inertia tensor about
#! that center.
pub def space::mass_of(&this, id: body_id): mass_data {
val b := &this.bodies[id.index as u64];
return mass_data{ mass = b.mass, center = b.local_center, inertia = b.inertia };
}
#! Where a body's center of mass is in space.
pub def space::center_of(&this, id: body_id): vec3 {
return this.bodies[id.index as u64].center;
}
#! Whether a body is awake, as it is but where it and all it rests on have
#! been still long enough.
pub def space::is_awake(&this, id: body_id): bool {
return this.bodies[id.index as u64].awake;
}
#! Puts a body somewhere, as it is at once, waking it.
pub def space::set_pose(&mut this, id: body_id, at: pose): void {
return if !this.has(id);
this.bodies[id.index as u64].at = at;
this.bodies[id.index as u64].center = at.apply(this.bodies[id.index as u64].local_center);
this.place_colliders(id.index);
this.wake_body(id.index);
}
#! Sets how fast a body moves, waking it.
pub def space::set_velocity(&mut this, id: body_id, velocity: vec3): void {
return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static;
this.bodies[id.index as u64].velocity = velocity;
if velocity.length_squared > 0 {
this.wake_body(id.index);
}
}
#! Sets how fast a body turns, waking it.
pub def space::set_spin(&mut this, id: body_id, spin: vec3): void {
return if !this.has(id) || this.bodies[id.index as u64].kind == body_kind::static || this.bodies[id.index as u64].fixed_rotation;
this.bodies[id.index as u64].spin = spin;
if spin.length_squared > 0 {
this.wake_body(id.index);
}
}
#! Pushes a dynamic body through the next step by a force at a place of space,
#! which turns it too where that's off its center, waking it.
pub def space::apply_force(&mut this, id: body_id, force: vec3, at: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
val i := id.index as u64;
this.bodies[i].force = this.bodies[i].force + force;
this.bodies[i].torque = this.bodies[i].torque + (at - this.bodies[i].center).cross(force);
this.wake_body(id.index);
}
#! Pushes a dynamic body through the next step by a force at its center,
#! waking it.
pub def space::apply_force_to_center(&mut this, id: body_id, force: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
this.bodies[id.index as u64].force = this.bodies[id.index as u64].force + force;
this.wake_body(id.index);
}
#! Turns a dynamic body through the next step by a torque, waking it.
pub def space::apply_torque(&mut this, id: body_id, torque: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
this.bodies[id.index as u64].torque = this.bodies[id.index as u64].torque + torque;
this.wake_body(id.index);
}
#! Changes how fast a dynamic body moves and turns at once, as a blow at a
#! place of space does, waking it.
pub def space::apply_impulse(&mut this, id: body_id, impulse: vec3, at: vec3): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
val i := id.index as u64;
this.bodies[i].velocity = this.bodies[i].velocity + impulse * this.bodies[i].inv_mass;
this.bodies[i].spin = this.bodies[i].spin + this.world_inverse_inertia(id.index) * (at - this.bodies[i].center).cross(impulse);
this.wake_body(id.index);
}
#! Wakes a body, and those it sleeps with.
pub def space::wake(&mut this, id: body_id): void {
if this.has(id) {
this.wake_body(id.index);
}
}
# A body's inverse inertia tensor, of space's axes as it's turned.
def space::world_inverse_inertia(&this, b: u32): mat3 {
val body := &this.bodies[b as u64];
val r := mat3::rotation(body.at.turn);
return r * body.inv_inertia * r.transposed();
}
# Sums a body's mass of its colliders', where it's dynamic, and how far they
# reach from its center.
def space::find_mass(&mut this, b: u32): void {
var sum := mass_data{};
if this.bodies[b as u64].is_dynamic() {
var c := this.bodies[b as u64].colliders;
while c != none {
val record := &this.colliders[c as u64];
if !record.is_mesh() && record.made.density > 0 {
sum = sum.add(record.made.shape.mass(record.made.density));
}
c = record.next;
}
}
var mass: f32 = 0;
var inertia := mat3{};
var inverse := mat3{};
var local := vec3::zero;
if this.bodies[b as u64].is_dynamic() {
# A dynamic body of no mass moves as one of 1.
mass = sum.mass > 0 ? sum.mass : 1f;
local = sum.center;
if sum.mass > 0 && !this.bodies[b as u64].fixed_rotation && sum.inertia.determinant > 0 {
inertia = sum.inertia;
inverse = sum.inertia.inverse();
}
}
var extent: f32 = 0;
var c := this.bodies[b as u64].colliders;
while c != none {
val record := &this.colliders[c as u64];
if !record.is_mesh() {
val box := record.made.shape.bounds(pose::identity);
extent = math::max(extent, (box.max - local).length);
extent = math::max(extent, (box.min - local).length);
}
c = record.next;
}
val i := b as u64;
this.bodies[i].mass = mass;
this.bodies[i].inv_mass = mass > 0 ? 1 / mass : 0f;
this.bodies[i].inertia = inertia;
this.bodies[i].inv_inertia = inverse;
this.bodies[i].local_center = local;
this.bodies[i].center = this.bodies[i].at.apply(local);
this.bodies[i].extent = extent;
}
# Puts a body's colliders' leaves where it is, each that leaves its grown box
# to find what it newly nears.
def space::place_colliders(&mut this, b: u32): void {
val at := this.bodies[b as u64].at;
var c := this.bodies[b as u64].colliders;
while c != none {
val box := this.box_of(c, at);
if this.tree.move(this.colliders[c as u64].leaf, box) && !this.colliders[c as u64].moved {
this.colliders[c as u64].moved = true;
this.moved.append(c);
}
c = this.colliders[c as u64].next;
}
}
+68
View File
@@ -0,0 +1,68 @@
#! Contains how a space steps forward in time, and what rays meet in it.
import std::containers;
import std::math;
import std::time;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
#! Steps the space forward in time: finds what's newly near, where it meets,
#! and moves its bodies, pushed apart where they meet. Events of what began
#! and stopped touching are those of this step alone after.
pub def space::step(&mut this, dt: f32): void {
this.noted.clear();
return if dt <= 0;
val began := instant::now();
this.find_pairs();
val paired := instant::now();
this.update_contacts();
val met := instant::now();
this.solve(dt);
val solved := instant::now();
if this.sleeping {
this.sleep_islands(dt);
}
val slept := instant::now();
this.profile = step_profile{
pairs = milliseconds(paired - began), contacts = milliseconds(met - paired),
solve = milliseconds(solved - met), sleep = milliseconds(slept - solved), step = milliseconds(slept - began),
};
}
def milliseconds(d: duration): f64 {
return d.in_nanoseconds as f64 / 1e6;
}
#! Where a ray met a space's collider: which, of which body, where, and of a
#! mesh's, which triangle.
pub struct space_hit {
pub var collider: collider_id;
pub var body: body_id;
pub var distance: f32;
pub var point: vec3;
pub var normal: vec3;
pub var triangle: u32 = 0xFFFFFFFF;
}
#! Where a ray first meets a collider on a layer of a mask, sensors passed
#! over: from a place, along a direction of length 1, as far as `reach`.
pub def space::ray_cast(&this, origin: vec3, direction: vec3, reach: f32, mask: u32 = 0xFFFFFFFF): maybe<space_hit> {
var best: maybe<space_hit> = nothing{};
this.tree.ray_cast(origin, direction, reach, def(leaf: u32, data: u64, so_far: f32): f32 {
val c := &this.colliders[data];
return so_far if (c.made.layers & mask) == 0 || c.made.sensor;
val at := this.bodies[c.body as u64].at;
val named := collider_id{ index = data as u32, generation = c.generation };
val of := body_id{ index = c.body, generation = this.bodies[c.body as u64].generation };
if c.is_mesh() {
val met := this.meshes[c.mesh as u64].ray_cast(at, origin, direction, so_far) else { return so_far; };
best = space_hit{ collider = named, body = of, distance = met.distance, point = met.point, normal = met.normal, triangle = met.triangle };
return met.distance;
}
val met := c.made.shape.ray_cast(at, origin, direction, so_far) else { return so_far; };
best = space_hit{ collider = named, body = of, distance = met.distance, point = met.point, normal = met.normal };
return met.distance;
});
return best;
}
+382
View File
@@ -0,0 +1,382 @@
#! Contains `aabb_tree`, a tree of boxes: each leaf a box holding a number of
#! its user's, as an entity's bits, and each branch the least box holding its
#! two children, so what's near a box, or along a ray, is found by passing down
#! only the branches that reach it, as Box2D's dynamic tree finds it.
#!
#! A leaf's box is grown past what it holds by the tree's margin, so what moves
#! a little stays within it, and the tree isn't changed. A leaf is put where it
#! grows the area of the boxes above it least, and each branch it passes is
#! turned, as an AVL tree turns one, where one child is two or more deeper than
#! the other, so the tree stays shallow whatever order its leaves come in.
import std::math;
import malunal::geometry;
import malunal::linear;
module malunal::physics3d;
# No node.
const none_node: u32 = 0xFFFFFFFF;
# The deepest a tree of shallow branches can be, with room to spare: past 2^40
# leaves.
const most_depth: u64 = 64;
struct tree_node {
var box: bounds;
var data: u64;
var parent: u32 = 0xFFFFFFFF; # Or the next free node, where it's free.
var left: u32 = 0xFFFFFFFF; # None of a leaf.
var right: u32 = 0xFFFFFFFF;
var height: i32; # 0 of a leaf, and -1 where it's free.
}
#! A tree of boxes, each leaf holding a number of its user's, named by the leaf
#! `insert` gives, which stays its name until it's removed.
pub struct aabb_tree {
var nodes: vector<tree_node>;
var root: u32 = 0xFFFFFFFF;
var free: u32 = 0xFFFFFFFF;
var leaves: u64;
#! How far each leaf's box is grown past what it holds.
pub var margin: f32 = 0.1;
}
#! A tree of no leaves, its boxes grown by a margin.
pub def aabb_tree::new(margin: f32 = 0.1): aabb_tree {
return aabb_tree{ nodes = vector::<tree_node>::new(), margin = margin };
}
#! How many leaves it holds.
pub val aabb_tree::length: u64 {
get => this.leaves;
}
#! How deep it is: 0 of no leaves or one, and 1 more for each branch down to
#! its deepest leaf.
pub val aabb_tree::height: i32 {
get => this.root == none_node ? 0 : this.nodes[this.root as u64].height;
}
#! Adds a box, and a number of the user's, as a leaf.
#! @returns The leaf, which names it until it's removed.
pub def aabb_tree::insert(&mut this, box: bounds, data: u64): u32 {
val leaf := this.allocate();
this.nodes[leaf as u64].box = grown(box, this.margin);
this.nodes[leaf as u64].data = data;
this.nodes[leaf as u64].height = 0;
this.insert_leaf(leaf);
this.leaves++;
return leaf;
}
#! Removes a leaf.
pub def aabb_tree::remove(&mut this, leaf: u32): void {
this.remove_leaf(leaf);
this.release(leaf);
this.leaves--;
}
#! Moves a leaf to hold a box, where its grown box doesn't hold it already.
#! @returns Whether it was moved.
pub def aabb_tree::move(&mut this, leaf: u32, box: bounds): bool {
return false if this.nodes[leaf as u64].box.contains(box);
this.remove_leaf(leaf);
this.nodes[leaf as u64].box = grown(box, this.margin);
this.insert_leaf(leaf);
return true;
}
#! The number a leaf holds.
pub def aabb_tree::data(&this, leaf: u32): u64 {
return this.nodes[leaf as u64].data;
}
#! A leaf's box, grown by the margin.
pub def aabb_tree::box_of(&this, leaf: u32): bounds {
return this.nodes[leaf as u64].box;
}
#! Visits each leaf whose box meets a box, as `visit(leaf, data)`, until it
#! gives false.
pub def aabb_tree::query<F>(&this, box: bounds, visit: F): void where F: invokable<def(u32, u64): bool> {
return if this.root == none_node;
var stack: u32[64];
var top: u64 = 1;
stack[0] = this.root;
while top > 0 {
top--;
val index := stack[top] as u64;
continue if !this.nodes[index].box.overlaps(box);
if this.nodes[index].left == none_node {
return if !visit(index as u32, this.nodes[index].data);
} else if top + 2 <= most_depth {
stack[top] = this.nodes[index].left;
stack[top + 1] = this.nodes[index].right;
top += 2;
}
}
}
#! Visits each leaf whose box a ray meets, from a place, along a direction of
#! length 1, as far as `reach`, as `visit(leaf, data, reach)`, which gives how
#! far to go on: the distance of what it found there, so only what's nearer is
#! visited after; `reach` as it was, to go on as far; or 0, to stop.
pub def aabb_tree::ray_cast<F>(&this, origin: vec3, direction: vec3, reach: f32, visit: F): void
where F: invokable<def(u32, u64, f32): f32> {
return if this.root == none_node;
var far := reach;
var stack: u32[64];
var top: u64 = 1;
stack[0] = this.root;
while top > 0 {
top--;
val index := stack[top] as u64;
continue if !ray_reaches(&this.nodes[index].box, origin, direction, far);
if this.nodes[index].left == none_node {
val next := visit(index as u32, this.nodes[index].data, far);
return if next <= 0;
far = math::min(far, next);
} else if top + 2 <= most_depth {
stack[top] = this.nodes[index].left;
stack[top + 1] = this.nodes[index].right;
top += 2;
}
}
}
#! Whether the tree is as it should be: each node's parent its parent, each
#! branch's box the least holding its children's, and its height one more than
#! its deeper child's, each branch's children no more than one apart in height.
#! For tests.
pub def aabb_tree::is_sound(&this): bool {
return true if this.root == none_node;
return false if this.nodes[this.root as u64].parent != none_node;
var stack: u32[64];
var top: u64 = 1;
var seen: u64 = 0;
stack[0] = this.root;
while top > 0 {
top--;
val index := stack[top] as u64;
val left := this.nodes[index].left;
val right := this.nodes[index].right;
if left == none_node {
return false if right != none_node || this.nodes[index].height != 0;
seen++;
continue;
}
val l := &this.nodes[left as u64];
val r := &this.nodes[right as u64];
return false if l.parent != index as u32 || r.parent != index as u32;
return false if this.nodes[index].height != 1 + math::max(l.height, r.height) || math::abs(l.height - r.height) > 1;
return false if !(l.box.merged(r.box) == this.nodes[index].box);
return false if top + 2 > most_depth;
stack[top] = left;
stack[top + 1] = right;
top += 2;
}
return seen == this.leaves;
}
# A box grown so far each way.
def grown(box: bounds, by: f32): bounds {
val reach := vec3{ by, by, by };
return bounds{ box.min - reach, box.max + reach };
}
# The area of a box's faces, which a tree weighs where to put a box by, as the
# chance a ray or a box passing by meets it.
def area_of(box: bounds): f32 {
val size := box.max - box.min;
return 2 * (size.x * size.y + size.y * size.z + size.z * size.x);
}
# Whether a ray reaches a box, from a place, along a direction, as far as
# `reach`: whether it's between the box's faces along every axis at once.
def ray_reaches(box: &bounds, origin: vec3, direction: vec3, reach: f32): bool {
var low: f32 = 0;
var high := reach;
val origins: f32[3] = [origin.x, origin.y, origin.z];
val ways: f32[3] = [direction.x, direction.y, direction.z];
val lows: f32[3] = [box.min.x, box.min.y, box.min.z];
val highs: f32[3] = [box.max.x, box.max.y, box.max.z];
for i in 0..3u {
if math::abs(ways[i]) < tiny {
return false if origins[i] < lows[i] || origins[i] > highs[i];
continue;
}
var near := (lows[i] - origins[i]) / ways[i];
var far := (highs[i] - origins[i]) / ways[i];
if near > far {
val swapped := near;
near = far;
far = swapped;
}
low = math::max(low, near);
high = math::min(high, far);
return false if low > high;
}
return true;
}
# A node to use: a free one, or a new one.
def aabb_tree::allocate(&mut this): u32 {
if this.free == none_node {
this.nodes.append(tree_node{});
return (this.nodes.length - 1) as u32;
}
val made := this.free;
this.free = this.nodes[made as u64].parent;
this.nodes[made as u64] = tree_node{};
return made;
}
# Frees a node, for another to use.
def aabb_tree::release(&mut this, index: u32): void {
this.nodes[index as u64] = tree_node{ parent = this.free, height = -1 };
this.free = index;
}
# What putting a box beneath a child costs: what the child's box grows by, or
# all of it, of a leaf, which a new branch takes the place of.
def aabb_tree::descent_cost(&this, child: u32, box: bounds): f32 {
val node := &this.nodes[child as u64];
val merged := area_of(box.merged(node.box));
return merged if node.left == none_node;
return merged - area_of(node.box);
}
# Puts a leaf where it grows the boxes above it least: beside a node, beneath a
# new branch holding both.
def aabb_tree::insert_leaf(&mut this, leaf: u32): void {
if this.root == none_node {
this.root = leaf;
this.nodes[leaf as u64].parent = none_node;
return;
}
val box := this.nodes[leaf as u64].box;
var index := this.root;
while this.nodes[index as u64].left != none_node {
val node_box := this.nodes[index as u64].box;
val left := this.nodes[index as u64].left;
val right := this.nodes[index as u64].right;
val combined := area_of(node_box.merged(box));
# Beside this node, a new branch holding both; beneath it, every box
# above grows as this one does.
val here := 2 * combined;
val inherited := 2 * (combined - area_of(node_box));
val to_left := this.descent_cost(left, box) + inherited;
val to_right := this.descent_cost(right, box) + inherited;
break if here < to_left && here < to_right;
index = to_left < to_right ? left : right;
}
val sibling := index;
val old_parent := this.nodes[sibling as u64].parent;
val branch := this.allocate();
this.nodes[branch as u64].parent = old_parent;
this.nodes[branch as u64].box = box.merged(this.nodes[sibling as u64].box);
this.nodes[branch as u64].height = this.nodes[sibling as u64].height + 1;
this.nodes[branch as u64].left = sibling;
this.nodes[branch as u64].right = leaf;
this.nodes[sibling as u64].parent = branch;
this.nodes[leaf as u64].parent = branch;
if old_parent == none_node {
this.root = branch;
} else if this.nodes[old_parent as u64].left == sibling {
this.nodes[old_parent as u64].left = branch;
} else {
this.nodes[old_parent as u64].right = branch;
}
this.refit(this.nodes[leaf as u64].parent);
}
# Takes a leaf out, its sibling taking its parent's place.
def aabb_tree::remove_leaf(&mut this, leaf: u32): void {
if leaf == this.root {
this.root = none_node;
return;
}
val parent := this.nodes[leaf as u64].parent;
val grandparent := this.nodes[parent as u64].parent;
val sibling := this.nodes[parent as u64].left == leaf ? this.nodes[parent as u64].right : this.nodes[parent as u64].left;
this.nodes[sibling as u64].parent = grandparent;
this.release(parent);
if grandparent == none_node {
this.root = sibling;
return;
}
if this.nodes[grandparent as u64].left == parent {
this.nodes[grandparent as u64].left = sibling;
} else {
this.nodes[grandparent as u64].right = sibling;
}
this.refit(grandparent);
}
# Walks up from a branch to the root, turning each that's out of balance, and
# making its box and height those of its children again.
def aabb_tree::refit(&mut this, from: u32): void {
var index := from;
while index != none_node {
index = this.balance(index);
val left := this.nodes[index as u64].left;
val right := this.nodes[index as u64].right;
this.nodes[index as u64].height = 1 + math::max(this.nodes[left as u64].height, this.nodes[right as u64].height);
this.nodes[index as u64].box = this.nodes[left as u64].box.merged(this.nodes[right as u64].box);
index = this.nodes[index as u64].parent;
}
}
# Turns a branch whose children are two or more apart in height: the deeper
# child takes its place, and it takes the deeper child's shallower child.
# @returns The node in its place now.
def aabb_tree::balance(&mut this, a: u32): u32 {
return a if this.nodes[a as u64].left == none_node || this.nodes[a as u64].height < 2;
val b := this.nodes[a as u64].left;
val c := this.nodes[a as u64].right;
val leaning := this.nodes[c as u64].height - this.nodes[b as u64].height;
if leaning > 1 {
this.raise(a, c, b, true);
return c;
}
if leaning < -1 {
this.raise(a, b, c, false);
return b;
}
return a;
}
# Raises `up`, a child of `a`, into its place: `a` becomes `up`'s first child,
# beside `up`'s deeper child, and takes `up`'s shallower child where `up` was,
# `other` its child still. `on_right` says `up` was `a`'s right child.
def aabb_tree::raise(&mut this, a: u32, up: u32, other: u32, on_right: bool): void {
val f := this.nodes[up as u64].left;
val g := this.nodes[up as u64].right;
# `up` takes `a`'s place beneath its parent.
val above := this.nodes[a as u64].parent;
this.nodes[up as u64].left = a;
this.nodes[up as u64].parent = above;
this.nodes[a as u64].parent = up;
if above == none_node {
this.root = up;
} else if this.nodes[above as u64].left == a {
this.nodes[above as u64].left = up;
} else {
this.nodes[above as u64].right = up;
}
# `up` keeps its deeper child; `a` takes the shallower where `up` was.
val deeper := this.nodes[f as u64].height > this.nodes[g as u64].height ? f : g;
val shallower := deeper == f ? g : f;
this.nodes[up as u64].right = deeper;
if on_right {
this.nodes[a as u64].right = shallower;
} else {
this.nodes[a as u64].left = shallower;
}
this.nodes[shallower as u64].parent = a;
this.nodes[a as u64].box = this.nodes[other as u64].box.merged(this.nodes[shallower as u64].box);
this.nodes[a as u64].height = 1 + math::max(this.nodes[other as u64].height, this.nodes[shallower as u64].height);
this.nodes[up as u64].box = this.nodes[a as u64].box.merged(this.nodes[deeper as u64].box);
this.nodes[up as u64].height = 1 + math::max(this.nodes[a as u64].height, this.nodes[deeper as u64].height);
}