Algorithm Search⌘K

Algorithmadvanced

Shock propagation

Also called stacking by shock propagation, shock propagation sweep.

Make tall stacks stable by solving contacts from the ground up in a contact graph and freezing each lower level when solving the one above.

Time
O(n + e) graph_and_levelsO((S + 1) I c) sweeps
Space
O(n + e + c) total
Where
I = the passes per level; S = the number of contact sweeps; c = the number of contacts; e = the number of edges of the contact graph; n = the number of bodies
Properties
deterministicin placeofflineiterative
Origin
Eran Guendelman, Robert Bridson, Ronald Fedkiw, 2003

Shock propagation is a heuristic that makes stacks of rigid bodies come to rest. An iterative contact solver such as projected Gauss-Seidel needs many sweeps before the weight of a tall stack reaches the ground, so with a fixed budget the stack sinks into itself. Shock propagation builds a graph of which body rests on which, sorts the bodies into levels from the ground up, and then makes one last sweep over the levels. After it handles a level, it gives the bodies of that level infinite mass, so the levels above cannot push them down again. This stops a stack in one sweep. It also changes the physics, because a body of finite mass is treated as if it could not move: the method does not conserve momentum, and it is tuning for stable stacks, not a solution of the contact problem.

In plain words

Think of a tower of boxes on the floor. A simple solver fixes one touching pair at a time. When it stops a box, it pushes the box below down a little. The push needs many rounds to reach the floor, and with few rounds the tower sinks.

Shock propagation first finds out which box sits on which. Then it fixes the floor contacts, and it nails the bottom boxes in place for the rest of the round. Next it fixes the boxes on top of them, and nails those. It goes up the tower in this way. A box can only be pushed up by what is below it, never down by what is above it. So the whole tower stops in one round. The price is that the upper boxes cannot press the lower ones, which real boxes do.

The problem

The input is one time step of a rigid body simulation: bodies with velocities after gravity, and contacts (A,B)(A, B) with normal nn from BB to AA, as on the collision impulse page. A contact approaches when vrel=n⋅(vA(p)−vB(p))<0v_{rel} = n \cdot (v_A(p) - v_B(p)) < 0. The aim is velocities for which no contact approaches, found with a small, fixed amount of work, also for stacks of many bodies. This page uses yy up and gravity (0,−9.81)(0, -9.81).

The algorithm

Guendelman, Bridson and Fedkiw (2003) define the levels by a contact graph (Section 8.1). Each body is moved for a short time Δτ\Delta\tau under gravity alone, with the others fixed. If the moved body AA then touches BB, the graph gets the edge B→AB \to A: AA would fall onto BB. In the code of this page, static bodies do not move, so they get no incoming edges. Bodies in a cycle of the graph, such as dominoes leaning on each other in a ring, are merged into one strongly connected component, found by two depth-first searches. The condensation is acyclic, and the level of a component is 0 if no edge enters it, and otherwise one more than the largest level of a component with an edge into it. A contact belongs to the higher level of its two bodies.

  1. SHOCK-PROPAGATION-STEP(bodies, contacts, Δτ, S, I)
  2. 1G ← edges B → A where A, moved under gravity for Δτ, touches B
  3. 2C_0, C_1, ... ← strongly connected components of G in topological order
  4. 3level(C) ← 0 if no edge enters C, else 1 + max level of a predecessor of C
  5. 4repeat S times ▷ contact sweeps
  6. 5for each level ℓ, from 0 upward
  7. 6repeat I times: resolve each contact of level ℓ
  8. 7for each level ℓ, from 0 upward ▷ the shock sweep
  9. 8repeat I times: resolve each contact of level ℓ
  10. 9give every body of level ℓ infinite mass (inverse mass 0)

RESOLVE applies the collision impulse of one contact if it approaches. The infinite masses of line L9 last only until the end of the sweep; the bodies keep their real masses in the next step. In the paper, the contact sweeps of lines L4 to L6 use the coefficient of restitution with a value of ϵ\epsilon ramped from −0.9-0.9 up to 00 over the sweeps (Section 8), and the shock sweep is run on the last of them (Section 8.2). The code of this page uses plastic impulses throughout (e=0e = 0) and a separate shock sweep, which is the same structure in a simpler form.

