Algorithmresearch
Incremental potential contact
Also called IPC contact model.
Add a smooth log barrier on distances to the implicit time step energy and cap each Newton step by a collision check, which keeps every state free of intersection if the check is conservative.
- Time
- O(n^3 + s + n c) iterationO(N (n^3 + s + n c)) step
- Space
- Θ(n^2 + s + c) step
- Where
- N = the number of Newton iterations per step; c = the number of obstacle segments; n = the number of free vertices; s = the number of springs
- Model
- Real RAM
- Properties
- deterministicnot exactnot friction in codemonotone objectivepenetration free with conservative ccd
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Minchen Li, Zachary Ferguson, Teseo Schneider, Timothy Langlois, Denis Zorin, Daniele Panozzo, Chenfanfu Jiang, Danny M. Kaufman, 2020
Incremental potential contact (IPC) handles contact in an implicit time step by adding a barrier energy that grows without bound as the distance between two primitives goes to zero. Li et al. (2020) minimize the backward Euler energy plus this barrier with a projected Newton method, and they cap each Newton step by a continuous collision check, so that no primitive touches another on the path between two iterates. If the collision check is conservative, every iterate and every state is free of intersection, and a line search makes the energy decrease at every iteration. The paper handles points against triangles and edges against edges in 3D, with friction; the code on this page is a 2D version with points against fixed segments and no friction.
In plain words
Think of a ball falling onto a floor. Instead of letting it pass into the floor and then pushing it back, IPC puts an invisible cushion just above the floor. The cushion is soft far away and becomes infinitely hard right at the floor, so the ball can never reach it. Each frame, the solver looks for the most comfortable position of everything, balancing motion, springs and cushions. It moves toward that position in steps, and before each step it checks the whole path for a collision and shortens the step if one would happen. So nothing ever passes through anything, even when objects move very fast.
The problem
The input is a set of vertices with masses , positions , velocities , a step , an elastic energy and obstacles. The output is the next state that minimizes the incremental potential of equation (1) of the paper, under the constraint that all distances stay positive:
with the paper's written as . Without contacts, the minimizer is the variational form of the backward Euler step, as in optimization time integration. IPC replaces the constraint by a barrier (equations (5) and (6)):
where is the distance of a pair of primitives, is the activation distance and is the stiffness. The paper adapts during the solve; the code fixes it. In the code, the elastic energy is a sum of 2D springs, the pairs are free vertices against fixed segments, is up and m/s².
The algorithm
IPC-STEP(x, v, Δt, κ, d̂, ε_d)- 1
x̂ <- x + Δt v + Δt² g ▷ pinned vertices stay - 2
z <- x ▷ start at the last state, which is free of intersection - 3
repeat: - 4
p <- -H⁻¹ ∇B(z) ▷ H: every stencil Hessian projected to PSD - 5
if max |p| / Δt < ε_d: stop - 6
α <- min(1, 0.8 · first time of contact on the path z + t p, t in [0, 1]) - 7
while B(z + α p) > B(z): α <- α/2 - 8
z <- z + α p - 9
v <- (z - x)/Δt; x <- z
The barrier (L4). is positive and decreasing on , tends to infinity at and is twice continuously differentiable at , where it meets zero (claim 1). So only pairs closer than add terms, and the Newton method sees a smooth energy.
The projected Hessian (L4). The paper projects the Hessian of each element and each contact stencil to a positive semidefinite matrix by clamping its negative eigenvalues (Section 4.3). For a 2D spring this sets the factor of the transverse term to zero when the spring is compressed. For a point near the end of a segment the barrier Hessian is , equation (7), and the second term is negative semidefinite, so the projection drops it. With the mass matrix added, is positive definite and is a descent direction (claim 2).
The step bound (L6). A Newton step can jump over a thin obstacle, because at the far side can be finite and small. A continuous collision check along the straight path from to finds the first time of contact, and the step is cut to a fraction of it (Section 4.4). In 2D, a point moving on a line meets a segment at most once unless it moves along the line of the segment, and the code solves this in closed form. The paper uses 3D point and triangle and edge and edge tests.
Stopping (L5). Algorithm 1 stops when the Newton direction, scaled to a velocity, is below . The code uses m/s unless a test sets another value.
Friction. Section 5 adds a smoothed Coulomb friction with lagged normal forces and tangent bases. The code leaves it out.
Example
A fast point by hand. A point of mass 1 is at height 0.5 m above a segment from to , with m/s, s, m and . Then . At the start the barrier is not active, so and . The path meets the segment at , so and the point moves to . Each later iteration does the same from the new height, so the heights are ; the code reaches after 10 iterations and stops after 11 at m, above the segment. Plain Newton with a line search but without L6 takes the full step to , where is finite, and the point passes through the segment.
A box drop (measured). A square of side 0.2 m with four vertices of 0.25 kg, edge and diagonal springs of N/m, m and starts with its lowest vertices at 0.5 m and falls at 20 m/s onto flat ground. Over one second of simulation:
| (s) | 1/30 | 1/100 | 1/300 |
|---|---|---|---|
| smallest gap over the run (m) | |||
| most Newton iterations in a step | 10 | 9 | 8 |
| mean Newton iterations per step | 1.13 | 0.73 | 1.34 |
The gap stays positive at every iterate. The box comes to rest at a gap of , and m. The rest gap depends on because the contact force is (claim 5), so a fixed gives a different barrier force at each step size. The paper sets adaptively for this reason.
Rest gap against stiffness (measured). For the same box at rest with s, the gap is , and m for , and . The sum of the contact forces is 9.810 N in all three cases, the weight of the box. A smaller gives a smaller gap, but a stiffer and harder Newton problem near contact.
Correctness
The claims are proved in proofs/correctness.md, in exact arithmetic.
- The barrier (proved). is twice continuously differentiable, positive, decreasing and convex on , zero beyond , and infinite in the limit . The test checks and against central differences and the smooth join at .
- Descent direction (proved). Each stencil projection clamps exactly the negative eigenvalues, so is positive definite and goes downhill when . The test checks the gradient and the unprojected Hessian against central differences, and that the projected matrix is positive semidefinite where the unprojected one is not.
- No intersection (proved, under a hypothesis). The step bound keeps every distance positive on the whole straight path between iterates, so all iterates and all states are free of intersection. In floating point this needs a collision check that is conservative, which is the hypothesis of the paper's guarantee. The test checks the time of contact against sampling for 300 random cases and the fast point above.
- Monotone energy (proved). The line search ends after a finite number of halvings with not larger than before. Convergence of the iterates to a minimizer is not proved here. The test records over all iterations of 30 steps of the box drop.
- Contact forces (proved). At a stationary point, with , nonzero only for , equations (8) and (9). The test checks that the forces of a box at rest sum to its weight.
- No contact (proved). Without active pairs the step is a Newton solve of backward Euler; the test checks a spring against the closed form and free fall against the symplectic Euler value m after 10 steps of s.
Proof: The barrier is smooth, the projected Newton step is a descent step, the step bound keeps every distance positive, and stationary points carry nonnegative contact forcesfull
We use the notation of the page for the 2D code. The free vertices have masses and positions ; pinned vertices are fixed. Springs have rest length , stiffness and energy , and . The obstacles are fixed segments of positive length, and . With on the free vertices, the barrier augmented incremental potential is
with , and for and for . The feasible set is , and outside it. All statements are for exact arithmetic.
The barrier
Lemma 1. On , is , , and , with , and on . Also as , and , and tend to as .
Proof. Let and on . Then , and . In , since and , and . In all three terms are positive. As , and , so all three tend to , which matches the zero function on to second order; so is at . As , and .
Lemma 2. On , each is with . Where the closest point of is inside the segment, (the unit normal toward ) and ; where it is an end point , and , which is positive semidefinite.
Proof. The distance to a closed convex set is off the set, with gradient the unit vector from the closest point. In the two regions the formulas are the derivatives of and . On the border of the regions the closest point is the end point and , so the gradients agree. The Hessian of has eigenvalues (along ) and .
So is on and away from the region borders, and when approaches the boundary of (Lemma 1, since all other terms are bounded on bounded sets). because every term is nonnegative.
The projected Hessian
Lemma 3. The matrix built by the code with project=True is the sum of and, for each stencil, the projection to positive semidefinite matrices of the stencil Hessian (the negative eigenvalues set to zero). So is symmetric positive definite on the free coordinates.
Proof. For a spring with length and direction , the Hessian of in is with and . Its eigenvalues are , with eigenvectors and for an eigenvector of . Replacing by sets the one possibly negative eigenvalue to zero and keeps the eigenvectors, which is the projection. Dropping a pinned end removes rows and columns, which keeps the matrix positive semidefinite.
For a contact pair, the Hessian of in is (equation (7) of the paper). In the interior region and the matrix is . In the end point region it is by Lemma 2, with eigenvalues along and across it (Lemma 1). The projection keeps , which is what the code assembles. The sum of and positive semidefinite matrices is positive definite.
Lemma 4 (descent direction). If , the Newton direction satisfies . If , then .
Proof. since is positive definite (Lemma 3). If then .
The step bound
Lemma 5. Let and let . segment_toi returns the smallest with , or none if there is no such .
Proof. Let have ends and and . The point is in exactly when for some . If , this linear system in has the one solution of Cramer's rule used by the code, so there is at most one touching time, and the code returns it when . If and is not on the line of , the path is parallel to the line and never meets it. If is on the line, the path stays on the line; since it is outside the segment, and it enters first at an end point, at the smaller of the times at which it passes and , which the code computes.
Theorem 6 (no crossing). Let and let be the value of L6. Then for all . Hence every iterate of the step and the result are in : no free vertex touches or crosses a segment at any iterate, nor on the straight path between consecutive iterates.
Proof. Each free vertex moves on the line . If it would touch for some , Lemma 5 gives the first such time (positive because ), and the code sets . If it touches no segment for , then is enough. So for no vertex is on a segment, and all distances are positive. The line search only shrinks , so the accepted point is on this safe path. The start is in by assumption, and induction over the iterations and the steps gives the claim.
The factor keeps the vertex away from the segment, so that the barrier stays finite and the next step does not begin at a touching point. In floating point arithmetic the theorem needs a collision check that does not report a later time than the true one; that is the conservative hypothesis under which the paper states its guarantee. The test checks the time of impact against sampling of the path and fixes a point at 1000 m/s that the plain Newton step would carry through a thin segment.
The line search
Lemma 7 (monotone). If , the halving loop of L7 stops with after a finite number of halvings. So the potential never increases over the iterations of a step.
Proof. By Theorem 6, is finite on , and it is there with (Lemmas 2 and 4). So for all small , and halving reaches such a .
The code also stops the halving when , as a guard against rounding. Then it accepts the point even if rose, but by Theorem 6 that point is still in . The test records at every iteration of 30 steps of a box drop and finds no increase. Lemma 7 says that decreases; it does not prove that the iterates converge to a stationary point, since the simple decrease test is weaker than an Armijo condition.
Stationary points
Theorem 8 (contact forces). If the loop stops with at , then on the free vertices
and only when . This is the backward Euler equation with contact forces along the distance gradients (equations (8) and (9) of the paper).
Proof. By Lemma 4, . Write out and divide by . The sign and support of follow from Lemma 1.
The forces are compressive and vanish beyond , and the gap of an active contact is positive, so this is a relaxed form of the complementarity conditions , , , with the product small when is small. For a body at rest on flat ground the sum of the equals the weight, ; the test checks this to N.
Corollary 9 (no contact is backward Euler). If no pair is within along the whole solve, the step is a Newton solve of the variational backward Euler step. For one spring along its axis, with one end pinned and no gravity, one Newton step reaches the closed form ; for free fall, one step gives , the symplectic Euler update.
Proof. Without active pairs the barrier terms are zero. For the spring along its axis, with the vertex at , the energy restricted to the axis is the quadratic , and the gradient across the axis is zero, so the Newton step is exact. For free fall and the step from any point lands on . With this is , .
Cost
Lemma 10. With free vertices, springs and segments, one Newton iteration of the code costs time and memory, plus for each halving of the line search.
Proof. The assembly visits every spring and every vertex and segment pair once, with work each. The dense LU solve of the system costs and stores numbers. The step bound visits every vertex and segment pair once. One evaluation of costs .
The paper uses a sparse solver and a spatial culling of the pairs (Section 4.6), which replace the and terms in practice.
Complexity
One Newton iteration of the code assembles the gradient and Hessian in , solves the dense system in and checks every vertex and segment pair for the step bound in . Each halving of the line search costs . The memory is . The paper uses a sparse Cholesky solver, culls pairs with a spatial structure and filters the collision checks (Section 4.6). The number of Newton iterations depends on the scene, on and on how close contacts are to .
Properties
- Free of intersection. Given conservative collision checks, no state and no iterate has an intersection, at any (claim 3).
- Monotone solver. The barrier augmented potential decreases at every iteration (claim 4).
- Smooth contact forces. Forces act from a distance and are always compressive; the contact gap is positive, not zero.
- Large time steps. The step is implicit, so stiff springs and fast motion do not force small steps for stability, but the accuracy still depends on .
- Expensive. Each iteration needs a global linear solve and collision checks, so IPC is much slower than penalty contact or XPBD contact.
Variants and improvements
- Friction. Section 5 of the paper adds smoothed friction (equations (10) to (17)), with a mollifier for small slip speeds and lagged normal forces. The paper states that it has no convergence guarantee for the lagged iterations.
- Edge and edge mollifier. In 3D, nearly parallel edges give a nonsmooth distance; Section 4.2 multiplies the barrier by a mollifier.
- Rigid and stiff bodies. Affine body dynamics restricts each body to an affine map, which keeps the barrier and step bound of IPC with far fewer unknowns.
- Codimensional and other elements. Later work applies the same barrier to shells, rods and particles.
- Relation to optimization. The interior point method and other barrier methods of optimization use the same idea of a barrier that keeps iterates feasible; IPC keeps the barrier with a fixed small instead of driving a barrier weight to zero.
When to use it
Use IPC when contact must be free of intersection with no tuning per scene, for example for tight knots, stacked cloth, large deformation with self contact, or a fast moving body that hits thin obstacles. It fits offline simulation and engineering use where a guaranteed result is worth the cost.
Do not use it for real time scenes with many contacts on a tight budget; use VBD, XPBD or penalty contact there. For cloth with a simpler pipeline, robust cloth collision with impact zones is another route to no intersection.
Pitfalls
- Starting in contact. The guarantee needs a start free of intersection. A start with a zero or negative distance gives an infinite barrier.
- Collision checks that are not conservative. A floating point check that reports a late time of contact can let a vertex cross. Use checks that are conservative by design.
- A fixed stiffness. With a fixed the gap and the conditioning change with (the box drop table). The paper adapts from the scene.
- Too large . Contacts act from far away and objects float visibly; too small makes the Newton problem stiff near contact.
- No projection. Without the stencil projection, can be indefinite and the Newton direction can go uphill.
- A step bound of exactly the time of contact. A step that ends on the obstacle gives an infinite barrier. The code takes of the time of contact as a safety margin; this value is a choice of the code.
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
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.
Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""
import math
# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6
# ---------------------------------------------------------------- vectors
def add(a, b):
"""Return a + b."""
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
"""Return a - b."""
return tuple(x - y for x, y in zip(a, b))
def scale(a, s):
"""Return s a for a number s."""
return tuple(s * x for x in a)
def dot(a, b):
"""Return the dot product of a and b."""
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
"""Return the cross product of two 3D vectors."""
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
)
def cross2(a, b):
"""Return the scalar 2D cross product a_x b_y - a_y b_x."""
return a[0] * b[1] - a[1] * b[0]
def norm(a):
"""Return the Euclidean length of a."""
return math.sqrt(sum(x * x for x in a))
def normalize(a):
"""Return a / |a|. Raise ValueError for the zero vector."""
n = norm(a)
if n == 0.0:
raise ValueError("cannot normalize the zero vector")
return tuple(x / n for x in a)
def lerp(a, b, t):
"""Return (1 - t) a + t b."""
return tuple((1 - t) * x + t * y for x, y in zip(a, b))
# ---------------------------------------------------------------- matrices
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None)."""
if m is None:
m = n
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def mul(a, b):
"""Return the matrix product a b."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the vector a x as a tuple."""
return tuple(sum(p * q for p, q in zip(row, x)) for row in a)
def transpose(a):
"""Return the transpose of a."""
return [list(col) for col in zip(*a)]
def _lu(a):
"""Gaussian elimination with partial pivoting on a copy of a square a.
Return (lu, perm, sign), or None if a pivot is exactly zero.
"""
n = len(a)
lu = [list(map(float, row)) for row in a]
perm = list(range(n))
sign = 1.0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(lu[i][k]))
if lu[p][k] == 0.0:
return None
if p != k:
lu[k], lu[p] = lu[p], lu[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
piv = lu[k][k]
for i in range(k + 1, n):
f = lu[i][k] / piv
lu[i][k] = f
if f != 0.0:
rk = lu[k]
ri = lu[i]
for j in range(k + 1, n):
ri[j] -= f * rk[j]
return lu, perm, sign
def det(a):
"""Return the determinant of a square matrix."""
n = len(a)
if n == 1:
return a[0][0]
if n == 2:
return a[0][0] * a[1][1] - a[0][1] * a[1][0]
if n == 3:
return (
a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
)
r = _lu(a)
if r is None:
return 0.0
lu, _, sign = r
d = sign
for i in range(n):
d *= lu[i][i]
return d
def _lu_solve(lu, perm, b):
n = len(lu)
y = [float(b[perm[i]]) for i in range(n)]
for i in range(n):
s = y[i]
row = lu[i]
for j in range(i):
s -= row[j] * y[j]
y[i] = s
for i in range(n - 1, -1, -1):
s = y[i]
row = lu[i]
for j in range(i + 1, n):
s -= row[j] * y[j]
y[i] = s / row[i]
return y
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (returns a list) or a matrix given as a list of rows
(returns a list of rows, one column of x per column of b).
Raise ValueError if a is singular.
"""
r = _lu(a)
if r is None:
raise ValueError("singular matrix")
lu, perm, _ = r
if len(b) > 0 and isinstance(b[0], (list, tuple)):
cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
return [list(row) for row in zip(*cols)]
return _lu_solve(lu, perm, b)
def inv(a):
"""Return the inverse of a square matrix. Raise ValueError if singular."""
return solve(a, eye(len(a)))
# ---------------------------------------------------------------- polar decomposition
def rot2(theta):
"""Return the 2 by 2 rotation matrix by the angle theta."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s], [s, c]]
def _frob(a):
return math.sqrt(sum(x * x for row in a for x in row))
def _sym_eig3(s):
"""Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).
Return (values, vectors), where vectors[k] is the unit eigenvector of
values[k].
"""
a = [list(map(float, row)) for row in s]
v = eye(3)
for _ in range(50):
off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
break
for p, q in ((0, 1), (0, 2), (1, 2)):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(3):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(3):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
for k in range(3):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
values = [a[i][i] for i in range(3)]
vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
return values, vectors
def polar(f, tol=1e-14, max_iter=100):
"""Return (R, S) with F = R S, det R = +1 and S symmetric.
2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
the rotation that maximizes trace(R^T F), and S = R^T F.
3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
is above 1e-2. It stops when the relative change in the Frobenius norm is
at most tol, or after max_iter steps. The iteration gives the orthogonal
polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
If det F > 0, S is symmetric positive definite. If det F < 0, S is
symmetric with one negative eigenvalue. Raise ValueError for a singular
3 by 3 F.
"""
n = len(f)
if n == 2:
theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
r = rot2(theta)
s = mul(transpose(r), f)
s01 = 0.5 * (s[0][1] + s[1][0])
s[0][1] = s[1][0] = s01
return r, s
if n != 3:
raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
x = [list(map(float, row)) for row in f]
change = float("inf")
for _ in range(max_iter):
xi = inv(x)
if change > 1e-2:
g = math.sqrt(_frob(xi) / _frob(x))
else:
g = 1.0
xit = transpose(xi)
y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
x = y
if change <= tol:
break
u = x
s = mul(transpose(u), f)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
if det(u) < 0.0:
values, vectors = _sym_eig3(s)
k = min(range(3), key=lambda i: values[i])
v = vectors[k]
h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
u = mul(u, h)
s = mul(h, s)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
return u, s
# ---------------------------------------------------------------- quaternions
def q_mul(p, q):
"""Return the Hamilton product p q."""
a1, b1, c1, d1 = p
a2, b2, c2, d2 = q
return (
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
)
def q_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return (q[0], -q[1], -q[2], -q[3])
def q_dot(p, q):
"""Return the dot product of p and q as vectors of R^4."""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]
def q_normalize(q):
"""Return q / |q|."""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("cannot normalize the zero quaternion")
return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)
def q_from_axis_angle(axis, angle):
"""Return the unit quaternion of the rotation by angle about axis (any length)."""
u = normalize(axis)
s = math.sin(0.5 * angle)
return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])
def q_to_mat3(q):
"""Return the 3 by 3 rotation matrix of a unit quaternion."""
w, x, y, z = q
return [
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
]
def q_rotate(q, v):
"""Return the vector part of q (0, v) q* for a unit quaternion q."""
r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
return (r[1], r[2], r[3])
def q_log(q):
"""Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).
For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
"""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("log of the zero quaternion")
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
lw = math.log(n)
if vn == 0.0:
return (lw, 0.0, 0.0, 0.0)
phi = math.atan2(vn, q[0])
f = phi / vn
return (lw, f * q[1], f * q[2], f * q[3])
def q_exp(q):
"""Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
ew = math.exp(q[0])
if vn == 0.0:
return (ew, 0.0, 0.0, 0.0)
f = ew * math.sin(vn) / vn
return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])
def slerp(q0, q1, t):
"""Spherical linear interpolation of unit quaternions on the short arc.
If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
normalized linear interpolation is returned. See
robotics/rigid-body-motion/spherical-linear-interpolation.
"""
if q_dot(q0, q1) < 0.0:
q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
w = 2.0 * math.atan2(a, b)
if w < SLERP_SMALL_ANGLE:
return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
s = math.sin(w)
c0 = math.sin((1 - t) * w) / s
c1 = math.sin(t * w) / s
return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))
def q_from_mat3(r):
"""Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.
Shepperd's method: take the largest of the trace, r00, r11 and r22, and
divide by the component that it gives. See
robotics/rigid-body-motion/shepperd-method.
"""
t = r[0][0] + r[1][1] + r[2][2]
k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
if k == 0:
w = math.sqrt(1.0 + t) / 2.0
f = 4.0 * w
q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
elif k == 1:
x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
f = 4.0 * x
q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
elif k == 2:
y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
f = 4.0 * y
q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
else:
z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
f = 4.0 * z
q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
if q[0] < 0.0:
q = (-q[0], -q[1], -q[2], -q[3])
return q
# ---------------------------------------------------------------- transforms
def make_T(r, t):
"""Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
d = len(t)
m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
m.append([0.0] * d + [1.0])
return m
def T_mul(a, b):
"""Return the product a b of two homogeneous transforms."""
return mul(a, b)
def T_inv(m):
"""Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].
The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
"""
d = len(m) - 1
a = [row[:d] for row in m[:d]]
t = [m[i][d] for i in range(d)]
ai = inv(a)
ti = matvec(ai, t)
return make_T(ai, tuple(-x for x in ti))
def T_apply(m, p):
"""Apply a homogeneous transform to a point p and return a tuple."""
d = len(m) - 1
return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))
# ---------------------------------------------------------------- derivatives
def num_grad(f, x, h=1e-6):
"""Return the gradient of a scalar f at x by central differences of step h."""
x = list(x)
g = []
for i in range(len(x)):
xi = x[i]
x[i] = xi + h
fp = f(x)
x[i] = xi - h
fm = f(x)
x[i] = xi
g.append((fp - fm) / (2.0 * h))
return g
incremental_potential_contact.py 229 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-potential-contact/. The authors are listed in prov/TZGCEP.jsonl.
"""Incremental potential contact (Li et al. 2020) for 2D spring bodies and static segments.
One step minimizes the barrier augmented incremental potential (equations (1),
(5) and (6) of the paper, with h written as dt)
B(x) = 1/2 (x - x^)^T M (x - x^) + dt^2 Psi(x) + kappa sum_k b(d_k(x)),
b(d) = -(d - dhat)^2 ln(d / dhat) for 0 < d < dhat, and 0 for d >= dhat,
where x^ = x_n + dt v_n + dt^2 g, Psi is the spring energy and d_k is the
distance from a free vertex to a static segment. The solver is the barrier
aware projected Newton method of Algorithm 1: each stencil Hessian is made
positive semidefinite, the step length is capped by a continuous collision
check along the Newton direction so that no distance reaches zero, and a
backtracking line search makes B decrease. It stops when max |p| / dt < eps_d.
Friction (Section 5 of the paper) is left out. kappa is fixed here; the paper
adapts it. The 2D point against segment setting is a version of the 3D point
against triangle and edge against edge setting of the paper.
"""
import math
from anim import solve
GRAVITY = (0.0, -9.81)
def barrier(d, dhat):
"""b(d), b'(d) and b''(d) of equation (6)."""
if d >= dhat:
return 0.0, 0.0, 0.0
t = d - dhat
lg = math.log(d / dhat)
return -t * t * lg, -2.0 * t * lg - t * t / d, -2.0 * lg - 4.0 * t / d + t * t / (d * d)
def point_segment(p, a, b):
"""Distance from p to the segment ab, its gradient in p and its Hessian in p."""
ex, ey = b[0] - a[0], b[1] - a[1]
ll = ex * ex + ey * ey
s = ((p[0] - a[0]) * ex + (p[1] - a[1]) * ey) / ll
if 0.0 < s < 1.0:
ln = math.sqrt(ll)
n = (-ey / ln, ex / ln)
d = (p[0] - a[0]) * n[0] + (p[1] - a[1]) * n[1]
if d < 0.0:
d, n = -d, (-n[0], -n[1])
return d, n, [[0.0, 0.0], [0.0, 0.0]]
c = a if s <= 0.0 else b
dx, dy = p[0] - c[0], p[1] - c[1]
d = math.hypot(dx, dy)
u = (dx / d, dy / d)
return d, u, [[((1.0 if i == j else 0.0) - u[i] * u[j]) / d for j in range(2)] for i in range(2)]
def segment_toi(p, dp, a, b):
"""The first t in [0, 1] at which p + t dp touches the segment ab, or None."""
ex, ey = b[0] - a[0], b[1] - a[1]
cross = dp[0] * ey - dp[1] * ex
rx, ry = a[0] - p[0], a[1] - p[1]
if cross == 0.0:
if rx * ey - ry * ex != 0.0:
return None
# p moves along the line of the segment: the first contact is at an end point
dd = dp[0] * dp[0] + dp[1] * dp[1]
if dd == 0.0:
return None
ts = [((c[0] - p[0]) * dp[0] + (c[1] - p[1]) * dp[1]) / dd for c in (a, b)]
ts = [t for t in ts if 0.0 <= t <= 1.0]
return min(ts) if ts else None
t = (rx * ey - ry * ex) / cross
s = (rx * dp[1] - ry * dp[0]) / cross
if 0.0 <= t <= 1.0 and 0.0 <= s <= 1.0:
return t
return None
class Scene:
def __init__(self, rest, springs, masses, segments, dhat, kappa, pinned=()):
"""springs are tuples (a, b, rest_length, stiffness); segments are static pairs of points."""
self.rest = [tuple(p) for p in rest]
self.springs = [tuple(s) for s in springs]
self.mass = list(masses)
self.segments = [tuple(map(tuple, s)) for s in segments]
self.dhat, self.kappa = dhat, kappa
self.pinned = set(pinned)
self.free = [i for i in range(len(rest)) if i not in self.pinned]
self.col = {v: k for k, v in enumerate(self.free)}
def min_distance(scene, x):
return min((point_segment(x[i], a, b)[0] for i in scene.free for a, b in scene.segments), default=math.inf)
def potential(scene, x, xhat, dt):
"""B(x). Return infinity if some distance is not positive."""
e = 0.0
for i in scene.free:
e += 0.5 * scene.mass[i] * ((x[i][0] - xhat[i][0]) ** 2 + (x[i][1] - xhat[i][1]) ** 2)
for a, b, r, k in scene.springs:
e += dt * dt * 0.5 * k * (math.dist(x[a], x[b]) - r) ** 2
for i in scene.free:
for sa, sb in scene.segments:
d = point_segment(x[i], sa, sb)[0]
if d <= 0.0:
return math.inf
e += scene.kappa * barrier(d, scene.dhat)[0]
return e
def gradient_and_hessian(scene, x, xhat, dt, project=True):
"""The gradient of B and its Hessian with each stencil projected to PSD, on the free coordinates."""
nf = 2 * len(scene.free)
col = scene.col
g = [0.0] * nf
h = [[0.0] * nf for _ in range(nf)]
for i in scene.free:
for d in range(2):
r = 2 * col[i] + d
g[r] += scene.mass[i] * (x[i][d] - xhat[i][d])
h[r][r] += scene.mass[i]
for a, b, rest, k in scene.springs:
dx, dy = x[a][0] - x[b][0], x[a][1] - x[b][1]
ln = math.hypot(dx, dy)
n = (dx / ln, dy / ln)
s = 1.0 - rest / ln
if project:
s = max(s, 0.0)
c = dt * dt * k
blk = [[c * (n[p] * n[q] + s * ((1.0 if p == q else 0.0) - n[p] * n[q])) for q in range(2)] for p in range(2)]
gs = (c * (ln - rest) * n[0], c * (ln - rest) * n[1])
for v, sv in ((a, 1.0), (b, -1.0)):
if v not in col:
continue
for p in range(2):
g[2 * col[v] + p] += sv * gs[p]
for u, su in ((a, 1.0), (b, -1.0)):
if u not in col:
continue
for p in range(2):
for q in range(2):
h[2 * col[v] + p][2 * col[u] + q] += sv * su * blk[p][q]
for i in scene.free:
for sa, sb in scene.segments:
d, grad, hd = point_segment(x[i], sa, sb)
if d >= scene.dhat:
continue
_, b1, b2 = barrier(d, scene.dhat)
kap = scene.kappa
for p in range(2):
g[2 * col[i] + p] += kap * b1 * grad[p]
# kappa (b'' grad grad^T + b' hess d); b' < 0 and hess d is PSD, so the projection drops that term
for p in range(2):
for q in range(2):
extra = 0.0 if project else kap * b1 * hd[p][q]
h[2 * col[i] + p][2 * col[i] + q] += kap * b2 * grad[p] * grad[q] + extra
return g, h
def step_bound(scene, x, p):
"""The largest alpha in (0, 1] such that x + t alpha p touches no segment for t in [0, 1), scaled by 0.8."""
t_min = 1.0
for i in scene.free:
dp = (p[2 * scene.col[i]], p[2 * scene.col[i] + 1])
for a, b in scene.segments:
t = segment_toi(x[i], dp, a, b)
if t is not None:
t_min = min(t_min, 0.8 * t)
return t_min
def predict(scene, x, v, dt, gravity=GRAVITY):
return [(q[0] + dt * u[0] + dt * dt * gravity[0], q[1] + dt * u[1] + dt * dt * gravity[1])
if i not in scene.pinned else tuple(q) for i, (q, u) in enumerate(zip(x, v))]
def ipc_step(scene, x, v, dt, eps_d=1e-6, gravity=GRAVITY, max_iter=200, history=None):
"""One step by barrier aware projected Newton (Algorithm 1). Return (x, v, iterations)."""
xhat = predict(scene, x, v, dt, gravity) # @line L1
z = [tuple(q) for q in x] # @line L2
e_prev = potential(scene, z, xhat, dt)
if history is not None:
history.append(e_prev)
it = 0
while it < max_iter: # @line L3
g, h = gradient_and_hessian(scene, z, xhat, dt)
p = solve(h, [-gi for gi in g]) # @line L4
if max(abs(c) for c in p) / dt < eps_d: # @line L5
break
alpha = min(1.0, step_bound(scene, z, p)) # @line L6
while True:
trial = list(z)
for i in scene.free:
c = scene.col[i]
trial[i] = (z[i][0] + alpha * p[2 * c], z[i][1] + alpha * p[2 * c + 1])
e = potential(scene, trial, xhat, dt)
if e <= e_prev or alpha < 1e-12: # @line L7
break
alpha *= 0.5
z, e_prev = trial, e # @line L8
if history is not None:
history.append(e_prev)
it += 1
v_new = [((a[0] - b[0]) / dt, (a[1] - b[1]) / dt) for a, b in zip(z, x)] # @line L9
return z, v_new, it
def contact_forces(scene, x, dt):
"""lambda_k = -(kappa / dt^2) b'(d_k) >= 0 for the active pairs (equation (9))."""
out = []
for i in scene.free:
for a, b in scene.segments:
d = point_segment(x[i], a, b)[0]
if d < scene.dhat:
out.append((i, -scene.kappa / (dt * dt) * barrier(d, scene.dhat)[1]))
return out
def box(center, size, stiffness, mass, segments, dhat, kappa):
"""A square of four vertices with edge and diagonal springs."""
cx, cy = center
hs = 0.5 * size
rest = [(cx - hs, cy - hs), (cx + hs, cy - hs), (cx + hs, cy + hs), (cx - hs, cy + hs)]
pairs = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (1, 3)]
springs = [(a, b, math.dist(rest[a], rest[b]), stiffness) for a, b in pairs]
return Scene(rest, springs, [mass] * 4, segments, dhat, kappa)
test_incremental_potential_contact.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-potential-contact/. The authors are listed in prov/TZGCEP.jsonl.
"""Tests of incremental potential contact: derivatives, the collision check, monotone Newton and no crossing."""
import math
import random
from anim import num_grad
import incremental_potential_contact as ipc
GROUND = [((-5.0, 0.0), (5.0, 0.0))]
def flat(x, free):
return [c for i in free for c in x[i]]
def unflat(z, x, free):
y = list(x)
for k, i in enumerate(free):
y[i] = (z[2 * k], z[2 * k + 1])
return y
def is_psd(h):
"""Cholesky of h + 1e-9 (1 + max |h_ii|) I succeeds."""
n = len(h)
shift = 1e-9 * (1.0 + max(abs(h[i][i]) for i in range(n)))
low = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = h[i][j] + (shift if i == j else 0.0) - sum(low[i][k] * low[j][k] for k in range(j))
if i == j:
if s <= 0.0:
return False
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return True
def test_barrier_derivatives_and_smoothness():
dhat = 0.01
for d in (1e-4, 1e-3, 4e-3, 9e-3):
b, b1, b2 = ipc.barrier(d, dhat)
assert b > 0.0 and b1 < 0.0 and b2 > 0.0
assert abs(num_grad(lambda z: ipc.barrier(z[0], dhat)[0], [d], 1e-8)[0] - b1) < 1e-5 * abs(b1)
assert abs(num_grad(lambda z: ipc.barrier(z[0], dhat)[1], [d], 1e-8)[0] - b2) < 1e-5 * abs(b2)
near = ipc.barrier(dhat * (1.0 - 1e-6), dhat)
assert all(abs(c) < 1e-5 for c in near)
assert ipc.barrier(dhat, dhat) == (0.0, 0.0, 0.0)
assert ipc.barrier(1e-12, dhat)[0] > 1e-3
def test_gradient_and_hessian_against_num_grad():
rng = random.Random(7)
segs = GROUND + [((0.3, -1.0), (0.3, 1.0))]
sc = ipc.box((0.15, 0.1), 0.2, 300.0, 0.25, segs, 0.06, 2.0)
x = [(p[0] + rng.uniform(-0.02, 0.02), p[1] + rng.uniform(-0.02, 0.02)) for p in sc.rest]
x[0] = (0.07, 0.03)
x[1] = (0.27, 0.01)
xhat = [(p[0] + 0.01, p[1] - 0.02) for p in x]
dt = 0.02
assert ipc.min_distance(sc, x) < sc.dhat
g, h = ipc.gradient_and_hessian(sc, x, xhat, dt, project=False)
z0 = flat(x, sc.free)
ng = num_grad(lambda z: ipc.potential(sc, unflat(z, x, sc.free), xhat, dt), z0, 1e-7)
scale = max(abs(c) for c in g)
assert max(abs(a - b) for a, b in zip(g, ng)) < 1e-5 * scale
for r in range(len(z0)):
col = num_grad(lambda z: ipc.gradient_and_hessian(sc, unflat(z, x, sc.free), xhat, dt, False)[0][r], z0, 1e-7)
for c in range(len(z0)):
assert abs(col[c] - h[r][c]) < 1e-4 * max(1.0, abs(h[r][c]))
def test_projected_hessian_is_psd_and_unprojected_can_be_indefinite():
"""The point near a segment end has an indefinite barrier Hessian; the projection removes the negative part."""
sc = ipc.Scene([(0.0, 0.0), (0.0, 0.0)], [(0, 1, 1.0, 50.0)], [1.0, 1.0], [((-1.0, 0.0), (0.0, 0.0))], 0.1, 10.0)
x = [(0.01, 0.02), (0.01, 0.52)]
_, h0 = ipc.gradient_and_hessian(sc, x, x, 0.1, project=False)
_, h1 = ipc.gradient_and_hessian(sc, x, x, 0.1, project=True)
big = [[1e3 * c for c in row] for row in h0]
for i in range(4):
big[i][i] -= 1e3 * 1.0
assert not is_psd(big)
sub = [[h1[i][j] - (1.0 if i == j else 0.0) for j in range(4)] for i in range(4)]
assert is_psd(sub)
def test_time_of_impact_against_sampling():
rng = random.Random(11)
hits = 0
n = 1000
for _ in range(300):
a = (rng.uniform(-1, 1), rng.uniform(-1, 1))
b = (rng.uniform(-1, 1), rng.uniform(-1, 1))
p = (rng.uniform(-1, 1), rng.uniform(-1, 1))
dp = (rng.uniform(-2, 2), rng.uniform(-2, 2))
t = ipc.segment_toi(p, dp, a, b)
ex, ey = b[0] - a[0], b[1] - a[1]
pts = [(p[0] + s / n * dp[0], p[1] + s / n * dp[1]) for s in range(n + 1)]
side = [ex * (q[1] - a[1]) - ey * (q[0] - a[0]) for q in pts]
par = [((q[0] - a[0]) * ex + (q[1] - a[1]) * ey) / (ex * ex + ey * ey) for q in pts]
crossings = [k for k in range(n) if side[k] * side[k + 1] < 0.0 and 0.0 < par[k] < 1.0 and 0.0 < par[k + 1] < 1.0]
if t is None:
assert not crossings
else:
hits += 1
q = (p[0] + t * dp[0], p[1] + t * dp[1])
assert ipc.point_segment(q, a, b)[0] < 1e-9
assert all(abs(k / n - t) <= 1.0 / n for k in crossings)
assert all(side[j] * side[0] > 0.0 for j in range(int(t * n)))
assert 30 < hits < 270
assert ipc.segment_toi((-2.0, 0.0), (3.0, 0.0), (-1.0, 0.0), (1.0, 0.0)) == 1.0 / 3.0
def test_one_spring_without_contact_is_backward_euler():
m, k, r, dt, y = 1.0, 100.0, 1.0, 0.1, 1.5
sc = ipc.Scene([(0.0, 0.0), (1.5, 0.0)], [(0, 1, r, k)], [m, m], GROUND[:0], 0.01, 1.0, pinned=[0])
x1, _, it = ipc.ipc_step(sc, [(0.0, 0.0), (1.5, 0.0)], [(0.0, 0.0)] * 2, dt, gravity=(0.0, 0.0), eps_d=1e-12)
assert abs(x1[1][0] - (m * y + dt * dt * k * r) / (m + dt * dt * k)) < 1e-14 and abs(x1[1][1]) < 1e-15
assert it == 1
def test_potential_never_increases_and_distance_stays_positive():
sc = ipc.box((0.0, 0.6), 0.2, 1e4, 0.25, GROUND, 1e-3, 1.0)
x, v = list(sc.rest), [(0.0, -20.0)] * 4
dt = 1.0 / 30.0
for _ in range(30):
hist = []
x, v, _ = ipc.ipc_step(sc, x, v, dt, history=hist)
assert all(b <= a for a, b in zip(hist, hist[1:]))
assert ipc.min_distance(sc, x) > 0.0 and all(p[1] > 0.0 for p in x)
def test_fast_point_does_not_tunnel_through_a_thin_wall():
sc = ipc.Scene([(0.0, 0.5)], [], [1.0], [((-1.0, 0.0), (1.0, 0.0))], 1e-3, 1.0)
x, v = [(0.0, 0.5)], [(0.0, -1000.0)]
for _ in range(5):
x, v, _ = ipc.ipc_step(sc, x, v, 1.0 / 30.0)
assert 0.0 < x[0][1] < 1e-3
def test_resting_contact_forces_carry_the_weight():
sc = ipc.box((0.0, 0.1005), 0.2, 1e4, 0.25, GROUND, 1e-3, 1.0)
x, v = list(sc.rest), [(0.0, 0.0)] * 4
dt = 1.0 / 100.0
for _ in range(60):
x, v, _ = ipc.ipc_step(sc, x, v, dt, eps_d=1e-8)
lam = ipc.contact_forces(sc, x, dt)
assert len(lam) == 2 and all(f >= 0.0 for _, f in lam)
assert abs(sum(f for _, f in lam) - 4 * 0.25 * 9.81) < 1e-4
assert max(abs(c) for u in v for c in u) < 1e-4
def test_free_fall_is_symplectic_euler():
sc = ipc.Scene([(0.0, 0.0)], [], [1.0], [], 1e-3, 1.0)
x, v = [(0.0, 0.0)], [(0.0, 0.0)]
for _ in range(10):
x, v, _ = ipc.ipc_step(sc, x, v, 0.1)
assert abs(x[0][1] + 5.3955) < 1e-12
History
Barrier methods are old tools of constrained optimization. Contact in graphics used penalty forces, impulses or complementarity solvers, each with trade-offs between robustness and parameter tuning. Li, Ferguson, Schneider, Langlois, Zorin, Panozzo, Jiang and Kaufman (2020) combined a smooth barrier, a projected Newton solve and a step bound from continuous collision checks into IPC, and presented it at SIGGRAPH 2020.
References
- Minchen Li, Zachary Ferguson, Teseo Schneider, Timothy Langlois, Denis Zorin, Daniele Panozzo, Chenfanfu Jiang and Danny M. Kaufman, Incremental potential contact: intersection- and inversion-free, large-deformation dynamics, ACM Transactions on Graphics 39(4), Article 49, 2020 (SIGGRAPH 2020), Section 2 (equation (1) the incremental potential, equations (2) and (3) admissibility and complementarity), Section 4 (Algorithm 1, barrier aware projected Newton), Sections 4.1 and 4.2 (equations (5) and (6), the barrier), Section 4.3 (the projected Hessian, equation (7)), Section 4.4 (the step bound by collision checks), Section 4.5 (equations (8) and (9), contact forces), Section 5 (friction)
Where this leads
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 TZGCEP Edit this page History Report an error Markdown