#! Contains how a space solves a step, as Box2D's soft step solves one: in #! substeps, each of which moves velocities by forces, pushes apart what meets, #! softly, moves the bodies, and pushes again without undoing overlaps; then #! bounces what met fast enough, and keeps each contact's impulses for the #! next step to begin with. #! #! A contact pushes as a stiff, damped spring of the space's frequency, so an #! overlap is undone over a few substeps, no faster than the push speed, and a #! stack doesn't jitter. Points apart within the speculative margin push only #! as much as would close the gap in a substep, so what falls stops at what's #! below it rather than in it. import std::containers; import std::math; import malunal::linear; module malunal::physics2d; # How soft a constraint is, as a damped spring of a frequency is: how much of # its error it undoes each second, and how much of its impulse it gives. struct softness { var bias_rate: f32; var mass_scale: f32 = 1; var impulse_scale: f32; } def soft_of(hertz: f32, damping: f32, h: f32): softness { return softness{} if hertz == 0; val omega := 2 * math::pi as f32 * hertz; val a1 := 2 * damping + h * omega; val a2 := h * omega * a1; val a3 := 1 / (1 + a2); return softness{ bias_rate = omega / a1, mass_scale = a2 * a3, impulse_scale = a3 }; } # A body as a step moves it: its velocities, and how far its center has moved # and it has turned since the step began. It's eight numbers, which # `wide_contact`'s lanes gather by where each begins. struct body_state { var v: vec2; var w: f32; var pad: f32; var dp: vec2; var dq: rot; } # How a body's velocities change each substep: by its forces and gravity, and # what its damping keeps of them. struct body_motion { var dv: vec2; var dw: f32; var linear_keep: f32 = 1; var angular_keep: f32 = 1; } # A point of a contact as the solver pushes at it: where it is from each # body's center, how far apart the two are there but for how far they've # moved, and the impulses pushing them apart and along. struct point_constraint { var anchor_a: vec2; var anchor_b: vec2; var base_separation: f32; var normal_impulse: f32; var tangent_impulse: f32; var max_impulse: f32; var normal_mass: f32; var tangent_mass: f32; var relative_velocity: f32; } struct contact_constraint { var a: u32; # States. var b: u32; var contact: u32; var normal: vec2; var friction: f32; var restitution: f32; var ma: f32; var ia: f32; var mb: f32; var ib: f32; var soft: softness; var count: u32; var points: point_constraint[2]; } # What a step works in, kept from one to the next so it isn't made anew: the # first state is of what doesn't move. struct solver_scratch { var states: vector; var motions: vector; var bodies: vector; var constraints: vector; var joints: vector; # Joints of a moving body. var joint_soft: softness; var wide: vector; var overflow: vector; # Constraints of no color. var colored: vector; # Each color's bodies, a bit each. var color_of: vector; var color_groups: u32[25]; # Where each color's lanes begin. } # The most a body turns in a substep, a quarter of a half turn, so a fast spin # doesn't skip through what it meets. const most_turn: f32 = 0.25 * 3.14159265; # A rotation turned further by an angle, kept of length 1. def turned(q: rot, angle: f32): rot { val c := q.c - angle * q.s; val s := q.s + angle * q.c; val length := math::sqrt(c * c + s * s); return length > 0 ? rot{ c / length, s / length } : rot::identity; } # The velocity of a place a body turning at `w` is `r` from its center of. def spun(w: f32, r: vec2): vec2 { return vec2{ -w * r.y, w * r.x }; } def space::solve(&mut this, dt: f32): void { val n: u32 = this.substeps > 0 ? this.substeps : 1; val h := dt / n as f32; val inv_h := 1 / h; var s := move(this.solver); this.gather(&mut s, h); this.prepare_contacts(&mut s, h); this.prepare_joints(&mut s, h); color_contacts(&mut s); val max_spin := most_turn * inv_h; for i in 0..n { integrate_velocities(&mut s, this.max_speed, max_spin); this.warm_joints(&mut s); warm_wide(&mut s); warm_contacts(&mut s); this.solve_joints(&mut s, h, true); solve_wide(&mut s, inv_h, this.push_speed, true); solve_contacts(&mut s, inv_h, this.push_speed, true); integrate_positions(&mut s, h); this.solve_joints(&mut s, h, false); solve_wide(&mut s, inv_h, this.push_speed, false); solve_contacts(&mut s, inv_h, this.push_speed, false); } unpack_contacts(&mut s); bounce(&mut s, this.restitution_threshold); this.keep_impulses(&s); this.finish(&s, dt); this.solver = move(s); } # Gives each moving body a state, and how its forces move it each substep. def space::gather(&mut this, s: &mut solver_scratch, h: f32): void { s.states.clear(); s.motions.clear(); s.bodies.clear(); s.states.append(body_state{}); s.motions.append(body_motion{}); s.bodies.append(none); for b in 0..this.bodies.length { if !this.bodies[b].alive || !this.moves(b as u32) { this.bodies[b].slot = 0; continue; } this.bodies[b].slot = s.states.length as u32; val body := &this.bodies[b]; s.states.append(body_state{ v = body.velocity, w = body.spin }); if body.kind == body_kind::dynamic { s.motions.append(body_motion{ dv = (this.gravity * body.gravity_scale + body.force * body.inv_mass) * h, dw = h * body.inv_inertia * body.torque, linear_keep = 1 / (1 + h * body.linear_damping), angular_keep = 1 / (1 + h * body.angular_damping), }); } else { s.motions.append(body_motion{}); } s.bodies.append(b as u32); } } def space::prepare_contacts(&this, s: &mut solver_scratch, h: f32): void { s.constraints.clear(); val hertz := math::min(this.contact_hertz, 0.25 / h); val soft := soft_of(hertz, this.contact_damping, h); # Against what doesn't move, twice as stiff. val stiff := soft_of(2 * hertz, this.contact_damping, h); for k in 0..this.contacts.length { val c := &this.contacts[k]; continue if !c.alive || !c.touching; val a := &this.bodies[c.body_a as u64]; val b := &this.bodies[c.body_b as u64]; continue if a.slot == 0 && b.slot == 0; val n := c.manifold.normal; val t := vec2{ n.y, -n.x }; var made := contact_constraint{ a = a.slot, b = b.slot, contact = k as u32, normal = n, friction = c.friction, restitution = c.restitution, ma = a.inv_mass, ia = a.inv_inertia, mb = b.inv_mass, ib = b.inv_inertia, soft = a.inv_mass == 0 || b.inv_mass == 0 ? stiff : soft, count = c.manifold.count, }; for j in 0..c.manifold.count { val mp := &c.manifold.points[j]; val ra := mp.point - a.center; val rb := mp.point - b.center; val rna := ra.cross(n); val rnb := rb.cross(n); val kn := made.ma + made.mb + made.ia * rna * rna + made.ib * rnb * rnb; val rta := ra.cross(t); val rtb := rb.cross(t); val kt := made.ma + made.mb + made.ia * rta * rta + made.ib * rtb * rtb; val vra := a.velocity + spun(a.spin, ra); val vrb := b.velocity + spun(b.spin, rb); made.points[j] = point_constraint{ anchor_a = ra, anchor_b = rb, base_separation = -mp.depth - (rb - ra).dot(n), normal_impulse = c.normal_impulse[j], tangent_impulse = c.tangent_impulse[j], normal_mass = kn > 0 ? 1 / kn : 0f, tangent_mass = kt > 0 ? 1 / kt : 0f, relative_velocity = n.dot(vrb - vra), }; } s.constraints.append(made); } } def integrate_velocities(s: &mut solver_scratch, max_speed: f32, max_spin: f32): void { for i in 1..s.states.length { val m := &s.motions[i]; val st := &mut s.states[i]; var v := st.v * m.linear_keep + m.dv; var w := st.w * m.angular_keep + m.dw; val speed_squared := v.length_squared; if speed_squared > max_speed * max_speed { v = v * (max_speed / math::sqrt(speed_squared)); } if w * w > max_spin * max_spin { w = w * (max_spin / math::abs(w)); } st.v = v; st.w = w; } } def integrate_positions(s: &mut solver_scratch, h: f32): void { for i in 1..s.states.length { val st := &mut s.states[i]; st.dq = turned(st.dq, h * st.w); st.dp = st.dp + st.v * h; } } # Of the contacts of no color, one at a time. def warm_contacts(s: &mut solver_scratch): void { for o in 0..s.overflow.length { val c := &s.constraints[s.overflow[o] as u64]; var va := s.states[c.a as u64].v; var wa := s.states[c.a as u64].w; var vb := s.states[c.b as u64].v; var wb := s.states[c.b as u64].w; val n := c.normal; val t := vec2{ n.y, -n.x }; for j in 0..c.count { val cp := &c.points[j]; val p := n * cp.normal_impulse + t * cp.tangent_impulse; wa -= c.ia * cp.anchor_a.cross(p); va = va - p * c.ma; wb += c.ib * cp.anchor_b.cross(p); vb = vb + p * c.mb; } s.states[c.a as u64].v = va; s.states[c.a as u64].w = wa; s.states[c.b as u64].v = vb; s.states[c.b as u64].w = wb; } } # Worked a number at a time rather than as `vec2`s: sakurac keeps numbers in # registers, where it passes small vectors through memory, which made this, # the hottest loop of a step, several times slower. def solve_contacts(s: &mut solver_scratch, inv_h: f32, push: f32, use_bias: bool): void { val states := s.states.slice(); val constraints := s.constraints.slice(); for o in 0..s.overflow.length { val c := &mut constraints[s.overflow[o] as u64]; val a := c.a as u64; val b := c.b as u64; var vax := states[a].v.x; var vay := states[a].v.y; var wa := states[a].w; var vbx := states[b].v.x; var vby := states[b].v.y; var wb := states[b].w; val dpx := states[b].dp.x - states[a].dp.x; val dpy := states[b].dp.y - states[a].dp.y; val qac := states[a].dq.c; val qas := states[a].dq.s; val qbc := states[b].dq.c; val qbs := states[b].dq.s; val nx := c.normal.x; val ny := c.normal.y; val ma := c.ma; val ia := c.ia; val mb := c.mb; val ib := c.ib; for j in 0..c.count { val cp := &mut c.points[j]; val rax := cp.anchor_a.x; val ray := cp.anchor_a.y; val rbx := cp.anchor_b.x; val rby := cp.anchor_b.y; # How far apart they are now: as they began, and as far as each anchor # has moved and turned since. val dx := dpx + (qbc * rbx - qbs * rby) - (qac * rax - qas * ray); val dy := dpy + (qbs * rbx + qbc * rby) - (qas * rax + qac * ray); val separation := dx * nx + dy * ny + cp.base_separation; var bias: f32 = 0; var mass_scale: f32 = 1; var impulse_scale: f32 = 0; if separation > 0 { # Apart: only what closes the gap this substep. bias = separation * inv_h; } else if use_bias { bias = c.soft.bias_rate * separation; if bias < -push { bias = -push; } mass_scale = c.soft.mass_scale; impulse_scale = c.soft.impulse_scale; } val vn := (vbx - wb * rby - vax + wa * ray) * nx + (vby + wb * rbx - vay - wa * rax) * ny; val before := cp.normal_impulse; var sum := before - cp.normal_mass * mass_scale * (vn + bias) - impulse_scale * before; if sum < 0 { sum = 0; } val impulse := sum - before; cp.normal_impulse = sum; if impulse > cp.max_impulse { cp.max_impulse = impulse; } val px := nx * impulse; val py := ny * impulse; vax -= px * ma; vay -= py * ma; wa -= ia * (rax * py - ray * px); vbx += px * mb; vby += py * mb; wb += ib * (rbx * py - rby * px); } # Friction, of no more than its share of what pushes them apart, along # the tangent: the normal turned a quarter clockwise. val tx := ny; val ty := -nx; for j in 0..c.count { val cp := &mut c.points[j]; val rax := cp.anchor_a.x; val ray := cp.anchor_a.y; val rbx := cp.anchor_b.x; val rby := cp.anchor_b.y; val vt := (vbx - wb * rby - vax + wa * ray) * tx + (vby + wb * rbx - vay - wa * rax) * ty; val most := c.friction * cp.normal_impulse; val before := cp.tangent_impulse; var sum := before - cp.tangent_mass * vt; if sum > most { sum = most; } else if sum < -most { sum = -most; } val impulse := sum - before; cp.tangent_impulse = sum; val px := tx * impulse; val py := ty * impulse; vax -= px * ma; vay -= py * ma; wa -= ia * (rax * py - ray * px); vbx += px * mb; vby += py * mb; wb += ib * (rbx * py - rby * px); } states[a].v.x = vax; states[a].v.y = vay; states[a].w = wa; states[b].v.x = vbx; states[b].v.y = vby; states[b].w = wb; } } # Bounces what met faster than the threshold, as much as its restitution # keeps of how fast it met: only at points that pushed, so a speculative # point that never closed doesn't bounce. def bounce(s: &mut solver_scratch, threshold: f32): void { for i in 0..s.constraints.length { val c := &mut s.constraints[i]; continue if c.restitution == 0; var va := s.states[c.a as u64].v; var wa := s.states[c.a as u64].w; var vb := s.states[c.b as u64].v; var wb := s.states[c.b as u64].w; val n := c.normal; for j in 0..c.count { val cp := &mut c.points[j]; continue if cp.relative_velocity > -threshold || cp.max_impulse == 0; val ra := cp.anchor_a; val rb := cp.anchor_b; val vn := (vb + spun(wb, rb) - va - spun(wa, ra)).dot(n); var impulse := -cp.normal_mass * (vn + c.restitution * cp.relative_velocity); val sum := math::max(cp.normal_impulse + impulse, 0f); impulse = sum - cp.normal_impulse; cp.normal_impulse = sum; cp.max_impulse = math::max(cp.max_impulse, impulse); val p := n * impulse; va = va - p * c.ma; wa -= c.ia * ra.cross(p); vb = vb + p * c.mb; wb += c.ib * rb.cross(p); } s.states[c.a as u64].v = va; s.states[c.a as u64].w = wa; s.states[c.b as u64].v = vb; s.states[c.b as u64].w = wb; } } def space::keep_impulses(&mut this, s: &solver_scratch): void { for i in 0..s.constraints.length { val c := &s.constraints[i]; for j in 0..c.count { this.contacts[c.contact as u64].normal_impulse[j] = c.points[j].normal_impulse; this.contacts[c.contact as u64].tangent_impulse[j] = c.points[j].tangent_impulse; } } } # Puts each moving body where its state moved it, its colliders' leaves with # it, and times how long it's been still. def space::finish(&mut this, s: &solver_scratch, dt: f32): void { val still := 0.05 * this.unit; for i in 1..s.states.length { val b := s.bodies[i] as u64; val st := &s.states[i]; val center := this.bodies[b].center + st.dp; val turn := normalized(st.dq * this.bodies[b].at.turn); this.bodies[b].center = center; this.bodies[b].at = pose{ at = center - turn.apply(this.bodies[b].local_center), turn = turn }; this.bodies[b].velocity = st.v; this.bodies[b].spin = st.w; this.bodies[b].force = vec2::zero; this.bodies[b].torque = 0; val speed := st.v.length + math::abs(st.w) * this.bodies[b].extent; if !this.bodies[b].can_sleep || speed > still { this.bodies[b].sleep_time = 0; } else { this.bodies[b].sleep_time += dt; } this.place_colliders(b as u32); } } # A rotation kept of length 1. def normalized(q: rot): rot { val length := math::sqrt(q.c * q.c + q.s * q.s); return length > 0 ? rot{ q.c / length, q.s / length } : rot::identity; }