#! 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, or one # a sensor and the other not static, 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()); if !this.bodies[ca.body as u64].is_dynamic() && !this.bodies[cb.body as u64].is_dynamic() { # A sensor meets what moves into it, kinematic as well as dynamic, but two # standing still never meet. return false if !ca.made.sensor && !cb.made.sensor; return false if this.bodies[ca.body as u64].kind == body_kind::static && this.bodies[cb.body as u64].kind == body_kind::static; } 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; } # Where a pair's shapes meet: as the crew found it, where the step is solved on # several threads, else found now. def space::pair_manifold(&this, p: u32): manifold { return this.found[p as u64] if this.threads > 1; return this.manifold_of(this.pairs[p as u64].a, this.pairs[p as u64].b, this.speculative); } # Finds where each pair of two shapes meets, on the crew, a block of pairs to # each thread, as none needs another's: what it finds is put to use one pair at # a time after, so a step gives the same on any number of threads. def space::find_manifolds(&mut this): void { this.found.clear(); this.found.resize(this.pairs.length, manifold{}); var job := pairs_job{ space = address(this) }; val block := math::max(this.pairs.length / (this.threads as u64 * 8), 16u); this.crew.run(run_pairs, address(&mut job) as *mut u8, this.pairs.length, block); } struct pairs_job { var space: *mut space; } def run_pairs(context: *mut u8, begin: u64, end: u64): void { val job := &through(context as *mut pairs_job); val s := &mut through(job.space); for p in begin..end { val pair := &s.pairs[p]; continue if !pair.alive || pair.sensor || pair.mesh; val ca := &s.colliders[pair.a as u64]; val cb := &s.colliders[pair.b as u64]; continue if !s.moves(ca.body) && !s.moves(cb.body); continue if !s.tree.box_of(ca.leaf).overlaps(s.tree.box_of(cb.leaf)); s.found[p] = s.manifold_of(pair.a, pair.b, s.speculative); } } # Finds where each pair of a moving body meets, dropping those whose grown # boxes no longer meet. def space::update_contacts(&mut this): void { if this.threads > 1 { this.find_manifolds(); } 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.pair_manifold(p as u32)); } if touching != this.pairs[p].touching { this.pairs[p].touching = touching; this.note(p as u32, touching); if touching && !this.pairs[p].sensor { this.note_hit(p as u32); } } 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; } #! Two colliders that began touching in a step faster than the space's #! `hit_speed`, as something landing does: which, where, the normal from the #! first toward the second, and how fast they met along it, as a sound of it #! might be loud. pub struct hit_event { pub var a: collider_id; pub var b: collider_id; pub var point: vec3; pub var normal: vec3; pub var speed: f32; } #! The hits of the last step. pub def space::hits(&this): span { return this.struck.span; } # How fast a body's place moves, of a place of space. def space::speed_at(&this, index: u32, at: vec3): vec3 { val b := &this.bodies[index as u64]; val r := at - b.center; return b.velocity + b.spin.cross(r); } # Notes how hard a pair that began touching met, where it met faster than the # hit speed: at its first point, as the step began. def space::note_hit(&mut this, p: u32): void { var k := this.pairs[p as u64].contacts; while k != none && this.contacts[k as u64].manifold.count == 0 { k = this.contacts[k as u64].next; } return if k == none; val c := &this.contacts[k as u64]; val point := c.manifold.points[0].point; val n := c.manifold.normal; val speed := -n.dot(this.speed_at(c.body_b, point) - this.speed_at(c.body_a, point)); return if speed < this.hit_speed; val a := this.pairs[p as u64].a; val b := this.pairs[p as u64].b; this.struck.append(hit_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 }, point = point, normal = n, speed = speed, }); } #! Visits each pair of colliders touching as the last step left them, a #! sensor's among them where it overlaps what it meets, as `visit(a, b, #! sensor)`, until it gives false: what began and stopped touching since a #! step before, by what it visited then, however colliders were taken away #! and attached between. pub def space::each_touching(&this, visit: F): void where F: invokable { for p in 0..this.pairs.length { val pair := &this.pairs[p]; continue if !pair.alive || !pair.touching; return if !visit(this.named(pair.a), this.named(pair.b), pair.sensor); } } #! Visits each point of each contact touching, as `visit(a, b, point, normal, #! depth)`, of its two colliders, its normal from the first toward the #! second, until it gives false, as gizmos draw them. pub def space::each_contact(&this, visit: F): void where F: invokable { for k in 0..this.contacts.length { val c := &this.contacts[k]; continue if !c.alive || !c.touching; val pair := &this.pairs[c.pair as u64]; val a := collider_id{ index = pair.a, generation = this.colliders[pair.a as u64].generation }; val b := collider_id{ index = pair.b, generation = this.colliders[pair.b as u64].generation }; for i in 0..c.manifold.count { return if !visit(a, b, c.manifold.points[i].point, c.manifold.normal, c.manifold.points[i].depth); } } }