Inside one level the contacts are solved II times, and the bodies of that level are not given infinite mass while it is solved (Section 8.2). This is how a ring of dominoes in one component is still solved by the ordinary iteration.

Example

Three boxes of mass 1 and side 1 stand on the ground and all move down at 11 m/s, for example after a gravity step. The contact graph is ground →\to box 1 →\to box 2 →\to box 3, with levels 0, 1, 2 and 3. The contacts are ground with box 1 (level 1), box 1 with box 2 (level 2), and box 2 with box 3 (level 3).

One contact sweep from the bottom up, with plastic impulses:

contact before after
ground and box 1 v1=−1v_1 = -1 v1=0v_1 = 0
box 1 and box 2 v1=0v_1 = 0, v2=−1v_2 = -1 v1=v2=−1/2v_1 = v_2 = -1/2
box 2 and box 3 v2=−1/2v_2 = -1/2, v3=−1v_3 = -1 v2=v3=−3/4v_2 = v_3 = -3/4

The velocities are (−1/2,−3/4,−3/4)(-1/2, -3/4, -3/4): the stack still sinks. Plain sweeps need 17 sweeps until every box is slower than 1% of its start speed. A shock sweep after the first sweep handles level 1 (box 1 stops) and freezes box 1, then level 2 (box 2 stops against the frozen box 1) and freezes it, then level 3. The result is (0,0,0)(0, 0, 0) after one sweep.

Momentum. A lower box of mass 1 moves up at 11 m/s, and an upper box of mass 3 on it moves down at 11 m/s. The total momentum is 1−3=−21 - 3 = -2. A plastic collision of the two gives both −1/2-1/2 m/s and keeps the momentum. The shock sweep freezes the lower box at level 0 first, so the upper box takes the velocity of the lower box: both move at 11 m/s, and the momentum is 44. The lower box is not slowed by the heavy box on top of it. This is the change of physics: the result is not what a collision of these two bodies would give.

Stacks over time. A column of NN boxes of mass 1 and side 1 starts at rest on the ground. Each step adds gravity, runs 4 contact sweeps with one pass per level, and moves the boxes by symplectic Euler, at Δt=1/60\Delta t = 1/60 for 120 steps. The numbers are measurements from the code of this page:

boxes NN 5 10 20
top box height at rest 4.5 9.5 19.5
without shock: top box height 3.81 6.31 10.32
without shock: largest overlap 0.262 0.557 0.768
with shock: top box height 4.5 9.5 19.5
with shock: largest overlap 0 0 0

Without shock propagation, the boxes overlap and the stack loses about half of its height for N=20N = 20. With it, the stack stays exactly at rest.

Correctness

The proof is in proofs/correctness.md. It uses the model of the code: boxes that translate only, with vertical normals. It shows:

  • Termination. Every loop is finite, so the step ends after O(n+e+(S+1)Ic)O(n + e + (S + 1) I c) work once the graph is built.
  • Levels respect the graph. Bodies in one component share a level, and every edge between components goes to a strictly higher level, because the components come out in a topological order.
  • Stacks give an acyclic graph. For boxes with disjoint interiors, an edge B→AB \to A means that the bottom of AA lies above the top of BB, so the graph has no cycle, and every contact has its upper body at a strictly higher level.
  • After the shock sweep, no contact approaches. When level ℓ\ell is solved, the bodies below are frozen, so each impulse only raises the velocity of a body of level ℓ\ell, and later levels cannot change it again. This holds for any number of contact sweeps before.
  • Nothing changes if nothing approaches. The sweep then applies no impulse.

Not proved: the result for bodies that rotate, where another contact of the same body can lower the relative velocity again; any error bound for the contacts inside one strongly connected component; and any property of the contact sweeps before the shock sweep. The momentum example shows that the result is not the solution of the contact problem.

Proof: The levels respect the contact graph, and after the shock sweep no contact of a stack approachesfull

