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

282 lines
10 KiB
Plaintext

#! 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;
}