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.
- Solves
- Rigid body simulation
- 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
- Model
- Real RAM
- Properties
- deterministicin placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with normal from to , as on the collision impulse page. A contact approaches when . 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 up and gravity .
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 under gravity alone, with the others fixed. If the moved body then touches , the graph gets the edge : would fall onto . 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.
SHOCK-PROPAGATION-STEP(bodies, contacts, Δτ, S, I)- 1
G ← edges B → A where A, moved under gravity for Δτ, touches B - 2
C_0, C_1, ... ← strongly connected components of G in topological order - 3
level(C) ← 0 if no edge enters C, else 1 + max level of a predecessor of C - 4
repeat S times ▷ contact sweeps - 5
for each level ℓ, from 0 upward - 6
repeat I times: resolve each contact of level ℓ - 7
for each level ℓ, from 0 upward ▷ the shock sweep - 8
repeat I times: resolve each contact of level ℓ - 9
give 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 ramped from up to 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 () and a separate shock sweep, which is the same structure in a simpler form.
Inside one level the contacts are solved 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 m/s, for example after a gravity step. The contact graph is ground box 1 box 2 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 | ||
| box 1 and box 2 | , | |
| box 2 and box 3 | , |
The velocities are : 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 after one sweep.
Momentum. A lower box of mass 1 moves up at m/s, and an upper box of mass 3 on it moves down at m/s. The total momentum is . A plastic collision of the two gives both 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 m/s, and the momentum is . 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 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 for 120 steps. The numbers are measurements from the code of this page:
| boxes | 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 . 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 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 means that the bottom of lies above the top of , 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 is solved, the bodies below are frozen, so each impulse only raises the velocity of a body of level , 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, up, and contacts where rests on , with the normal from to . RESOLVE on a contact computes (vertical components); if and , where is the inverse mass used in the current sweep, it applies : gains and loses . Afterwards . 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 contact sweeps and one shock sweep, each over the levels with passes over the contacts of the level, and each RESOLVE is a constant amount of work. So the step ends after operations for bodies, edges and 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 if and are in the same component, and for every edge 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 comes before , so line L3 reads only levels that are already set. A node gets the level of its component. For an edge between components, the component of is a predecessor of the component of , so .
Lemma 2 (stacks give an acyclic graph). Let the boxes have disjoint interiors, and let the graph have the edge when box , moved down by , overlaps box . Then every edge has . In particular , the graph is acyclic, every component is a single box, and every edge goes to a strictly higher level.
Proof. The moved box overlaps , so the horizontal intervals overlap. Before the move the interiors were disjoint, so the vertical intervals were disjoint: either or . In the second case, moving down keeps , so there is no overlap. Hence the first case holds, and . The bottoms strictly increase along every edge, so there is no cycle, each component is one box, and Lemma 1 gives strictly increasing levels.
When a box rests on with a gap of at most zero and is smaller than the heights of the boxes, the moved overlaps , so the edge 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 of the solve has , and that static bodies have inverse mass zero. Then after lines L7 to L9, every contact has . This holds for any number of contact sweeps before and any .
Proof. A contact belongs to the level . The shock sweep handles the levels in increasing order, and line L9 sets for every body of a level after that level is handled. RESOLVE changes the velocity of a body only if its is nonzero.
Consider the pass over level . Every body of a lower level has by then. Each contact of level has its lower body at a level below , so RESOLVE on it changes only , and only upward (). Bodies of level are never the lower body of a contact of level , because such a contact would belong to a higher level. So during the pass over level , velocities change only for bodies of level , and they only increase. Take a contact of level . Since , RESOLVE runs on it at least once; after that, . Later in the same pass, can only increase and is fixed, so at the end of the pass. After the pass, and both have , so no later RESOLVE changes or .
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 and there are no other contacts, the shock sweep leaves every box at rest, whatever .
Proof. Let box sit on box , with the ground as box 0, so box has level . 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 and 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 sets to , by induction from the ground, which has .
Proposition (no effect when nothing approaches). If no contact has before the shock sweep, the shock sweep changes no velocity. Proof. Each RESOLVE then does nothing, and so nothing changes for the next one.
Momentum is not kept. A RESOLVE with for a body of finite mass changes the momentum of and not that of . So the shock sweep changes the total momentum whenever it acts on such a contact. The page gives an example with momentum before and 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 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 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 time with depth-first search for bodies and edges. Building the graph needs a collision query per moved body; the code of this page tests all pairs in , and an engine uses its broad phase. Each sweep resolves every contact times, so contact sweeps and one shock sweep cost for contacts. Memory is .
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 ; 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 from up to , 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 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 up; this page uses 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag P1VHW8 Edit this page History Report an error Markdown