Files
physics/physics2d/space.sakura
T
2026-10-30 23:21:01 -05:00

517 lines
19 KiB
Plaintext

#! 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 Box2D's world steps them.
#!
#! 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; 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, as pixels, is made with how many units a
#! meter is, so a tolerance of 5 millimeters stays 5 millimeters.
import std::containers;
import std::math;
import std::time;
import malunal::linear;
module malunal::physics2d;
#! 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 := vec2{ 0, -10 };
#! 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;
var unit: f32 = 1;
var bodies: vector<body_record>;
var colliders: vector<collider_record>;
var grids: vector<grid>;
var free_grids: vector<u32>;
var met: vector<met_cell>;
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_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>; # Colliders whose leaves moved.
var near: vector<u32>;
var noted: vector<contact_event>;
var solver: solver_scratch;
var islands: vector<u32>;
#! How long the last step took, and each of its parts.
pub var profile: step_profile;
}
#! 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: vec2 = vec2{ 0, -10 }, 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 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;
this.bodies[index as u64] = body_record{
kind = made.kind, generation = generation, alive = true, at = made.at, center = made.at.at,
velocity = made.kind == body_kind::static ? vec2::zero : made.velocity, spin = made.kind == body_kind::static ? 0f : made.spin,
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);
# Those it sleeps with wake, as what held them may be gone.
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 a grid's solid cells, as a tilemap's walls, met as
#! boxes, each but the faces it shares with a solid neighbor, so what slides
#! along a floor of many cells slides as along one. Its shape and density are
#! passed over; a grid meets shapes, not another grid.
pub def space::attach_grid(&mut this, to: body_id, cells: grid, made: collider): collider_id {
var held := move(cells);
return collider_id{} if !this.has(to);
var g: u32 = 0;
if this.free_grids.length > 0 {
g = this.free_grids[this.free_grids.length - 1];
this.free_grids.truncate();
this.grids[g as u64] = move(held);
} else {
g = this.grids.length as u32;
this.grids.append(move(held));
}
return this.attach_record(to, collider_record{ made = made, grid = g, 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): aabb {
val record := &this.colliders[c as u64];
return record.made.shape.bounds(at) if !record.is_grid();
val own := this.grids[record.grid as u64].bounds;
val corners: vec2[4] = [own.min, vec2{ own.max.x, own.min.y }, own.max, vec2{ own.min.x, own.max.y }];
var low := at.apply(corners[0]);
var high := low;
for k in 1..4u {
val p := at.apply(corners[k]);
low = low.min(p);
high = high.max(p);
}
return aabb{ low, high };
}
#! 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;
# Unlinked from its body's colliders.
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, 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_grid() {
val g := this.colliders[c as u64].grid;
this.grids[g as u64] = grid::new(0, 0);
this.free_grids.append(g);
}
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): vec2 {
return this.bodies[id.index as u64].velocity;
}
pub def space::spin_of(&this, id: body_id): f32 {
return this.bodies[id.index as u64].spin;
}
#! A body's mass, its center of its own places, and its rotational inertia
#! 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 the plane.
pub def space::center_of(&this, id: body_id): vec2 {
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: vec2): 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: f32): 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 != 0 {
this.wake_body(id.index);
}
}
#! Pushes a dynamic body through the next step by a force at a place of the
#! plane, which turns it too where that's off its center, waking it.
pub def space::apply_force(&mut this, id: body_id, force: vec2, at: vec2): 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 += (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: vec2): 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: f32): void {
return if !this.has(id) || !this.bodies[id.index as u64].is_dynamic();
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 the plane does, waking it.
pub def space::apply_impulse(&mut this, id: body_id, impulse: vec2, at: vec2): 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].inv_inertia * (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);
}
}
# 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 made := &this.colliders[c as u64].made;
if !this.colliders[c as u64].is_grid() && made.density > 0 {
sum = sum.add(made.shape.mass(made.density));
}
c = this.colliders[c as u64].next;
}
}
var mass: f32 = 0;
var inertia: f32 = 0;
var local := vec2::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.inertia > 0 && !this.bodies[b as u64].fixed_rotation {
inertia = sum.inertia;
}
}
var extent: f32 = 0;
var c := this.bodies[b as u64].colliders;
while c != none {
val s := &this.colliders[c as u64].made.shape;
if !this.colliders[c as u64].is_grid() {
for i in 0..s.count {
extent = math::max(extent, (s.point(i) - local).length + s.radius);
}
}
c = this.colliders[c as u64].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 = inertia > 0 ? 1 / inertia : 0f;
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;
}
}
#! Where a ray met a space's collider: which, of which body, and where.
pub struct space_hit {
pub var collider: collider_id;
pub var body: body_id;
pub var distance: f32;
pub var point: vec2;
pub var normal: vec2;
}
#! 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: vec2, direction: vec2, 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;
var met := ray_hit{};
if c.is_grid() {
val cell := this.grids[c.grid as u64].ray_cast(at, origin, direction, so_far) else { return so_far; };
met = cell.hit;
} else {
met = c.made.shape.ray_cast(at, origin, direction, so_far) else { return so_far; };
}
best = space_hit{
collider = collider_id{ index = data as u32, generation = c.generation },
body = body_id{ index = c.body, generation = this.bodies[c.body as u64].generation },
distance = met.distance, point = met.point, normal = met.normal,
};
return met.distance;
});
return best;
}
#! 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),
};
}
#! 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;
}
def milliseconds(d: duration): f64 {
return d.in_nanoseconds as f64 / 1e6;
}