The setting is the code of the page: 2D axis-aligned boxes that only translate, yy up, and contacts (A,B)(A, B) where AA rests on BB, with the normal (0,1)(0, 1) from BB to AA. RESOLVE on a contact computes vrel=vA−vBv_{rel} = v_A - v_B (vertical components); if vrel<0v_{rel} < 0 and k=wA+wB>0k = w_A + w_B > 0, where ww is the inverse mass used in the current sweep, it applies j=−vrel/k≥0j = -v_{rel}/k \ge 0: vAv_A gains wAjw_A j and vBv_B loses wBjw_B j. Afterwards vrel=0v_{rel} = 0. Line numbers refer to the pseudocode of the page.

Termination. Building the graph (line L1) visits each ordered pair of bodies once. The two depth-first searches (line L2) visit each node and edge a constant number of times. Line L3 visits each component and each edge between components once. The sweeps (lines L4 to L9) run SS contact sweeps and one shock sweep, each over the levels with II passes over the contacts of the level, and each RESOLVE is a constant amount of work. So the step ends after O(n2+e+(S+1)Ic)O(n^2 + e + (S + 1) I c) operations for nn bodies, ee edges and cc contacts.

Lemma 1 (components and levels). Line L2 returns the strongly connected components in a topological order of the condensation (an edge between two components goes from an earlier to a later one). Line L3 then assigns levels with level(u)=level(v)\text{level}(u) = \text{level}(v) if uu and vv are in the same component, and level(u)<level(v)\text{level}(u) < \text{level}(v) for every edge u→vu \to v between different components.

Proof. The first part is the correctness of the two-pass depth-first search algorithm for strongly connected components: the second search, run on the reversed graph in decreasing order of finishing times of the first search, collects exactly one component per tree, and the component that contains the node with the largest finishing time has no edge entering it from an unvisited component. So the components come out in a topological order. In that order, every predecessor component of cc comes before cc, so line L3 reads only levels that are already set. A node gets the level of its component. For an edge u→vu \to v between components, the component of uu is a predecessor of the component of vv, so level(v)≥level(u)+1\text{level}(v) \ge \text{level}(u) + 1. □\square

Lemma 2 (stacks give an acyclic graph). Let the boxes have disjoint interiors, and let the graph have the edge j→ij \to i when box ii, moved down by δ>0\delta > 0, overlaps box jj. Then every edge j→ij \to i has top(j)≤bottom(i)\text{top}(j) \le \text{bottom}(i). In particular bottom(j)<bottom(i)\text{bottom}(j) < \text{bottom}(i), the graph is acyclic, every component is a single box, and every edge goes to a strictly higher level.

Proof. The moved box overlaps jj, so the horizontal intervals overlap. Before the move the interiors were disjoint, so the vertical intervals were disjoint: either top(j)≤bottom(i)\text{top}(j) \le \text{bottom}(i) or top(i)≤bottom(j)\text{top}(i) \le \text{bottom}(j). In the second case, moving ii down keeps top(i)−δ<bottom(j)\text{top}(i) - \delta < \text{bottom}(j), so there is no overlap. Hence the first case holds, and bottom(j)<top(j)≤bottom(i)\text{bottom}(j) < \text{top}(j) \le \text{bottom}(i). The bottoms strictly increase along every edge, so there is no cycle, each component is one box, and Lemma 1 gives strictly increasing levels. □\square

When a box AA rests on BB with a gap of at most zero and δ\delta is smaller than the heights of the boxes, the moved AA overlaps BB, so the edge B→AB \to A exists. The theorem below assumes this for every contact of the solve.

Theorem 1 (after the shock sweep, no contact approaches). Assume that every contact (A,B)(A, B) of the solve has level(A)>level(B)\text{level}(A) > \text{level}(B), and that static bodies have inverse mass zero. Then after lines L7 to L9, every contact has vA−vB≥0v_A - v_B \ge 0. This holds for any number S≥0S \ge 0 of contact sweeps before and any I≥1I \ge 1.

Proof. A contact (A,B)(A, B) belongs to the level max⁡(level(A),level(B))=level(A)\max(\text{level}(A), \text{level}(B)) = \text{level}(A). The shock sweep handles the levels 0,1,2,…0, 1, 2, \ldots in increasing order, and line L9 sets wu=0w_u = 0 for every body uu of a level after that level is handled. RESOLVE changes the velocity of a body only if its ww is nonzero.

