Algorithm Search⌘K

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
Properties
deterministicnot exactnot friction in codemonotone objectivepenetration free with conservative ccd
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 mim_i, positions xn\mathbf x^n, velocities vn\mathbf v^n, a step Δt\Delta t, an elastic energy Ψ\Psi and obstacles. The output is the next state xn+1\mathbf x^{n+1} that minimizes the incremental potential of equation (1) of the paper, under the constraint that all distances stay positive:

E(x)=12(x−x^)TM(x−x^)+Δt2Ψ(x),x^=xn+Δtvn+Δt2M−1fe,E(\mathbf x) = \tfrac12(\mathbf x - \hat{\mathbf x})^T M(\mathbf x - \hat{\mathbf x}) + \Delta t^2\Psi(\mathbf x), \qquad \hat{\mathbf x} = \mathbf x^n + \Delta t\mathbf v^n + \Delta t^2 M^{-1}\mathbf f_e,

with the paper's hh written as Δt\Delta t. 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)):

B(x)=E(x)+κ∑kb(dk(x)),b(d)=−(d−d^)2ln⁡dd^ for 0<d<d^,b(d)=0 for d≥d^,B(\mathbf x) = E(\mathbf x) + \kappa\sum_k b(d_k(\mathbf x)), \qquad b(d) = -(d - \hat d)^2\ln\frac{d}{\hat d} \text{ for } 0 < d < \hat d, \quad b(d) = 0 \text{ for } d \ge \hat d,

where dkd_k is the distance of a pair of primitives, d^\hat d is the activation distance and κ>0\kappa > 0 is the stiffness. The paper adapts κ\kappa 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, yy is up and g=(0,−9.81)\mathbf g = (0, -9.81) m/s².

The algorithm

  1. IPC-STEP(x, v, Δt, κ, d̂, ε_d)
  2. 1x̂ <- x + Δt v + Δt² g ▷ pinned vertices stay
  3. 2z <- x ▷ start at the last state, which is free of intersection
  4. 3repeat:
  5. 4p <- -H⁻¹ ∇B(z) ▷ H: every stencil Hessian projected to PSD
  6. 5if max |p| / Δt < ε_d: stop
  7. 6α <- min(1, 0.8 · first time of contact on the path z + t p, t in [0, 1])
  8. 7while B(z + α p) > B(z): α <- α/2
  9. 8z <- z + α p
  10. 9v <- (z - x)/Δt; x <- z

