Files
physics/physics2d/shape.sakura
T
2026-10-30 21:59:14 -05:00

311 lines
10 KiB
Plaintext

#! 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 malunal::linear;
module malunal::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] };
}