Consider the pass over level ℓ\ell. Every body of a lower level has w=0w = 0 by then. Each contact of level ℓ\ell has its lower body BB at a level below ℓ\ell, so RESOLVE on it changes only vAv_A, and only upward (wAj≥0w_A j \ge 0). Bodies of level ℓ\ell are never the lower body of a contact of level ℓ\ell, because such a contact would belong to a higher level. So during the pass over level ℓ\ell, velocities change only for bodies of level ℓ\ell, and they only increase. Take a contact (A,B)(A, B) of level ℓ\ell. Since I≥1I \ge 1, RESOLVE runs on it at least once; after that, vA−vB≥0v_A - v_B \ge 0. Later in the same pass, vAv_A can only increase and vBv_B is fixed, so vA−vB≥0v_A - v_B \ge 0 at the end of the pass. After the pass, AA and BB both have w=0w = 0, so no later RESOLVE changes vAv_A or vBv_B. □\square

Corollary (a resting stack stops in one sweep). In a single column of boxes on static ground in which every box moves down with the same speed u>0u > 0 and there are no other contacts, the shock sweep leaves every box at rest, whatever SS.

Proof. Let box kk sit on box k−1k - 1, with the ground as box 0, so box kk has level kk. Before the shock sweep, the contact sweeps only apply nonnegative impulses that push the upper box up and the lower box down, so every box still moves down or is at rest: by induction over the sweeps, each RESOLVE moves vAv_A and vBv_B toward each other and never above the larger of the two old values, which is at most zero. In the shock sweep, the pass over level kk sets vkv_k to max⁡(vk,vk−1)=max⁡(vk,0)=0\max(v_k, v_{k-1}) = \max(v_k, 0) = 0, by induction from the ground, which has v0=0v_0 = 0. □\square

Proposition (no effect when nothing approaches). If no contact has vA−vB<0v_A - v_B < 0 before the shock sweep, the shock sweep changes no velocity. Proof. Each RESOLVE then does nothing, and so nothing changes for the next one. □\square

Momentum is not kept. A RESOLVE with wB=0w_B = 0 for a body BB of finite mass changes the momentum of AA and not that of BB. So the shock sweep changes the total momentum whenever it acts on such a contact. The page gives an example with momentum −2-2 before and 44 after. This is the sense in which shock propagation changes the physics: it is a heuristic, not a solution method for the contact problem.

What is not proved. For bodies that rotate, a contact of level ℓ\ell can receive an impulse from another contact of the same body with a different normal that lowers its relative velocity, so Theorem 1 does not apply as stated. Contacts inside one strongly connected component (bodies of the same level) are only iterated II times, and no bound on their remaining error is proved. Nothing is proved about the contact sweeps before the shock sweep, and the plausibility of the result is judged by eye in the source.

Complexity

The strongly connected components and the levels take O(n+e)O(n + e) time with depth-first search for nn bodies and ee edges. Building the graph needs a collision query per moved body; the code of this page tests all pairs in O(n2)O(n^2), and an engine uses its broad phase. Each sweep resolves every contact II times, so SS contact sweeps and one shock sweep cost O((S+1)Ic)O((S + 1) I c) for cc contacts. Memory is O(n+e+c)O(n + e + c).

Properties

  • A heuristic: it changes the physics by giving lower levels infinite mass (Guendelman, Bridson and Fedkiw 2003, Section 8.2).
  • Stops a stack in one sweep, whatever its height, in the model of the proof.
  • Does not conserve momentum, and the upper bodies do not press on the lower ones during the shock sweep.
  • Depends on the direction of gravity, through the contact graph.
  • The levels depend on the choice of Δτ\Delta\tau; a value that is too large finds edges between bodies that are not about to touch.

Variants and improvements

  • Ramped restitution. Guendelman, Bridson and Fedkiw run the contact sweeps with ϵ\epsilon from −0.9-0.9 up to 00, and the shock sweep on the last one (Section 8).
  • Propagation sweeps first. In the paper, a large box dropped onto a plank resting on other bodies needs the ordinary sweeps to pass its weight down before the shock sweep; with shock propagation alone, the plank does not react as expected (Figure 6). Similarly, a see-saw with shock propagation alone sits still or tips slowly (Figure 7).
  • Velocity-based shock propagation. Erleben (2007) uses shock propagation in a fixed time stepping scheme for velocity-based complementarity formulations, with an iterative solver tuned for multibody dynamics.
  • Warm starting instead. Catto (2005) keeps the impulses of the last step, which also lets a stack of ten boxes stand with 10 iterations (Section 9.1). This changes the start of the iteration, not the masses.

