Stacking, Iterations and Sleeping
A single contact is easy: the impulse formula gives the exact answer. A stack of ten crates has ten contacts, and they all depend on each other: the bottom contact must hold the weight of everything above it, but it only "knows" that once the contacts above have pushed down on it. Solving them all exactly at once is a large linear system (a linear complementarity problem), too slow for games. Engines solve it approximately and iteratively instead, and the quality of stacks is the most visible measure of how good a physics engine is.
Sequential impulses
The method used by Box2D, Jolt, PhysX's default solver, Bullet and most hobby engines is sequential impulses (projected Gauss-Seidel):
- Apply gravity and other forces to the velocities.
- Loop over all contacts and solve each one on its own, as if it were the only one, applying the impulse immediately so the next contact sees the updated velocities.
- Repeat step 2 for N iterations. Each pass spreads the information one contact further through the stack.
- Integrate positions with the corrected velocities.
Two details make this converge to a stable stack:
- Accumulated impulse clamping. A contact may only push (
jn ≥ 0), but a single iteration's correction can be negative. The solver keeps the total impulse of each contact across iterations and clamps the total, not the increment:newTotal = max(total + delta, 0), then appliesnewTotal − total. Clamping each increment separately can never take back an impulse that turned out too large in an earlier iteration. - Warm starting. Contacts that persist from the last step (matched by the pair of bodies and the feature IDs of the contact points) start with last step's accumulated impulse instead of zero. A resting stack needs nearly the same impulses every step, so the solver begins close to the answer.
The program below solves a column of ten boxes with 1 to 32 iterations, with and without warm starting, and reports how far the top box has sunk after 3 seconds and how fast anything is still moving. (The slop is only 1 mm, so sinking is easy to see.)
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
// A column of boxes (1 m tall, 1 kg) resting on static ground. 1D: only vertical motion.
struct Result { double sink, maxSpeed; };
Result simulate(int boxes, int iterations, bool warmStart) {
const double g = 9.81, dt = 1.0 / 60, beta = 0.2, slop = 0.001;
std::vector<double> y(boxes), v(boxes, 0.0), acc(boxes, 0.0); // acc[i]: impulse of contact below box i
for (int i = 0; i < boxes; i++) y[i] = i; // bottom of box i
double maxSpeed = 0;
for (int step = 0; step < 180; step++) {
for (double& vi : v) vi -= g * dt;
if (warmStart) { // reapply last step's impulses
for (int i = 0; i < boxes; i++) { v[i] += acc[i]; if (i > 0) v[i - 1] -= acc[i]; }
} else std::fill(acc.begin(), acc.end(), 0.0);
for (int it = 0; it < iterations; it++) {
for (int i = 0; i < boxes; i++) { // contact under box i (bottom to top)
double below = i == 0 ? 0.0 : y[i - 1] + 1;
double depth = below - y[i];
double vBelow = i == 0 ? 0.0 : v[i - 1];
double invBelow = i == 0 ? 0.0 : 1.0;
double vn = v[i] - vBelow;
double bias = beta / dt * std::max(depth - slop, 0.0);
double lambda = -(vn - bias) / (1.0 + invBelow);
double newAcc = std::max(acc[i] + lambda, 0.0); // total impulse may only push
lambda = newAcc - acc[i];
acc[i] = newAcc;
v[i] += lambda;
if (i > 0) v[i - 1] -= lambda * invBelow;
}
}
for (int i = 0; i < boxes; i++) y[i] += v[i] * dt;
if (step >= 120) for (double vi : v) maxSpeed = std::max(maxSpeed, std::fabs(vi));
}
return {double(boxes - 1) - y[boxes - 1], maxSpeed}; // how far the top box sank
}
int main() {
std::cout << std::fixed << std::setprecision(3);
std::cout << "10 boxes, after 3 s | cold start | warm start\n";
std::cout << "iterations | top sank max speed | top sank max speed\n";
for (int it : {1, 2, 4, 8, 16, 32}) {
Result c = simulate(10, it, false), w = simulate(10, it, true);
std::cout << std::setw(10) << it << " | " << std::setw(7) << c.sink << " m " << std::setw(7) << c.maxSpeed
<< " m/s | " << std::setw(7) << w.sink << " m " << std::setw(7) << w.maxSpeed << " m/s\n";
}
}10 boxes, after 3 s | cold start | warm start
iterations | top sank max speed | top sank max speed
1 | 0.556 m 0.521 m/s | -0.356 m 0.300 m/s
2 | 0.313 m 0.076 m/s | -0.094 m 0.060 m/s
4 | 0.157 m 0.002 m/s | -0.008 m 0.003 m/s
8 | 0.080 m 0.000 m/s | 0.004 m 0.000 m/s
16 | 0.041 m 0.000 m/s | 0.006 m 0.000 m/s
32 | 0.022 m 0.000 m/s | 0.003 m 0.000 m/s
Without warm starting, the stack sinks more the fewer iterations it gets, because each step only spreads the weight a few contacts up the column, and Baumgarte correction keeps catching up. Warm starting carries the converged impulses over, so 4–8 iterations already keep the top box within a centimeter of its rest height, a result the cold solver does not reach even with 32. It has a price: with only 1–2 iterations the remembered impulses overshoot and the column bounces (a negative "sank" means the top box is above its rest height).
| Engine | Iteration settings |
|---|---|
| Unity (PhysX) | Physics.defaultSolverIterations (6) and defaultSolverVelocityIterations (1), per body Rigidbody.solverIterations |
| Box2D v3 | subStepCount in b2World_Step (4 is the documented default) |
| Godot (Jolt) | Project Settings > Physics > Jolt Physics 3D > Simulation: Velocity Steps, Position Steps |
| Rapier | world.numSolverIterations in JS, IntegrationParameters in Rust |
Raising iterations is the first knob to try for wobbly stacks and stretchy chains, and the most expensive one: cost grows linearly with it for every contact in the scene. Box2D v3 replaces "more iterations" with sub-stepping: it splits each step into small sub-steps with one solver pass each, which converges better for the same cost. Prefer raising iterations per body (the tall tower, the ragdoll) over raising them globally.
Tip: Contact order matters for Gauss-Seidel. Solving the stack from the ground up spreads support faster than top-down. Engines don't sort contacts by height, but they keep the order stable from step to step, so the same scene behaves the same way every run. That is one of the requirements of determinism.
Play with a stack
The demo below is a small sequential-impulse solver in the browser. To keep it short the boxes are axis-aligned and never rotate, so it only has to handle face-to-face contacts with a normal along x or y. It still has everything this lesson describes: accumulated normal and friction impulses (friction clamped by μ · jn), warm starting from a contact cache, Baumgarte correction with a slop, and sleeping. Orange boxes are awake, blue boxes are asleep.
- Click empty space to drop a box, click a box to push it (this wakes everything).
- Lower the iterations to 1–2 and turn warm starting off: the column visibly sinks into itself. Turn warm start on again and watch it straighten.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height, PX = 30; // 30 pixels per meter: the world is 16 x 9 m
const STEP = 1 / 60, GRAVITY = 10, BETA = 0.2, SLOP = 0.01, FRICTION = 0.5;
const SLEEP_SPEED = 0.08, SLEEP_TIME = 0.5;
let iterations = 8, warmStart = true;
// Axis-aligned boxes only (no rotation): position = center, half extents hx, hy.
let bodies = [], cache = new Map();
function box(x, y, hx, hy, invMass) {
return { x, y, hx, hy, vx: 0, vy: 0, invMass, still: 0, asleep: false };
}
function reset() {
bodies = [box(8, -0.5, 9, 0.5, 0), box(-0.5, 4.5, 0.5, 5, 0), box(16.5, 4.5, 0.5, 5, 0)]; // ground, walls
for (let i = 0; i < 7; i++) bodies.push(box(5, 0.5 + i * 1.0, 0.5, 0.5, 1)); // a column
for (let r = 0; r < 4; r++) for (let c = 0; c <= 3 - r; c++) // a pyramid
bodies.push(box(10.5 + c * 1.02 + r * 0.51, 0.5 + r, 0.5, 0.5, 1));
cache.clear();
}
reset();
const dynamic = (b) => b.invMass > 0;
const wake = (b) => { if (dynamic(b)) { b.asleep = false; b.still = 0; } };
const invM = (b) => (dynamic(b) && !b.asleep ? b.invMass : 0); // sleeping bodies act as static
function findContacts() {
const contacts = [];
for (let i = 0; i < bodies.length; i++) for (let j = i + 1; j < bodies.length; j++) {
const a = bodies[i], b = bodies[j];
if (!dynamic(a) && !dynamic(b)) continue;
const dx = b.x - a.x, dy = b.y - a.y;
const ox = a.hx + b.hx - Math.abs(dx), oy = a.hy + b.hy - Math.abs(dy);
if (ox <= 0 || oy <= 0) continue;
// a moving body that hits a sleeping one wakes it (and its contacts wake the rest next step)
const moving = (x) => dynamic(x) && !x.asleep && Math.hypot(x.vx, x.vy) > 0.5;
if ((a.asleep && moving(b)) || (b.asleep && moving(a))) { wake(a); wake(b); }
if (invM(a) + invM(b) === 0) continue;
const c = ox < oy ? { a, b, nx: Math.sign(dx) || 1, ny: 0, depth: ox } : { a, b, nx: 0, ny: Math.sign(dy) || 1, depth: oy };
const key = i + ',' + j + (c.nx ? 'x' : 'y');
const old = warmStart ? cache.get(key) : null;
c.key = key; c.jn = old ? old.jn : 0; c.jt = old ? old.jt : 0;
contacts.push(c);
}
return contacts;
}
function applyImpulse(c, px, py) {
const ia = invM(c.a), ib = invM(c.b);
c.a.vx -= px * ia; c.a.vy -= py * ia;
c.b.vx += px * ib; c.b.vy += py * ib;
}
function update(dt) {
for (const b of bodies) if (dynamic(b) && !b.asleep) b.vy -= GRAVITY * dt;
const contacts = findContacts();
for (const c of contacts) applyImpulse(c, c.nx * c.jn - c.ny * c.jt, c.ny * c.jn + c.nx * c.jt); // warm start
for (let it = 0; it < iterations; it++) {
for (const c of contacts) {
const k = invM(c.a) + invM(c.b);
if (k === 0) continue;
// normal: accumulated impulse may only push
let rvx = c.b.vx - c.a.vx, rvy = c.b.vy - c.a.vy;
const vn = rvx * c.nx + rvy * c.ny;
const bias = BETA / dt * Math.max(c.depth - SLOP, 0);
let jn = (-vn + bias) / k;
const newN = Math.max(c.jn + jn, 0); jn = newN - c.jn; c.jn = newN;
applyImpulse(c, c.nx * jn, c.ny * jn);
// friction along the tangent (-ny, nx), clamped by mu * normal impulse
rvx = c.b.vx - c.a.vx; rvy = c.b.vy - c.a.vy;
const vt = -rvx * c.ny + rvy * c.nx;
let jt = -vt / k;
const maxF = FRICTION * c.jn;
const newT = Math.max(-maxF, Math.min(maxF, c.jt + jt)); jt = newT - c.jt; c.jt = newT;
applyImpulse(c, -c.ny * jt, c.nx * jt);
}
}
cache = new Map(contacts.map((c) => [c.key, { jn: c.jn, jt: c.jt }]));
for (const b of bodies) {
if (!dynamic(b) || b.asleep) continue;
b.x += b.vx * dt; b.y += b.vy * dt;
if (b.y < -5) { b.invMass = 0; b.hx = b.hy = 0; } // fell out of the world: retire it
b.still = Math.hypot(b.vx, b.vy) < SLEEP_SPEED ? b.still + dt : 0;
if (b.still > SLEEP_TIME) { b.asleep = true; b.vx = b.vy = 0; }
}
}
// ---- input: buttons, drop a box on empty space, push a box you click ----
const buttons = [
{ x: 10, y: 8, w: 22, label: '−', act: () => { iterations = Math.max(1, iterations - 1); } },
{ x: 128, y: 8, w: 22, label: '+', act: () => { iterations = Math.min(30, iterations + 1); } },
{ x: 160, y: 8, w: 110, label: '', act: () => { warmStart = !warmStart; } },
{ x: 280, y: 8, w: 60, label: 'Reset', act: reset },
];
cv.addEventListener('pointerdown', (e) => {
const r = cv.getBoundingClientRect();
const sx = (e.clientX - r.left) * W / r.width, sy = (e.clientY - r.top) * H / r.height;
for (const btn of buttons) if (sx >= btn.x && sx <= btn.x + btn.w && sy >= btn.y && sy <= btn.y + 20) {
btn.act(); for (const b of bodies) wake(b); // new solver settings: let everything settle again
return;
}
const wx = sx / PX, wy = (H - sy) / PX;
const hit = bodies.find((b) => dynamic(b) && Math.abs(wx - b.x) < b.hx && Math.abs(wy - b.y) < b.hy);
if (hit) { // push away from the click point
for (const b of bodies) wake(b);
hit.vx += (hit.x - wx > 0 ? 1 : -1) * 6; hit.vy += 2;
} else if (wy > 1 && wx > 0.6 && wx < 15.4) {
const b = box(wx, wy, 0.5, 0.5, 1); b.vy = -1; bodies.push(b);
}
});
function draw() {
ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
let awake = 0, asleep = 0;
for (const b of bodies) {
if (b.hx === 0) continue;
if (dynamic(b)) b.asleep ? asleep++ : awake++;
ctx.fillStyle = !dynamic(b) ? '#455a64' : b.asleep ? '#3f51b5' : '#ffb74d';
ctx.fillRect((b.x - b.hx) * PX, H - (b.y + b.hy) * PX, b.hx * 2 * PX, b.hy * 2 * PX);
if (dynamic(b)) { ctx.strokeStyle = '#0e1018'; ctx.strokeRect((b.x - b.hx) * PX + 0.5, H - (b.y + b.hy) * PX + 0.5, b.hx * 2 * PX - 1, b.hy * 2 * PX - 1); }
}
ctx.font = '13px system-ui, sans-serif'; ctx.textBaseline = 'middle';
for (const btn of buttons) {
ctx.fillStyle = '#263238'; ctx.fillRect(btn.x, btn.y, btn.w, 20);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center';
ctx.fillText(btn.label || `warm start: ${warmStart ? 'on' : 'off'}`, btn.x + btn.w / 2, btn.y + 10);
}
ctx.textAlign = 'center'; ctx.fillText(`iterations: ${iterations}`, 80, 18);
ctx.textAlign = 'left';
ctx.fillText(`awake ${awake} asleep ${asleep} (blue) click space: drop a box, click a box: push`, 10, 40);
}
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
acc += Math.min((now - last) / 1000, 0.1);
last = now;
while (acc >= STEP) { update(STEP); acc -= STEP; }
draw();
requestAnimationFrame(frame);
});
</script>Islands and sleeping
Most of a level is at rest most of the time: crates in a corner, a pile of rubble after an explosion. Solving them every step wastes CPU and lets solver noise make them creep. Engines therefore put still bodies to sleep:
- A body is a sleep candidate while its linear and angular speed stay below a threshold (for example 5 cm/s) for a time (for example 0.5 s). Unity exposes
Rigidbody.sleepThreshold(a mass-normalized energy), Box2D v3b2BodyDef.sleepThreshold(a speed), GodotRigidBody3D.can_sleepandsleepingper body, plus Sleep Velocity Threshold and Sleep Time Threshold in the Jolt project settings. - Bodies that touch, directly or through a chain of contacts and joints, form an island. An island sleeps only when every body in it is ready, because a crate can't sleep while the crate it rests on still moves.
- A sleeping island wakes as a whole when something touches it, when a joint attached to it changes, or when code moves a body or applies a force. Engines also wake bodies when you change their transform from code.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <string>
// Each body settles at its own rate (speed = v0 * e^(-decay * t)). A body is "still" while its speed is
// under the threshold; after `timeToSleep` seconds of stillness it is ready to sleep. An island (bodies
// that touch each other) sleeps only when ALL its bodies are ready, and wakes as soon as one moves.
struct Body { std::string name; int island; double v0, decay, stillFor = 0; bool ready = false; };
int main() {
std::cout << std::fixed << std::setprecision(2);
const double dt = 1.0 / 60, threshold = 0.05, timeToSleep = 0.5;
std::vector<Body> bodies = {
{"crate A", 0, 2.0, 3.0}, {"crate B", 0, 1.0, 1.5}, {"crate C", 0, 3.0, 4.0}, // a stack: island 0
{"barrel", 1, 2.0, 3.0}, // alone: island 1
};
bool islandAsleep[2] = {false, false};
for (int step = 1; step <= 330; step++) {
double t = step * dt;
if (step == 180) { bodies[1].v0 *= 40; std::cout << "t = " << t << " s: a ball hits crate B\n"; }
for (Body& b : bodies) {
double speed = b.v0 * std::exp(-b.decay * t);
b.stillFor = speed < threshold ? b.stillFor + dt : 0.0;
bool ready = b.stillFor >= timeToSleep;
if (ready && !b.ready) std::cout << "t = " << t << " s: " << b.name << " is ready to sleep\n";
b.ready = ready;
}
for (int isl = 0; isl < 2; isl++) {
bool all = true;
for (const Body& b : bodies) if (b.island == isl && !b.ready) all = false;
if (all != islandAsleep[isl]) {
islandAsleep[isl] = all;
std::cout << "t = " << t << " s: island " << isl << (all ? " falls asleep" : " wakes up") << "\n";
}
}
}
}t = 1.53 s: crate C is ready to sleep
t = 1.73 s: crate A is ready to sleep
t = 1.73 s: barrel is ready to sleep
t = 1.73 s: island 1 falls asleep
t = 2.50 s: crate B is ready to sleep
t = 2.50 s: island 0 falls asleep
t = 3.00 s: a ball hits crate B
t = 3.00 s: island 0 wakes up
t = 4.97 s: crate B is ready to sleep
t = 4.97 s: island 0 falls asleep
The barrel sleeps first, as an island of one. The stack waits for its slowest member, crate B. When a ball hits crate B, the whole island wakes, although crates A and C were perfectly still, because the impulse may travel through the stack. (A real engine also resets the timers of every body in a woken island, so they all wait the full half second again.)
Sleeping bugs are some of the most common physics complaints: a door that stays open because the body slept before the player touched it through a trigger, a platform that stops moving because its body slept. Wake bodies explicitly (Rigidbody.WakeUp(), b2Body_SetAwake, setting Godot's sleeping = false) when gameplay code changes something the solver can't see.
Test yourself
Why do sequential-impulse solvers clamp the accumulated impulse instead of each iteration's increment?
- It is faster
- So a later iteration can reduce an impulse that an earlier iteration made too large, while the total still never pulls
- Because increments are always positive
- To support restitution
What does warm starting do?
- Heats objects up
- Starts each persistent contact with the impulse it had in the previous step
- Runs the first step at a smaller dt
- Wakes sleeping bodies
Two crates rest on each other. One is perfectly still, the other still wobbles. When can the still crate sleep?
- Immediately
- Only when the whole island, including the wobbling crate, has been still long enough
- Never
- After exactly one step