Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-30 13:26:21 -05:00
commit 80f851a1f6
34 files changed
+4606

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
#! Contains `aabb`, a box along the plane's axes, as what holds a shape, and
#! what an `aabb_tree` sorts.
import std::math;
import std::serial;
import linear;
module physics2d;
#! A box along the plane's axes, from its least corner to its greatest.
@serial
pub struct aabb {
@serial pub var min: vec2;
@serial pub var max: vec2;
}
#! The box of a middle, reaching so far each way.
pub def aabb::around(center: vec2, half: vec2): aabb {
return aabb{ center - half, center + half };
}
pub def aabb::equals(&this, other: &aabb): bool {
return this.min == other.min && this.max == other.max;
}
pub val aabb::center: vec2 {
get => (this.min + this.max) * 0.5;
}
#! How far it reaches each way from its middle.
pub val aabb::half_size: vec2 {
get => (this.max - this.min) * 0.5;
}
pub val aabb::size: vec2 {
get => this.max - this.min;
}
#! How far around it is, which an `aabb_tree` weighs where to put a box by.
pub val aabb::perimeter: f32 {
get => 2 * ((this.max.x - this.min.x) + (this.max.y - this.min.y));
}
#! Whether a place is within it, its edges among it.
pub def aabb::contains(&this, p: vec2): bool {
return p.x >= this.min.x && p.x <= this.max.x && p.y >= this.min.y && p.y <= this.max.y;
}
#! Whether it holds another box whole.
pub def aabb::encloses(&this, other: aabb): bool {
return other.min.x >= this.min.x && other.min.y >= this.min.y && other.max.x <= this.max.x && other.max.y <= this.max.y;
}
#! Whether it and another box meet, touching among it.
pub def aabb::overlaps(&this, other: aabb): bool {
return other.min.x <= this.max.x && other.max.x >= this.min.x && other.min.y <= this.max.y && other.max.y >= this.min.y;
}
#! The least box holding it and another.
pub def aabb::merged(&this, other: aabb): aabb {
return aabb{ this.min.min(other.min), this.max.max(other.max) };
}
#! It grown so far each way.
pub def aabb::grown(&this, by: f32): aabb {
return aabb{ this.min - vec2{ by, by }, this.max + vec2{ by, by } };
}
#! How far along a ray it's first met, from a place, along a direction, as far
#! as `reach` lengths of the direction: 0 where the place is within it.
pub def aabb::ray_hit(&this, origin: vec2, direction: vec2, reach: f32): maybe<f32> {
var low: f32 = 0;
var high := reach;
val origins: f32[2] = [origin.x, origin.y];
val ways: f32[2] = [direction.x, direction.y];
val lows: f32[2] = [this.min.x, this.min.y];
val highs: f32[2] = [this.max.x, this.max.y];
for i in 0..2u {
if math::abs(ways[i]) < tiny {
return nothing{} 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 nothing{} if low > high;
}
return low;
}
+262
View File
@@ -0,0 +1,262 @@
#! 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 hull, its points where its pose places them, with
#! its radius around them: a circle of one point, a capsule of two, a polygon
#! of its corners. Two circles meet as their middles near; a circle and a hull
#! as the circle's middle nears the hull's edges, or lies within it; and two
#! hulls by the edge of either that holds them furthest apart, as the
#! separating axis theorem finds it. Where their hulls overlap, or their round
#! sides near along a face, the other's nearest edge is clipped to that face,
#! as Box2D clips one, so a box resting flat on another meets it at two
#! points; where only their round sides meet, they meet at one, along the line
#! between the hulls' nearest points.
import std::math;
import linear;
module physics2d;
#! A point where two shapes meet: midway between their surfaces, and how deep
#! the one is within the other there, 0 where they touch.
pub struct contact {
pub var point: vec2;
pub var depth: f32;
}
#! 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 or two
#! points, as a box resting flat on another rests on two.
pub struct manifold {
pub var normal: vec2;
pub var points: contact[2];
pub var count: u32;
}
#! The deepest of its points.
pub val manifold::depth: f32 {
get => this.count == 0 ? 0f : this.count == 1 ? this.points[0].depth : math::max(this.points[0].depth, this.points[1].depth);
}
#! The manifold turned around, of the second shape against the first.
pub def manifold::flipped(&this): manifold {
return manifold{ normal = this.normal * -1f, points = this.points, count = this.count };
}
# A shape's points where its pose places it, and its edges' normals.
struct hull {
var points: vec2[8];
var normals: vec2[8];
var count: u32;
var radius: f32;
}
def hull_of(s: &shape, at: pose): hull {
var made := hull{ count = s.count, radius = s.radius };
for i in 0..s.count {
made.points[i] = at.apply(s.point(i));
made.normals[i] = at.turn.apply(s.normal(i));
}
return made;
}
#! 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.
pub def collide(a: &shape, at_a: pose, b: &shape, at_b: pose): maybe<manifold> {
val ha := hull_of(a, at_a);
val hb := hull_of(b, at_b);
if ha.count == 1 && hb.count == 1 {
return circles(ha.points[0], ha.radius, hb.points[0], hb.radius);
}
if hb.count == 1 {
return hull_and_circle(&ha, hb.points[0], hb.radius);
}
if ha.count == 1 {
if hull_and_circle(&hb, ha.points[0], ha.radius) is some(m) {
return m.flipped();
}
return nothing{};
}
return hulls(&ha, &hb);
}
#! 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 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: vec2, on_a: vec2, radius_a: f32, on_b: vec2, radius_b: f32, depth: f32): 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 };
return made;
}
def circles(a: vec2, ra: f32, b: vec2, rb: f32): maybe<manifold> {
val between := b - a;
val distance := between.length;
return nothing{} if distance > ra + rb;
val normal := distance > tiny ? between * (1 / distance) : vec2{ 0, 1 };
return one_point(normal, a, ra, b, rb, ra + rb - distance);
}
# A hull and a circle: within a polygon, pushed out by the face it's nearest;
# else by the hull's point nearest the circle's middle.
def hull_and_circle(h: &hull, c: vec2, radius: f32): maybe<manifold> {
val reach := h.radius + radius;
# The face the middle is furthest in front of.
var face: u32 = 0;
var separation := -1e30f;
for i in 0..h.count {
val s := h.normals[i].dot(c - h.points[i]);
if s > separation {
separation = s;
face = i;
}
}
return nothing{} if separation > reach;
if h.count >= 3 && separation <= 0 {
val n := h.normals[face];
return one_point(n, c - n * separation, h.radius, c, radius, reach - separation);
}
var nearest := h.points[0];
var best := 1e30f;
for i in 0..h.count {
val p := nearest_on_segment(c, h.points[i], h.points[(i + 1) % h.count]);
val d := (c - p).length_squared;
if d < best {
best = d;
nearest = p;
}
}
val distance := math::sqrt(best);
return nothing{} if distance > reach;
val normal := distance > tiny ? (c - nearest) * (1 / distance) : h.normals[face];
return one_point(normal, nearest, h.radius, c, radius, reach - distance);
}
# How far in front of a hull's edge another hull lies, of the edge that holds
# it furthest: the edge, and the distance, below 0 where they overlap.
struct apart {
var edge: u32;
var separation: f32;
}
def furthest_apart(from: &hull, other: &hull): apart {
var found := apart{ separation = -1e30f };
for i in 0..from.count {
val n := from.normals[i];
var least := 1e30f;
for j in 0..other.count {
least = math::min(least, n.dot(other.points[j] - from.points[i]));
}
if least > found.separation {
found = apart{ edge = i, separation = least };
}
}
return found;
}
# Two hulls of two or more points each.
def hulls(a: &hull, b: &hull): maybe<manifold> {
val reach := a.radius + b.radius;
val of_a := furthest_apart(a, b);
return nothing{} if of_a.separation > reach;
val of_b := furthest_apart(b, a);
return nothing{} if of_b.separation > reach;
# The face of the first is taken where it's as good, so the same pair gives
# the same face from one frame to the next.
val flip := of_b.separation > of_a.separation + 1e-4;
val reference := flip ? b : a;
val incident := flip ? a : b;
val face := flip ? of_b.edge : of_a.edge;
val separation := flip ? of_b.separation : of_a.separation;
if separation > 1e-4 && reach > 0 {
# Apart but for their round sides: they meet along the line between the
# hulls' nearest points, or along a face nearly that way.
var best := 1e30f;
var on_a := a.points[0];
var on_b := b.points[0];
for i in 0..edges_of(a) {
for j in 0..edges_of(b) {
val pair := nearest_of_segments(a.points[i], a.points[(i + 1) % a.count], b.points[j], b.points[(j + 1) % b.count]);
val d := (pair[1] - pair[0]).length_squared;
if d < best {
best = d;
on_a = pair[0];
on_b = pair[1];
}
}
}
val distance := math::sqrt(best);
return nothing{} if distance > reach;
val normal := (on_b - on_a) * (1 / distance);
val along_face := flip ? normal * -1f : normal;
if along_face.dot(reference.normals[face]) < 0.995 {
return one_point(normal, on_a, a.radius, on_b, b.radius, reach - distance);
}
}
return clipped(reference, incident, face, flip);
}
# How many distinct edges a hull has: a capsule's two are one segment.
def edges_of(h: &hull): u32 {
return h.count == 2 ? 1 : h.count;
}
# The incident hull's edge facing most against the reference face, clipped to
# the face's width: each point of it within reach of the face a contact.
def clipped(reference: &hull, incident: &hull, face: u32, flip: bool): maybe<manifold> {
val n := reference.normals[face];
val v1 := reference.points[face];
val v2 := reference.points[(face + 1) % reference.count];
var edge: u32 = 0;
var least := 1e30f;
for i in 0..incident.count {
val d := n.dot(incident.normals[i]);
if d < least {
least = d;
edge = i;
}
}
var points: vec2[2] = [incident.points[edge], incident.points[(edge + 1) % incident.count]];
val tangent := (v2 - v1).normalized();
var kept: u32 = 2;
kept = clip(&mut points, kept, tangent * -1f, -tangent.dot(v1));
return nothing{} if kept < 2;
kept = clip(&mut points, kept, tangent, tangent.dot(v2));
return nothing{} if kept < 2;
val reach := reference.radius + incident.radius;
var made := manifold{ normal = flip ? n * -1f : n };
for i in 0..2u {
val s := n.dot(points[i] - v1);
continue if s > reach;
# Midway between the reference's surface and the incident's.
val on_reference := points[i] - n * (s - reference.radius);
val on_incident := points[i] - n * incident.radius;
made.points[made.count] = contact{ point = (on_reference + on_incident) * 0.5, depth = reach - s };
made.count++;
}
return nothing{} if made.count == 0;
return made;
}
# Clips a segment to the side of a line where `normal.dot(p) <= offset`, as
# Sutherland and Hodgman clip, keeping two points where any of it is there.
def clip(points: &mut vec2[2], kept: u32, normal: vec2, offset: f32): u32 {
val d0 := normal.dot(points[0]) - offset;
val d1 := normal.dot(points[1]) - offset;
return 2 if d0 <= 0 && d1 <= 0;
return 0 if d0 > 0 && d1 > 0;
val t := d0 / (d0 - d1);
val crossing := points[0] + (points[1] - points[0]) * t;
if d0 > 0 {
points[0] = crossing;
} else {
points[1] = crossing;
}
return 2;
}
+194
View File
@@ -0,0 +1,194 @@
#! Contains `grid`: solid cells of a grid, as a tilemap's walls are, each a box
#! of the grid's cell size, from the grid's origin at the bottom left of its
#! first cell, x to the right and y up.
#!
#! A shape meets each solid cell as a box, but for the faces two solid cells
#! share: a manifold pushing the shape into a solid neighbor, along the axis
#! it pushes most, is passed over, so a body sliding along a floor of many
#! cells slides as along one, never caught on the seams between them.
import std::containers;
import std::math;
import linear;
module physics2d;
#! Solid cells of a grid, so many across and up.
pub struct grid {
#! How wide and high each cell is.
pub var cell := vec2{ 1, 1 };
var _width: u32;
var _height: u32;
var _solid: vector<u8>; # Each cell, a row at a time, from the bottom left.
}
#! A grid so many cells across and up, each so wide and high, none solid.
pub def grid::new(width: u32, height: u32, cell: vec2 = vec2{ 1, 1 }): grid {
var made := grid{ cell = cell, _width = width, _height = height, _solid = vector::<u8>::new() };
made._solid.resize(width as u64 * height as u64, 0);
return made;
}
pub val grid::width: u32 {
get => this._width;
}
pub val grid::height: u32 {
get => this._height;
}
#! Whether a cell is solid: none outside the grid is.
pub def grid::is_solid(&this, x: i64, y: i64): bool {
return false if x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64;
return this._solid[(y as u64) * this._width as u64 + x as u64] != 0;
}
#! Makes a cell solid, or not.
pub def grid::set(&mut this, x: u32, y: u32, solid: bool): void {
return if x >= this._width || y >= this._height;
this._solid[y as u64 * this._width as u64 + x as u64] = solid ? 1 : 0;
}
#! A cell's box, of the grid's own places.
pub def grid::box_of(&this, x: u32, y: u32): aabb {
val low := vec2{ x as f32 * this.cell.x, y as f32 * this.cell.y };
return aabb{ low, low + this.cell };
}
#! The box of all its cells, of its own places.
pub val grid::bounds: aabb {
get => aabb{ vec2::zero, vec2{ this._width as f32 * this.cell.x, this._height as f32 * this.cell.y } };
}
#! Visits each solid cell a box of the grid's own places meets, as
#! `visit(x, y)`, until it gives false.
pub def grid::cells_in<F>(&this, box: aabb, visit: F): void where F: invokable<def(u32, u32): bool> {
return if this._width == 0 || this._height == 0;
val x0 := math::max(math::floor(box.min.x / this.cell.x) as i64, 0);
val y0 := math::max(math::floor(box.min.y / this.cell.y) as i64, 0);
val x1 := math::min(math::floor(box.max.x / this.cell.x) as i64, this._width as i64 - 1);
val y1 := math::min(math::floor(box.max.y / this.cell.y) as i64, this._height as i64 - 1);
var y := y0;
while y <= y1 {
var x := x0;
while x <= x1 {
if this.is_solid(x, y) {
return if !visit(x as u32, y as u32);
}
x++;
}
y++;
}
}
#! Visits the manifold of a shape against each solid cell it meets, as
#! `visit(x, y, m)`, until it gives false: `at` places the grid, and `at_s`
#! the shape, and each manifold's normal is from the cell toward the shape,
#! of the plane's places. Those pushing the shape into a solid neighbor are
#! passed over.
pub def grid::collide<F>(&this, at: pose, s: &shape, at_s: pose, visit: F): void where F: invokable<def(u32, u32, manifold): bool> {
val local := at.unapply_pose(at_s);
val half := this.cell * 0.5;
this.cells_in(s.bounds(local), def(x: u32, y: u32): bool {
val box := shape::box(half, vec2{ (x as f32 + 0.5) * this.cell.x, (y as f32 + 0.5) * this.cell.y });
val found := collide(&box, pose::identity, s, local) else { return true; };
# Along the axis it pushes most, toward a solid neighbor, it's a face the
# two share.
val n := found.normal;
var nx: i64 = 0;
var ny: i64 = 0;
if math::abs(n.x) > math::abs(n.y) {
nx = n.x > 0 ? 1 : -1;
} else {
ny = n.y > 0 ? 1 : -1;
}
return true if this.is_solid(x as i64 + nx, y as i64 + ny);
var placed := manifold{ normal = at.turn.apply(n), count = found.count };
for i in 0..found.count {
placed.points[i] = contact{ point = at.apply(found.points[i].point), depth = found.points[i].depth };
}
return visit(x, y, placed);
});
}
#! Whether a shape meets any solid cell, `at` placing the grid and `at_s` the
#! shape, but where it only meets the faces solid cells share.
pub def grid::overlaps(&this, at: pose, s: &shape, at_s: pose): bool {
var met := false;
this.collide(at, s, at_s, def(x: u32, y: u32, m: manifold): bool {
met = true;
return false;
});
return met;
}
#! Where a ray met a grid: the hit, and the solid cell it met.
pub struct grid_hit {
pub var hit: ray_hit;
pub var x: u32;
pub var y: u32;
}
#! Where a ray first meets a solid cell, `at` placing the grid: from a place,
#! along a direction of length 1, as far as `reach`, passing from cell to cell
#! as Amanatides and Woo pass, the face it enters by its normal. A ray
#! beginning in a solid cell meets it at 0, facing back along the ray.
pub def grid::ray_cast(&this, at: pose, origin: vec2, direction: vec2, reach: f32): maybe<grid_hit> {
val o := at.unapply(origin);
val d := at.turn.unapply(direction);
val whole := this.bounds;
val start := whole.ray_hit(o, d, reach) else { return nothing{}; };
val p := o + d * start;
var x := math::clamp(math::floor(p.x / this.cell.x) as i64, 0, this._width as i64 - 1);
var y := math::clamp(math::floor(p.y / this.cell.y) as i64, 0, this._height as i64 - 1);
# The face of the grid it entered by, or none where it began within it.
var normal := d * -1f;
if start > 0 {
val gaps: f32[4] = [math::abs(p.x - whole.min.x), math::abs(p.x - whole.max.x), math::abs(p.y - whole.min.y), math::abs(p.y - whole.max.y)];
val faces: vec2[4] = [vec2{ -1, 0 }, vec2{ 1, 0 }, vec2{ 0, -1 }, vec2{ 0, 1 }];
var nearest: u64 = 0;
for i in 1..4u {
if gaps[i] < gaps[nearest] {
nearest = i;
}
}
normal = faces[nearest];
}
val step_x: i64 = d.x > 0 ? 1 : d.x < 0 ? -1 : 0;
val step_y: i64 = d.y > 0 ? 1 : d.y < 0 ? -1 : 0;
val across_x := step_x != 0 ? this.cell.x / math::abs(d.x) : 1e30f;
val across_y := step_y != 0 ? this.cell.y / math::abs(d.y) : 1e30f;
# How far along the ray, from its beginning, each next line of cells is.
var next_x := 1e30f;
var next_y := 1e30f;
if step_x > 0 {
next_x = ((x + 1) as f32 * this.cell.x - o.x) / d.x;
} else if step_x < 0 {
next_x = (x as f32 * this.cell.x - o.x) / d.x;
}
if step_y > 0 {
next_y = ((y + 1) as f32 * this.cell.y - o.y) / d.y;
} else if step_y < 0 {
next_y = (y as f32 * this.cell.y - o.y) / d.y;
}
var t := start;
while true {
if this.is_solid(x, y) {
return grid_hit{
hit = ray_hit{ distance = t, point = at.apply(o + d * t), normal = at.turn.apply(normal) }, x = x as u32, y = y as u32,
};
}
if next_x < next_y {
t = next_x;
next_x += across_x;
x += step_x;
normal = vec2{ -step_x as f32, 0 };
} else {
t = next_y;
next_y += across_y;
y += step_y;
normal = vec2{ 0, -step_y as f32 };
}
return nothing{} if t > reach || x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64;
}
return nothing{};
}
+69
View File
@@ -0,0 +1,69 @@
#! Contains `physics2d`: what collides in a plane, as a game of two dimensions
#! asks it. Shapes, circles, capsules, and convex polygons, 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 `grid` of solid cells, as a
#! tilemap's walls are, met as boxes, each but the faces it shares with a solid
#! neighbor, so a body slides along a floor of many cells as along one.
#!
#! The plane is `linear`'s x and y: x to the right, y up, and angles
#! counterclockwise, in radians. A polygon's corners are counterclockwise, and
#! each edge's normal faces out. A shape's surface is within it, so two shapes
#! touching meet, at a depth of 0.
#!
#! What this holds is collision alone: bodies that move by forces and push one
#! another apart come after, as `physics2d`'s solver.
import std::math;
import linear;
module physics2d;
# How near two numbers are taken as one, as lengths in a game's units are.
const tiny: f32 = 1e-6;
# The point of a segment nearest a place.
def nearest_on_segment(p: vec2, a: vec2, b: vec2): vec2 {
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: vec2, a2: vec2, b1: vec2, b2: vec2): vec2[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];
}
+91
View File
@@ -0,0 +1,91 @@
#! Contains `rot`, a rotation in the plane, and `pose`, where a body is and
#! which way it's turned, which places its shapes.
import std::math;
import std::serial;
import linear;
module physics2d;
#! A rotation in the plane, counterclockwise, as its angle's cosine and sine,
#! so turning a vector takes no trigonometry.
@serial
pub struct rot {
@serial pub var c: f32 = 1;
@serial pub var s: f32;
}
#! No rotation.
pub val rot::identity := rot{ 1, 0 };
#! A rotation by an angle, in radians, counterclockwise.
pub def rot::of(angle: f32): rot {
return rot{ math::cos(angle), math::sin(angle) };
}
#! Its angle, in radians, from -π to π.
pub val rot::angle: f32 {
get => math::atan2(this.s, this.c);
}
pub def rot::equals(&this, other: &rot): bool {
return this.c == other.c && this.s == other.s;
}
#! A vector turned by it.
pub def rot::apply(&this, v: vec2): vec2 {
return vec2{ this.c * v.x - this.s * v.y, this.s * v.x + this.c * v.y };
}
#! A vector turned back by it, as its inverse turns it.
pub def rot::unapply(&this, v: vec2): vec2 {
return vec2{ this.c * v.x + this.s * v.y, this.c * v.y - this.s * v.x };
}
#! It after another: turning by the product turns by `other`, then by this.
pub def rot::mul(&this, other: &rot): rot {
return rot{ this.c * other.c - this.s * other.s, this.s * other.c + this.c * other.s };
}
#! Where a body is in the plane, and which way it's turned: what a place of its
#! own, as its shapes' corners are, is in the plane.
@serial
pub struct pose {
@serial pub var at: vec2;
@serial pub var turn := rot::identity;
}
#! At the origin, unturned.
pub val pose::identity := pose{};
#! A pose at a place, turned by an angle, in radians, counterclockwise.
pub def pose::of(at: vec2, angle: f32 = 0): pose {
return pose{ at = at, turn = rot::of(angle) };
}
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 the plane.
pub def pose::apply(&this, local: vec2): vec2 {
return this.at + this.turn.apply(local);
}
#! Where a place of the plane is in the body's own.
pub def pose::unapply(&this, place: vec2): vec2 {
return this.turn.unapply(place - this.at);
}
#! 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 };
}
#! Another pose of the plane, 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 c := this.turn.c * other.turn.c + this.turn.s * other.turn.s;
val s := this.turn.c * other.turn.s - this.turn.s * other.turn.c;
return pose{ at = this.unapply(other.at), turn = rot{ c, s } };
}
+310
View File
@@ -0,0 +1,310 @@
#! Contains `shape`: a circle, a capsule, or a convex polygon, 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::containers;
import std::math;
import linear;
module physics2d;
#! The most corners a polygon has.
pub const max_corners: u32 = 8;
#! What a shape is.
pub enum shape_kind: u8 {
#! The places within its radius of its middle.
circle,
#! The places within its radius of a segment, between its two ends, as a
#! pill; of a radius of 0, the segment itself, as a thin wall.
capsule,
#! A convex polygon of three to eight corners.
polygon,
}
#! A shape of a body, about the body's origin, as a pose places it: a circle,
#! a capsule, or a convex polygon, each its points and a radius around them. A
#! circle is its middle, a capsule its two ends, and a polygon its corners,
#! counterclockwise, each edge's normal facing out.
pub struct shape {
var _kind: shape_kind;
var _radius: f32;
var _count: u32;
var _points: vec2[8];
var _normals: vec2[8]; # Of edge `i`, from point `i` to the next.
}
#! 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: vec2;
pub var normal: vec2;
}
#! A circle of a radius, about a middle, the body's origin at first.
pub def shape::circle(radius: f32, center: vec2 = vec2::zero): shape {
var made := shape{ _kind = shape_kind::circle, _radius = radius, _count = 1 };
made._points[0] = center;
return made;
}
#! A capsule of a radius about the segment between two places: a circle of
#! the radius, where they're one place.
pub def shape::capsule(a: vec2, b: vec2, radius: f32): shape {
return shape::circle(radius, a) if (b - a).length_squared <= tiny * tiny;
var made := shape{ _kind = shape_kind::capsule, _radius = radius, _count = 2 };
made._points[0] = a;
made._points[1] = b;
made.find_normals();
return made;
}
#! A capsule standing up, 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 circle.
pub def shape::pill(width: f32, height: f32, center: vec2 = vec2::zero): shape {
val radius := width / 2;
val reach := math::max(height / 2 - radius, 0f);
return shape::capsule(center - vec2{ 0, reach }, center + vec2{ 0, reach }, radius);
}
#! A segment between two places, of no thickness, as a capsule of no radius.
pub def shape::segment(a: vec2, b: vec2): shape {
return shape::capsule(a, b, 0);
}
#! A box reaching so far each way from its middle, turned by an angle, in
#! radians.
pub def shape::box(half: vec2, center: vec2 = vec2::zero, angle: f32 = 0): shape {
val turn := rot::of(angle);
var made := shape{ _kind = shape_kind::polygon, _count = 4 };
val corners: vec2[4] = [vec2{ -half.x, -half.y }, vec2{ half.x, -half.y }, vec2{ half.x, half.y }, vec2{ -half.x, half.y }];
for i in 0..4u {
made._points[i] = center + turn.apply(corners[i]);
}
made.find_normals();
return made;
}
#! The convex polygon around places, three to eight of its corners among
#! them: what's inside it and on its edges left out. Nothing where the places
#! hold no area, or their hull has more than eight corners.
pub def shape::polygon(places: span<vec2>): maybe<shape> {
var sorted := vector::<vec2>::new();
for i in 0..places.length {
sorted.append(places[i]);
}
sorted.sort_by(before_in_x);
# Andrew's monotone chain: the hull's lower half, left to right, then its
# upper, right to left, each corner turning left of the last two.
var hull := vector::<vec2>::new();
for i in 0..sorted.length {
while hull.length >= 2 && turning(hull[hull.length - 2], hull[hull.length - 1], sorted[i]) <= tiny {
hull.truncate();
}
hull.append(sorted[i]);
}
val lower := hull.length + 1;
var i := sorted.length;
while i > 1 {
i--;
val p := sorted[i - 1];
while hull.length >= lower && turning(hull[hull.length - 2], hull[hull.length - 1], p) <= tiny {
hull.truncate();
}
hull.append(p);
}
# Its last corner is its first again.
if hull.length > 0 {
hull.truncate();
}
return nothing{} if hull.length < 3 || hull.length > max_corners as u64;
var made := shape{ _kind = shape_kind::polygon, _count = hull.length as u32 };
for k in 0..hull.length {
made._points[k] = hull[k];
}
made.find_normals();
return made;
}
# Whether a place comes before another, left to right, then bottom to top.
def before_in_x(a: &vec2, b: &vec2): bool {
return a.x < b.x if a.x != b.x;
return a.y < b.y;
}
# Twice the area of the triangle of three places, positive where they turn
# counterclockwise.
def turning(a: vec2, b: vec2, c: vec2): f32 {
return (b - a).cross(c - a);
}
# Finds the normal of each edge: its direction turned a quarter clockwise,
# which faces out of corners counterclockwise.
def shape::find_normals(&mut this): void {
for i in 0..this._count {
val edge := this._points[(i + 1) % this._count] - this._points[i];
this._normals[i] = vec2{ edge.y, -edge.x }.normalized();
}
}
pub val shape::kind: shape_kind {
get => this._kind;
}
#! How far around its points it reaches: a circle's or a capsule's radius,
#! and none of a polygon.
pub val shape::radius: f32 {
get => this._radius;
}
#! How many points it's of: a circle 1, a capsule 2, and a polygon its
#! corners.
pub val shape::count: u32 {
get => this._count;
}
#! A point of it: a circle's middle, a capsule's end, or a polygon's corner.
pub def shape::point(&this, i: u32): vec2 {
return this._points[i];
}
#! The normal of an edge of a capsule or a polygon, from point `i` to the
#! next, facing out.
pub def shape::normal(&this, i: u32): vec2 {
return this._normals[i];
}
#! The box holding it, where a pose places it.
pub def shape::bounds(&this, at: pose): aabb {
var low := at.apply(this._points[0]);
var high := low;
for i in 1..this._count {
val p := at.apply(this._points[i]);
low = low.min(p);
high = high.max(p);
}
val r := vec2{ this._radius, this._radius };
return aabb{ low - r, high + r };
}
#! Whether it holds a place of the plane, where a pose places it, its surface
#! among it.
pub def shape::contains(&this, at: pose, p: vec2): bool {
val local := at.unapply(p);
if this._kind == shape_kind::circle {
return (local - this._points[0]).length_squared <= this._radius * this._radius;
}
if this._kind == shape_kind::capsule {
val nearest := nearest_on_segment(local, this._points[0], this._points[1]);
return (local - nearest).length_squared <= this._radius * this._radius;
}
for i in 0..this._count {
return false if this._normals[i].dot(local - this._points[i]) > 0;
}
return true;
}
#! 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: vec2, direction: vec2, reach: f32): maybe<ray_hit> {
val o := at.unapply(origin);
val d := at.turn.unapply(direction);
var found: maybe<ray_hit> = nothing{};
match this._kind {
circle => found = ray_circle(o, d, reach, this._points[0], this._radius);
capsule => found = ray_capsule(o, d, reach, this._points[0], this._points[1], this._radius);
polygon => found = this.ray_polygon(o, d, reach);
}
if found is some(hit) {
return ray_hit{ distance = hit.distance, point = at.apply(hit.point), normal = at.turn.apply(hit.normal) };
}
return nothing{};
}
# A ray, of the shape's own places, meeting a circle.
def ray_circle(o: vec2, d: vec2, reach: f32, center: vec2, 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 * -1f } 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 flat sides, where it meets them between its
# ends, else its round ends; or a segment, of no radius, from either side.
def ray_capsule(o: vec2, d: vec2, reach: f32, a: vec2, b: vec2, radius: f32): maybe<ray_hit> {
val nearest := nearest_on_segment(o, a, b);
if (o - nearest).length_squared <= radius * radius {
return ray_hit{ distance = 0, point = o, normal = d * -1f };
}
val along := (b - a).normalized();
val length := (b - a).length;
# The side facing the ray's beginning.
var side := along.perpendicular();
if side.dot(o - a) < 0 {
side = side * -1f;
}
val toward := d.dot(side);
var best: maybe<ray_hit> = nothing{};
if toward < 0 {
val t := (side.dot(o - a) - radius) / -toward;
if t >= 0 && t <= reach {
val p := o + d * t;
val s := (p - a).dot(along);
if s >= 0 && s <= length {
return ray_hit{ distance = t, point = p, normal = side };
}
}
}
return nothing{} if radius <= 0;
val first := ray_circle(o, d, reach, a, radius);
val second := ray_circle(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 polygon, clipped by each edge'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 polygon.
def shape::ray_polygon(&this, o: vec2, d: vec2, reach: f32): maybe<ray_hit> {
var lower: f32 = 0;
var upper := reach;
var entered: i64 = -1;
for i in 0..this._count {
val n := this._normals[i];
val numerator := n.dot(this._points[i] - 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 = i as i64;
} else if denominator > 0 && t < upper {
upper = t;
}
return nothing{} if upper < lower;
}
return ray_hit{ distance = 0, point = o, normal = d * -1f } if entered < 0;
return ray_hit{ distance = lower, point = o + d * lower, normal = this._normals[entered as u32] };
}
+340
View File
@@ -0,0 +1,340 @@
#! 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 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 linear;
module physics2d;
# 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: aabb;
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: aabb, data: u64): u32 {
val leaf := this.allocate();
this.nodes[leaf as u64].box = box.grown(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: aabb): bool {
return false if this.nodes[leaf as u64].box.encloses(box);
this.remove_leaf(leaf);
this.nodes[leaf as u64].box = box.grown(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): aabb {
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: aabb, 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: vec2, direction: vec2, 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 this.nodes[index].box.ray_hit(origin, direction, far) is none;
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 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: aabb): f32 {
val node := &this.nodes[child as u64];
val merged := box.merged(node.box).perimeter;
return merged if node.left == none_node;
return merged - node.box.perimeter;
}
# 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 := node_box.merged(box).perimeter;
# 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 - node_box.perimeter);
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);
}