When to use it

Use it when stacks and piles must come to rest with a small budget of sweeps, in animation and games, and when a plausible result matters more than the forces between the bodies. Do not use it when the forces or the momentum must be right, for example for a see-saw, a balance, or a heavy body landing on a light one, or when there is no clear direction of support.

Pitfalls

  • Freeze every level. A level with no contacts of its own must still be frozen, or a body below can be pushed down by a contact above it. The code loops over all levels for this reason.
  • Restore the masses. The infinite masses belong to one sweep only. Keep them in a separate list, as the code does, so that the next step uses the real masses.
  • Penetration breaks the graph. If the bodies overlap, moving one down can touch a body above it, which adds edges in both directions and merges the stack into one component. In the run without shock propagation above, the largest level fell to 2 after the boxes sank.
  • Same level, no freezing. Bodies in one component are solved only by the II passes; a large ring of leaning bodies behaves like plain iteration.
  • Robotics conventions. Pages such as Stewart-Trinkle time stepping and rigid contact complementarity use zz up; this page uses yy up.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

shock_propagation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shock-propagation/. The authors are listed in prov/P1VHW8.jsonl.

"""Shock propagation for stacks (Guendelman, Bridson and Fedkiw 2003, Section 8).

The model of this file is small on purpose: 2D axis-aligned boxes that only
translate, y up, gravity (0, -g), and contacts with the normal (0, 1) from
the lower body B to the upper body A. A contact is resolved by a plastic
impulse when it approaches, as in the contact processing of the paper with
a restitution of zero.

The graph part (contact graph, strongly connected components by two depth
first searches, levels) works on any directed graph.
"""


# ------------------------------------------------------------------ graph part


def strongly_connected_components(n, edges):
    """Return the components of the digraph on 0..n-1, in a topological order of the condensation.

    Two depth-first searches: one on the graph for the finishing order, one on
    the reversed graph in the reverse finishing order."""
    adj = [[] for _ in range(n)]
    radj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        radj[v].append(u)
    seen, order = [False] * n, []
    for s in range(n):
        if seen[s]:
            continue
        seen[s] = True
        stack = [(s, iter(adj[s]))]
        while stack:
            u, it = stack[-1]
            nxt = next(it, None)
            if nxt is None:
                stack.pop()
                order.append(u)
            elif not seen[nxt]:
                seen[nxt] = True
                stack.append((nxt, iter(adj[nxt])))
    comp = [-1] * n
    comps = []
    for s in reversed(order):
        if comp[s] != -1:
            continue
        cid = len(comps)
        comp[s] = cid
        members, stack = [], [s]
        while stack:
            u = stack.pop()
            members.append(u)
            for w in radj[u]:
                if comp[w] == -1:
                    comp[w] = cid
                    stack.append(w)
        comps.append(sorted(members))
    return comps, comp


def levels(n, edges):
    """Level of each node: 0 for a component that no edge enters, else 1 + the largest level of a predecessor."""
    comps, comp = strongly_connected_components(n, edges)  # @line L2
    preds = [set() for _ in comps]
    for u, v in edges:
        if comp[u] != comp[v]:
            preds[comp[v]].add(comp[u])
    clevel = [0] * len(comps)
    for c in range(len(comps)):  # @line L3
        clevel[c] = 1 + max(clevel[p] for p in preds[c]) if preds[c] else 0  # @line L3
    return [clevel[comp[u]] for u in range(n)], comp


# ------------------------------------------------------------------ bodies and contacts


class Box:
    """An axis-aligned box: center (x, y), half sizes (hx, hy), mass m (None: static), velocity (vx, vy)."""

    def __init__(self, x, y, hx, hy, m=None, vx=0, vy=0):
        self.x, self.y, self.hx, self.hy = x, y, hx, hy
        self.inv_m = 0 if m is None else 1 / m
        self.m = m
        self.vx, self.vy = vx, vy

    @property
    def static(self):
        return self.m is None