The barrier (L4). bb is positive and decreasing on (0,d^)(0, \hat d), tends to infinity at 00 and is twice continuously differentiable at d^\hat d, where it meets zero (claim 1). So only pairs closer than d^\hat d 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 1−r/ℓ1 - r/\ell of the transverse term to zero when the spring is compressed. For a point near the end of a segment the barrier Hessian is κ(b′′∇d∇dT+b′∇2d)\kappa(b''\nabla d\nabla d^T + b'\nabla^2 d), equation (7), and the second term is negative semidefinite, so the projection drops it. With the mass matrix added, HH is positive definite and p\mathbf p is a descent direction (claim 2).

The step bound (L6). A Newton step can jump over a thin obstacle, because BB at the far side can be finite and small. A continuous collision check along the straight path from z\mathbf z to z+p\mathbf z + \mathbf p 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 εd\varepsilon_d. The code uses εd=10−6\varepsilon_d = 10^{-6} 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 (−1,0)(-1, 0) to (1,0)(1, 0), with v=−1000v = -1000 m/s, Δt=1/30\Delta t = 1/30 s, d^=10−3\hat d = 10^{-3} m and κ=1\kappa = 1. Then y^=0.5−33.333−0.0109=−32.844\hat y = 0.5 - 33.333 - 0.0109 = -32.844. At the start the barrier is not active, so H=1H = 1 and p=y^−0.5=−33.344p = \hat y - 0.5 = -33.344. The path meets the segment at t=0.5/33.344t = 0.5/33.344, so α=0.8t\alpha = 0.8t and the point moves to y=0.5−0.8⋅0.5=0.1y = 0.5 - 0.8 \cdot 0.5 = 0.1. Each later iteration does the same from the new height, so the heights are 0.5,0.1,0.02,0.004,8×10−4,…0.5, 0.1, 0.02, 0.004, 8 \times 10^{-4}, \dots; the code reaches 5.1×10−85.1 \times 10^{-8} after 10 iterations and stops after 11 at 1.6×10−81.6 \times 10^{-8} m, above the segment. Plain Newton with a line search but without L6 takes the full step to y=−32.844y = -32.844, where BB 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 k=104k = 10^4 N/m, d^=10−3\hat d = 10^{-3} m and κ=1\kappa = 1 starts with its lowest vertices at 0.5 m and falls at 20 m/s onto flat ground. Over one second of simulation:

Δt\Delta t (s) 1/30 1/100 1/300
smallest gap over the run (m) 4.1×10−64.1 \times 10^{-6} 2.1×10−52.1 \times 10^{-5} 8.4×10−58.4 \times 10^{-5}
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 2.1×10−42.1 \times 10^{-4}, 6.5×10−46.5 \times 10^{-4} and 8.7×10−48.7 \times 10^{-4} m. The rest gap depends on Δt\Delta t because the contact force is λ=−κb′(d)/Δt2\lambda = -\kappa b'(d)/\Delta t^2 (claim 5), so a fixed κ\kappa gives a different barrier force at each step size. The paper sets κ\kappa adaptively for this reason.

Rest gap against stiffness (measured). For the same box at rest with Δt=0.01\Delta t = 0.01 s, the gap is 2.3×10−52.3 \times 10^{-5}, 6.5×10−46.5 \times 10^{-4} and 9.6×10−49.6 \times 10^{-4} m for κ=10−2\kappa = 10^{-2}, 11 and 10210^2. The sum of the contact forces is 9.810 N in all three cases, the weight of the box. A smaller κ\kappa 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.

  1. The barrier (proved). bb is twice continuously differentiable, positive, decreasing and convex on (0,d^)(0, \hat d), zero beyond d^\hat d, and infinite in the limit d→0d \to 0. The test checks b′b' and b′′b'' against central differences and the smooth join at d^\hat d.
  2. Descent direction (proved). Each stencil projection clamps exactly the negative eigenvalues, so HH is positive definite and p\mathbf p goes downhill when ∇B≠0\nabla B \ne 0. 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.
  3. 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.
  4. Monotone energy (proved). The line search ends after a finite number of halvings with BB not larger than before. Convergence of the iterates to a minimizer is not proved here. The test records BB over all iterations of 30 steps of the box drop.
  5. Contact forces (proved). At a stationary point, M(x−x^)/Δt2=−∇Ψ+∑λk∇dkM(\mathbf x - \hat{\mathbf x})/\Delta t^2 = -\nabla\Psi + \sum\lambda_k\nabla d_k with λk=−κb′(dk)/Δt2≥0\lambda_k = -\kappa b'(d_k)/\Delta t^2 \ge 0, nonzero only for dk<d^d_k < \hat d, equations (8) and (9). The test checks that the forces of a box at rest sum to its weight.
  6. 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 −5.3955-5.3955 m after 10 steps of 0.10.1 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 mi>0m_i > 0 and positions xi∈R2\mathbf x_i \in \mathbb R^2; pinned vertices are fixed. Springs s=(a,b)s = (a, b) have rest length rs>0r_s > 0, stiffness ks>0k_s > 0 and energy Es=ks2(∣xa−xb∣−rs)2E_s = \frac{k_s}{2}(|\mathbf x_a - \mathbf x_b| - r_s)^2, and Ψ=∑sEs\Psi = \sum_s E_s. The obstacles are fixed segments S1,…,ScS_1, \dots, S_c of positive length, and dik(x)=dist⁡(xi,Sk)d_{ik}(\mathbf x) = \operatorname{dist}(\mathbf x_i, S_k). With x^=xn+Δtvn+Δt2g\hat{\mathbf x} = \mathbf x^n + \Delta t\mathbf v^n + \Delta t^2\mathbf g on the free vertices, the barrier augmented incremental potential is

B(x)=12(x−x^)TM(x−x^)+Δt2Ψ(x)+κ∑i,kb(dik(x)),B(\mathbf x) = \tfrac12(\mathbf x - \hat{\mathbf x})^T M(\mathbf x - \hat{\mathbf x}) + \Delta t^2\Psi(\mathbf x) + \kappa\sum_{i,k} b(d_{ik}(\mathbf x)),

with κ>0\kappa > 0, d^>0\hat d > 0 and b(d)=−(d−d^)2ln⁡(d/d^)b(d) = -(d - \hat d)^2\ln(d/\hat d) for 0<d<d^0 < d < \hat d and b(d)=0b(d) = 0 for d≥d^d \ge \hat d. The feasible set is A={x:dik(x)>0 for all i,k}\mathcal A = \{\mathbf x : d_{ik}(\mathbf x) > 0 \text{ for all } i, k\}, and B=+∞B = +\infty outside it. All statements are for exact arithmetic.

The barrier

Lemma 1. On (0,∞)(0, \infty), bb is C2C^2, b≥0b \ge 0, b′≤0b' \le 0 and b′′≥0b'' \ge 0, with b>0b > 0, b′<0b' < 0 and b′′>0b'' > 0 on (0,d^)(0, \hat d). Also b(d)→+∞b(d) \to +\infty as d→0+d \to 0^+, and bb, b′b' and b′′b'' tend to 00 as d→d^−d \to \hat d^-.

Proof. Let t=d−d^<0t = d - \hat d < 0 and ℓ=ln⁡(d/d^)<0\ell = \ln(d/\hat d) < 0 on (0,d^)(0, \hat d). Then b=−t2ℓ>0b = -t^2\ell > 0, b′=−2tℓ−t2/db' = -2t\ell - t^2/d and b′′=−2ℓ−4t/d+t2/d2b'' = -2\ell - 4t/d + t^2/d^2. In b′b', −2tℓ<0-2t\ell < 0 since t<0t < 0 and ℓ<0\ell < 0, and −t2/d<0-t^2/d < 0. In b′′b'' all three terms are positive. As d→d^d \to \hat d, t→0t \to 0 and ℓ→0\ell \to 0, so all three tend to 00, which matches the zero function on [d^,∞)[\hat d, \infty) to second order; so bb is C2C^2 at d^\hat d. As d→0d \to 0, t2→d^2t^2 \to \hat d^2 and −ℓ→+∞-\ell \to +\infty. □\square

Lemma 2. On A\mathcal A, each dikd_{ik} is C1C^1 with ∣∇dik∣=1|\nabla d_{ik}| = 1. Where the closest point of SkS_k is inside the segment, ∇d=n\nabla d = \mathbf n (the unit normal toward xi\mathbf x_i) and ∇2d=0\nabla^2 d = 0; where it is an end point c\mathbf c, ∇d=u=(xi−c)/d\nabla d = \mathbf u = (\mathbf x_i - \mathbf c)/d and ∇2d=(I−uuT)/d\nabla^2 d = (I - \mathbf u\mathbf u^T)/d, which is positive semidefinite.

Proof. The distance to a closed convex set is C1C^1 off the set, with gradient the unit vector from the closest point. In the two regions the formulas are the derivatives of n⋅(x−a)\mathbf n\cdot(\mathbf x - \mathbf a) and ∣x−c∣|\mathbf x - \mathbf c|. On the border of the regions the closest point is the end point and u=n\mathbf u = \mathbf n, so the gradients agree. The Hessian of ∣x−c∣|\mathbf x - \mathbf c| has eigenvalues 00 (along u\mathbf u) and 1/d1/d. □\square

So BB is C1C^1 on A\mathcal A and C2C^2 away from the region borders, and B(x)→+∞B(\mathbf x) \to +\infty when x\mathbf x approaches the boundary of A\mathcal A (Lemma 1, since all other terms are bounded on bounded sets). B≥0B \ge 0 because every term is nonnegative.

The projected Hessian

Lemma 3. The matrix HH built by the code with project=True is the sum of MM and, for each stencil, the projection to positive semidefinite matrices of the stencil Hessian (the negative eigenvalues set to zero). So HH is symmetric positive definite on the free coordinates.

Proof. For a spring with length ℓ\ell and direction n\mathbf n, the Hessian of Δt2Es\Delta t^2 E_s in (xa,xb)(\mathbf x_a, \mathbf x_b) is (K−K−KK)\begin{pmatrix} K & -K \\ -K & K\end{pmatrix} with K=Δt2ks(nnT+σ(I−nnT))K = \Delta t^2 k_s(\mathbf n\mathbf n^T + \sigma(I - \mathbf n\mathbf n^T)) and σ=1−rs/ℓ\sigma = 1 - r_s/\ell. Its eigenvalues are 0,0,2Δt2ks,2Δt2ksσ0, 0, 2\Delta t^2 k_s, 2\Delta t^2 k_s\sigma, with eigenvectors (w,w)(\mathbf w, \mathbf w) and (w,−w)(\mathbf w, -\mathbf w) for w\mathbf w an eigenvector of KK. Replacing σ\sigma by max⁡(σ,0)\max(\sigma, 0) 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 κb(d)\kappa b(d) in xi\mathbf x_i is κ(b′′∇d∇dT+b′∇2d)\kappa(b''\nabla d\nabla d^T + b'\nabla^2 d) (equation (7) of the paper). In the interior region ∇2d=0\nabla^2 d = 0 and the matrix is κb′′nnT⪰0\kappa b''\mathbf n\mathbf n^T \succeq 0. In the end point region it is κb′′uuT+κ(b′/d)(I−uuT)\kappa b''\mathbf u\mathbf u^T + \kappa(b'/d)(I - \mathbf u\mathbf u^T) by Lemma 2, with eigenvalues κb′′≥0\kappa b'' \ge 0 along u\mathbf u and κb′/d≤0\kappa b'/d \le 0 across it (Lemma 1). The projection keeps κb′′uuT\kappa b''\mathbf u\mathbf u^T, which is what the code assembles. The sum of M≻0M \succ 0 and positive semidefinite matrices is positive definite. □\square

Lemma 4 (descent direction). If g=∇B(z)≠0\mathbf g = \nabla B(\mathbf z) \ne 0, the Newton direction p=−H−1g\mathbf p = -H^{-1}\mathbf g satisfies gTp<0\mathbf g^T\mathbf p < 0. If p=0\mathbf p = 0, then ∇B(z)=0\nabla B(\mathbf z) = 0.

Proof. gTp=−gTH−1g<0\mathbf g^T\mathbf p = -\mathbf g^T H^{-1}\mathbf g < 0 since H−1H^{-1} is positive definite (Lemma 3). If p=0\mathbf p = 0 then g=−Hp=0\mathbf g = -H\mathbf p = 0. □\square

The step bound

Lemma 5. Let q∉S\mathbf q \notin S and let q(t)=q+t Δq\mathbf q(t) = \mathbf q + t\,\Delta\mathbf q. segment_toi returns the smallest t∈[0,1]t \in [0, 1] with q(t)∈S\mathbf q(t) \in S, or none if there is no such tt.

Proof. Let SS have ends a\mathbf a and b\mathbf b and e=b−a\mathbf e = \mathbf b - \mathbf a. The point q(t)\mathbf q(t) is in SS exactly when q(t)=a+se\mathbf q(t) = \mathbf a + s\mathbf e for some s∈[0,1]s \in [0, 1]. If Δq×e≠0\Delta\mathbf q \times \mathbf e \ne 0, this linear system in (t,s)(t, s) 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 t,s∈[0,1]t, s \in [0, 1]. If Δq×e=0\Delta\mathbf q \times \mathbf e = 0 and q\mathbf q is not on the line of SS, the path is parallel to the line and never meets it. If q\mathbf q is on the line, the path stays on the line; since q∉S\mathbf q \notin S it is outside the segment, and it enters SS first at an end point, at the smaller of the times at which it passes a\mathbf a and b\mathbf b, which the code computes. □\square

Theorem 6 (no crossing). Let z∈A\mathbf z \in \mathcal A and let α\alpha be the value of L6. Then z+τp∈A\mathbf z + \tau\mathbf p \in \mathcal A for all τ∈[0,α]\tau \in [0, \alpha]. Hence every iterate of the step and the result are in A\mathcal A: 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 zi+τpi\mathbf z_i + \tau\mathbf p_i. If it would touch SkS_k for some τ∈[0,1]\tau \in [0, 1], Lemma 5 gives the first such time tik>0t_{ik} > 0 (positive because zi∉Sk\mathbf z_i \notin S_k), and the code sets α≤0.8 tik<tik\alpha \le 0.8\,t_{ik} < t_{ik}. If it touches no segment for τ∈[0,1]\tau \in [0, 1], then α≤1\alpha \le 1 is enough. So for τ≤α\tau \le \alpha no vertex is on a segment, and all distances are positive. The line search only shrinks α\alpha, so the accepted point is on this safe path. The start z=xn\mathbf z = \mathbf x^n is in A\mathcal A by assumption, and induction over the iterations and the steps gives the claim. □\square

The factor 0.80.8 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.

Lemma 7 (monotone). If ∇B(z)≠0\nabla B(\mathbf z) \ne 0, the halving loop of L7 stops with B(z+αp)≤B(z)B(\mathbf z + \alpha\mathbf p) \le B(\mathbf z) after a finite number of halvings. So the potential never increases over the iterations of a step.

Proof. By Theorem 6, ϕ(τ)=B(z+τp)\phi(\tau) = B(\mathbf z + \tau\mathbf p) is finite on [0,α0][0, \alpha_0], and it is C1C^1 there with ϕ′(0)=gTp<0\phi'(0) = \mathbf g^T\mathbf p < 0 (Lemmas 2 and 4). So ϕ(τ)<ϕ(0)\phi(\tau) < \phi(0) for all small τ>0\tau > 0, and halving reaches such a τ\tau. □\square

The code also stops the halving when α<10−12\alpha < 10^{-12}, as a guard against rounding. Then it accepts the point even if BB rose, but by Theorem 6 that point is still in A\mathcal A. The test records BB at every iteration of 30 steps of a box drop and finds no increase. Lemma 7 says that BB 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 p=0\mathbf p = 0 at xn+1\mathbf x^{n+1}, then on the free vertices

Mxn+1−x^Δt2=−∇Ψ(xn+1)+∑i,kλik∇dik,λik=−κΔt2b′(dik)≥0,M\frac{\mathbf x^{n+1} - \hat{\mathbf x}}{\Delta t^2} = -\nabla\Psi(\mathbf x^{n+1}) + \sum_{i,k}\lambda_{ik}\nabla d_{ik}, \qquad \lambda_{ik} = -\frac{\kappa}{\Delta t^2}b'(d_{ik}) \ge 0,

and λik>0\lambda_{ik} > 0 only when dik<d^d_{ik} < \hat d. This is the backward Euler equation with contact forces along the distance gradients (equations (8) and (9) of the paper).

Proof. By Lemma 4, ∇B=0\nabla B = 0. Write out ∇B=M(x−x^)+Δt2∇Ψ+κ∑b′(dik)∇dik\nabla B = M(\mathbf x - \hat{\mathbf x}) + \Delta t^2\nabla\Psi + \kappa\sum b'(d_{ik})\nabla d_{ik} and divide by Δt2\Delta t^2. The sign and support of λik\lambda_{ik} follow from Lemma 1. □\square

The forces are compressive and vanish beyond d^\hat d, and the gap of an active contact is positive, so this is a relaxed form of the complementarity conditions λ≥0\lambda \ge 0, d≥0d \ge 0, λd=0\lambda d = 0, with the product small when d^\hat d is small. For a body at rest on flat ground the sum of the λik\lambda_{ik} equals the weight, ∑mig\sum m_i g; the test checks this to 10−410^{-4} N.

Corollary 9 (no contact is backward Euler). If no pair is within d^\hat d 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 x=(my+Δt2kr)/(m+Δt2k)x = (m y + \Delta t^2 k r)/(m + \Delta t^2 k); for free fall, one step gives xn+1=x^\mathbf x^{n+1} = \hat{\mathbf x}, the symplectic Euler update.

Proof. Without active pairs the barrier terms are zero. For the spring along its axis, with the vertex at y>ry > r, the energy restricted to the axis is the quadratic m2(x−y)2+Δt2k2(x−r)2\frac m2(x - y)^2 + \frac{\Delta t^2k}{2}(x - r)^2, and the gradient across the axis is zero, so the Newton step is exact. For free fall B=12∣x−x^∣M2B = \frac12|\mathbf x - \hat{\mathbf x}|^2_M and the step from any point lands on x^\hat{\mathbf x}. With vn+1=(xn+1−xn)/Δt\mathbf v^{n+1} = (\mathbf x^{n+1} - \mathbf x^n)/\Delta t this is vn+1=vn+Δtg\mathbf v^{n+1} = \mathbf v^n + \Delta t\mathbf g, xn+1=xn+Δtvn+1\mathbf x^{n+1} = \mathbf x^n + \Delta t\mathbf v^{n+1}. □\square

Cost

Lemma 10. With nn free vertices, ss springs and cc segments, one Newton iteration of the code costs O(n3+s+nc)O(n^3 + s + nc) time and Θ(n2+s+c)\Theta(n^2 + s + c) memory, plus O(s+nc)O(s + nc) for each halving of the line search.

Proof. The assembly visits every spring and every vertex and segment pair once, with O(1)O(1) work each. The dense LU solve of the 2n×2n2n \times 2n system costs O(n3)O(n^3) and stores Θ(n2)\Theta(n^2) numbers. The step bound visits every vertex and segment pair once. One evaluation of BB costs O(n+s+nc)O(n + s + nc). □\square

The paper uses a sparse solver and a spatial culling of the pairs (Section 4.6), which replace the n3n^3 and ncnc terms in practice.

Complexity

One Newton iteration of the code assembles the gradient and Hessian in O(s+nc)O(s + nc), solves the dense 2n×2n2n \times 2n system in O(n3)O(n^3) and checks every vertex and segment pair for the step bound in O(nc)O(nc). Each halving of the line search costs O(n+s+nc)O(n + s + nc). The memory is Θ(n2+s+c)\Theta(n^2 + s + c). 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 Δt\Delta t and on how close contacts are to d^\hat d.

Properties

  • Free of intersection. Given conservative collision checks, no state and no iterate has an intersection, at any Δt\Delta t (claim 3).
  • Monotone solver. The barrier augmented potential decreases at every iteration (claim 4).
  • Smooth contact forces. Forces act from a distance d^\hat d 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 Δt\Delta t.
  • 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 d^\hat d 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 κ\kappa the gap and the conditioning change with Δt\Delta t (the box drop table). The paper adapts κ\kappa from the scene.
  • Too large d^\hat d. Contacts act from far away and objects float visibly; too small d^\hat d makes the Newton problem stiff near contact.
  • No projection. Without the stencil projection, HH 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 0.80.8 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.

anim.pyI0RawGitHub
# 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

  1. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.iteration
  • a full proof of time.step
  • a full proof of space.step
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
  • at least three sources
  • a scene preset for the example