def overlap_x(a, b):
    return min(a.x + a.hx, b.x + b.hx) - max(a.x - a.hx, b.x - b.hx)


def boxes_overlap(a, b, dy_a=0):
    """Strict overlap of a (moved by dy_a) and b."""
    oy = min(a.y + dy_a + a.hy, b.y + b.hy) - max(a.y + dy_a - a.hy, b.y - b.hy)
    return overlap_x(a, b) > 0 and oy > 0


def contact_graph(boxes, g, dtau):
    """Edge j -> i when box i, moved down by its fall under gravity in time dtau, overlaps box j."""
    drop = g * dtau * dtau / 2
    edges = []
    for i, bi in enumerate(boxes):  # @line L1
        if bi.static:
            continue
        for j, bj in enumerate(boxes):
            if j != i and boxes_overlap(bi, bj, -drop):  # @line L1
                edges.append((j, i))  # @line L1
    return edges


def find_contacts(boxes, slop):
    """Contacts (A, B): A rests on B, with a horizontal overlap and a vertical gap of at most slop."""
    out = []
    for a, A in enumerate(boxes):
        for b, B in enumerate(boxes):
            if a == b or A.y <= B.y or overlap_x(A, B) <= 0:
                continue
            gap = (A.y - A.hy) - (B.y + B.hy)
            if gap <= slop and not (A.static and B.static):
                out.append((a, b))
    return out


def resolve(boxes, inv_m, contact):
    """A plastic impulse along (0, 1) on the upper body if the contact approaches. Return the impulse."""
    a, b = contact
    A, B = boxes[a], boxes[b]
    v_rel = A.vy - B.vy
    k = inv_m[a] + inv_m[b]
    if v_rel >= 0 or k == 0:
        return 0
    j = -v_rel / k
    A.vy += inv_m[a] * j
    B.vy -= inv_m[b] * j
    return j


def solve_velocities(boxes, contacts, level, sweeps, iters, shock=True):
    """Contact propagation sweeps from the lowest level up, then one shock propagation sweep."""
    inv_m = [bx.inv_m for bx in boxes]
    by_level = {}
    for c in contacts:
        by_level.setdefault(max(level[c[0]], level[c[1]]), []).append(c)
    order = sorted(by_level)
    for _ in range(sweeps):  # @line L4
        for lv in order:  # @line L5
            for _ in range(iters):  # @line L6
                for c in by_level[lv]:  # @line L6
                    resolve(boxes, inv_m, c)  # @line L6
    if not shock:
        return
    for lv in range(max(level) + 1):  # @line L7
        for _ in range(iters):  # @line L8
            for c in by_level.get(lv, []):  # @line L8
                resolve(boxes, inv_m, c)  # @line L8
        for u, bx in enumerate(boxes):  # @line L9
            if level[u] == lv:  # @line L9
                inv_m[u] = 0  # @line L9
    # the infinite masses live only in the local list inv_m, so the boxes keep their masses


def step(boxes, dt, g, sweeps, iters, shock=True, slop=1e-9):
    """One time step: gravity, contact graph and levels, velocity solve, then positions (symplectic Euler)."""
    for bx in boxes:
        if not bx.static:
            bx.vy -= g * dt
    edges = contact_graph(boxes, g, dt)
    level, _ = levels(len(boxes), edges)
    contacts = find_contacts(boxes, slop)
    solve_velocities(boxes, contacts, level, sweeps, iters, shock)
    for bx in boxes:
        if not bx.static:
            bx.x += bx.vx * dt
            bx.y += bx.vy * dt
    return level, contacts


def penetration(boxes, contacts):
    return max([0] + [(boxes[b].y + boxes[b].hy) - (boxes[a].y - boxes[a].hy) for a, b in contacts])


def stack(n, m=1, size=0.5, gap=0):
    """The ground (static) and n boxes of mass m and side 2*size, stacked with the given gap."""
    boxes = [Box(0, -1, 10, 1)]
    for k in range(n):
        boxes.append(Box(0, size + k * (2 * size + gap), size, size, m))
    return boxes
test_shock_propagation.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shock-propagation/. The authors are listed in prov/P1VHW8.jsonl.

import random
from fractions import Fraction as F

from shock_propagation import (Box, contact_graph, find_contacts, levels, penetration, solve_velocities, stack, step,
                               strongly_connected_components)


def closure(n, edges):
    reach = [[i == j for j in range(n)] for i in range(n)]
    for u, v in edges:
        reach[u][v] = True
    for k in range(n):
        for i in range(n):
            if reach[i][k]:
                for j in range(n):
                    if reach[k][j]:
                        reach[i][j] = True
    return reach


def test_components_and_levels_match_brute_force():
    rng = random.Random(1)
    for _ in range(300):
        n = rng.randint(1, 8)
        edges = [(u, v) for u in range(n) for v in range(n) if u != v and rng.random() < 0.2]
        reach = closure(n, edges)
        comps, comp = strongly_connected_components(n, edges)
        for u in range(n):
            for v in range(n):
                assert (comp[u] == comp[v]) == (reach[u][v] and reach[v][u])
        # topological order of the condensation: every edge goes to the same or a later component
        assert all(comp[u] <= comp[v] for u, v in edges)
        level, _ = levels(n, edges)
        # brute force: the level is the largest number of components on a path into the node, minus one
        best = {}

        def longest(c):
            if c not in best:
                ps = {comp[u] for u, v in edges if comp[v] == c and comp[u] != c}
                best[c] = 1 + max(longest(p) for p in ps) if ps else 0
            return best[c]

        assert level == [longest(comp[u]) for u in range(n)]
        for u, v in edges:
            assert level[u] == level[v] if comp[u] == comp[v] else level[u] < level[v]


def test_dominoes_in_a_circle_share_one_level():
    n = 7  # node 0 is the ground, 1..6 are dominoes, each leaning on the next
    edges = [(0, i) for i in range(1, n)] + [(i, i % (n - 1) + 1) for i in range(1, n)]
    level, comp = levels(n, edges)
    assert level == [0] + [1] * (n - 1)
    assert len(set(comp[1:])) == 1


def test_pyramid_contact_graph_from_falling():
    boxes = [Box(0, -1, 10, 1), Box(F(-3, 5), F(1, 2), F(1, 2), F(1, 2), 1), Box(F(3, 5), F(1, 2), F(1, 2), F(1, 2), 1),
             Box(0, F(3, 2), F(1, 2), F(1, 2), 1)]
    edges = contact_graph(boxes, 10, F(1, 60))
    assert sorted(edges) == [(0, 1), (0, 2), (1, 3), (2, 3)]
    level, _ = levels(4, edges)
    assert level == [0, 1, 1, 2]
    assert sorted(find_contacts(boxes, 0)) == [(1, 0), (2, 0), (3, 1), (3, 2)]


def test_page_example_three_box_stack():
    boxes = stack(3, m=F(1), size=F(1, 2))
    for b in boxes[1:]:
        b.vy = F(-1)
    level, _ = levels(4, contact_graph(boxes, 10, F(1, 60)))
    assert level == [0, 1, 2, 3]
    contacts = find_contacts(boxes, 0)
    solve_velocities(boxes, contacts, level, 1, 1, shock=False)
    assert [b.vy for b in boxes[1:]] == [F(-1, 2), F(-3, 4), F(-3, 4)]
    solve_velocities(boxes, contacts, level, 0, 1, shock=True)
    assert [b.vy for b in boxes[1:]] == [0, 0, 0]
    # plain sweeps alone: count the sweeps until every box is slower than 1% of the start
    boxes = stack(3, m=F(1), size=F(1, 2))
    for b in boxes[1:]:
        b.vy = F(-1)
    sweeps = 0
    while max(-b.vy for b in boxes[1:]) > F(1, 100):
        solve_velocities(boxes, contacts, level, 1, 1, shock=False)
        sweeps += 1
    assert sweeps == 17


def skyline_scene(rng):
    """Boxes dropped one by one onto the ground and each other, so that each rests exactly on what is below it."""
    boxes = [Box(0, -1, 100, 1)]
    for _ in range(rng.randint(1, 9)):
        hx, hy = F(rng.randint(1, 4), 4), F(rng.randint(1, 3), 4)
        x = F(rng.randint(-8, 8), 4)
        probe = Box(x, 0, hx, hy, 1)
        top = max([0] + [b.y + b.hy for b in boxes[1:] if min(x + hx, b.x + b.hx) - max(x - hx, b.x - b.hx) > 0])
        probe.y = top + hy
        probe.inv_m = 1 / F(rng.randint(1, 20))
        probe.m = 1 / probe.inv_m
        probe.vy = F(rng.randint(-8, 4), 2)
        boxes.append(probe)
    return boxes


def test_after_the_shock_sweep_no_contact_approaches():
    rng = random.Random(3)
    for _ in range(150):
        boxes = skyline_scene(rng)
        edges = contact_graph(boxes, 10, F(1, 60))
        level, _ = levels(len(boxes), edges)
        contacts = find_contacts(boxes, 0)
        for a, b in contacts:
            assert level[a] > level[b]  # stacks of boxes give an acyclic graph
        solve_velocities(boxes, contacts, level, rng.randint(0, 2), rng.randint(1, 2), shock=True)
        for a, b in contacts:
            assert boxes[a].vy - boxes[b].vy >= 0


def test_shock_sweep_changes_nothing_when_no_contact_approaches():
    rng = random.Random(5)
    for _ in range(60):
        boxes = skyline_scene(rng)
        level, _ = levels(len(boxes), contact_graph(boxes, 10, F(1, 60)))
        contacts = find_contacts(boxes, 0)
        solve_velocities(boxes, contacts, level, 0, 1, shock=True)
        before = [b.vy for b in boxes]
        solve_velocities(boxes, contacts, level, 0, 1, shock=True)
        assert [b.vy for b in boxes] == before


def test_shock_propagation_changes_momentum():
    lower = Box(0, 0, F(1, 2), F(1, 2), F(1), vy=F(1))
    upper = Box(0, 1, F(1, 2), F(1, 2), F(3), vy=F(-1))
    boxes = [lower, upper]
    contacts = find_contacts(boxes, 0)
    assert contacts == [(1, 0)]
    p0 = lower.m * lower.vy + upper.m * upper.vy
    solve_velocities(boxes, contacts, [0, 1], 0, 1, shock=True)
    assert (lower.vy, upper.vy) == (1, 1)
    assert (p0, lower.m * lower.vy + upper.m * upper.vy) == (-2, 4)
    # a plastic collision without shock propagation keeps the momentum
    lower.vy, upper.vy = F(1), F(-1)
    solve_velocities(boxes, contacts, [0, 1], 1, 1, shock=False)
    assert (lower.vy, upper.vy) == (F(-1, 2), F(-1, 2))


def test_stack_sinks_without_shock_and_holds_with_it():
    results = {}
    for shock in (False, True):
        boxes = stack(10)
        for _ in range(120):
            _, contacts = step(boxes, 1 / 60, 9.81, 4, 1, shock)
        results[shock] = (penetration(boxes, contacts), boxes[-1].y)
    assert results[True][0] < 1e-12 and abs(results[True][1] - 9.5) < 1e-12
    assert results[False][0] > 0.3 and results[False][1] < 8  # measured: the top box sinks by more than 3 m

History

Guendelman, Bridson and Fedkiw (2003) introduced the contact graph, its levels and shock propagation in their method for nonconvex rigid bodies with stacking, which separates collision, contact and the position update in each time step. They collapsed cycles of the graph into strongly connected components with two depth-first searches, the method of Tarjan being another way to find them. Erleben (2007) made shock propagation part of a velocity-based time stepping method for multibody animation.

References

  1. Eran Guendelman, Robert Bridson and Ronald Fedkiw, Nonconvex rigid bodies with stacking, ACM Transactions on Graphics 22(3), 871-878, 2003 (SIGGRAPH 2003), Section 6 (the time step and the predicted positions), Section 8 (contact processing), Section 8.1 (the contact graph and its strongly connected components) and Section 8.2 (shock propagation), Figures 6 and 7
  2. Kenny Erleben, Velocity-based shock propagation for multibody dynamics animation, ACM Transactions on Graphics 26(2), article 12, 2007, the fixed time stepping scheme with shock propagation for velocity-based complementarity formulations
  3. Erin Catto, Iterative Dynamics with Temporal Coherence, Game Developers Conference, 2005, Section 9.1 (box stacking with and without contact caching)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.graph_and_levels
  • a full proof of time.sweeps
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example