Algorithm Search⌘K

Algorithmadvanced

Extended position based dynamics

Also called XPBD.

Position based dynamics with a compliance and a Lagrange multiplier per constraint, so that the converged stiffness does not depend on the time step or on the sweep count.

Time
O(n + k c) stepΘ(c) sweep
Space
O(n + c) step
Where
c = the number of constraints, each on a bounded number of particles; k = the number of solver sweeps per step; n = the number of particles
Properties
not angular momentum conservingbackward euler for linear constraintsdeterministicnot exactlinear momentum conserving
Origin
Miles Macklin, Matthias Müller, Nuttapong Chentanez, 2016

Extended position based dynamics (XPBD) is position based dynamics with two additions: each constraint gets a compliance α\alpha, the inverse of a stiffness, and a Lagrange multiplier λ\lambda that collects its total correction during the step. Macklin, Müller and Chentanez (2016) derived the update as a Gauss-Seidel solve of a simplified Newton system of backward Euler. When the sweeps converge, a spring of compliance α\alpha has the stiffness 1/α1/\alpha for any Δt\Delta t and any sweep count, and with α=0\alpha = 0 the method is PBD with hard constraints.

In plain words

PBD fixes each stick of a rope fully, every time it visits it. So more visits make the rope stiffer, even if nothing else changes. XPBD gives each stick a softness number and a running total of how hard it has already pulled in this frame. On each visit the stick asks: given my softness and how hard I already pull, how much more should I pull? The answer gets smaller on every visit, and it settles at the same rope for any number of visits. A soft stick ends up a little longer than its rest length, by the amount its pull and its softness agree on. A stick with softness zero is a rigid stick, as in PBD.

The problem

The input is a set of particles with positions xi\mathbf x_i, velocities vi\mathbf v_i and inverse masses wi=1/miw_i = 1/m_i (wi=0w_i = 0 for a pinned particle), constraints CjC_j with compliances αj≥0\alpha_j \ge 0, a step Δt\Delta t and a sweep count kk. The elastic potential of the constraints is

U(x)=∑j12αjCj(x)2,U(\mathbf x) = \sum_j \frac{1}{2\alpha_j} C_j(\mathbf x)^2 ,

so a distance constraint C=∣xi−xj∣−dC = |\mathbf x_i - \mathbf x_j| - d is a spring of stiffness 1/α1/\alpha. The aim is the backward Euler step for UU and gravity. With x~=xn+Δtvn+Δt2g\tilde{\mathbf x} = \mathbf x^n + \Delta t \mathbf v^n + \Delta t^2 \mathbf g it is a stationary point of 12(x−x~)TM(x−x~)+Δt2U(x)\tfrac12 (\mathbf x - \tilde{\mathbf x})^T M (\mathbf x - \tilde{\mathbf x}) + \Delta t^2 U(\mathbf x), the variational form of backward Euler that this site also uses for optimization time integration, projective dynamics, vertex block descent, incremental potential contact and affine body dynamics. XPBD gives an approximation of it at the cost of PBD. The page uses 2D, yy up and g=(0,−9.81)\mathbf g = (0, -9.81) m/s².

The algorithm

  1. XPBD-STEP(x, v, w, constraints, Δt, k)
  2. 1for each free particle i: x~_i <- x_i + Δt v_i + Δt² g ▷ prediction
  3. 2for each constraint j: λ_j <- 0
  4. 3p <- x~
  5. 4repeat k times:
  6. 5for each constraint C_j in a fixed order, with α~_j = α_j / Δt²:
  7. 6Δλ <- (-C_j(p) - α~_j λ_j) / (Σ_i w_i |∇_i C_j(p)|² + α~_j)
  8. 7for each particle i of C_j: p_i <- p_i + w_i ∇_i C_j(p) Δλ
  9. 8λ_j <- λ_j + Δλ
  10. 9for each particle i: v_i <- (p_i - x_i) / Δt; x_i <- p_i

Where L6 comes from. Write λj=−Cj(x)/α~j\lambda_j = -C_j(\mathbf x)/\tilde\alpha_j. Then the backward Euler step is the pair of equations M(x−x~)−∇C(x)Tλ=0M(\mathbf x - \tilde{\mathbf x}) - \nabla \mathbf C(\mathbf x)^T \boldsymbol\lambda = 0 and C(x)+A~λ=0\mathbf C(\mathbf x) + \tilde A \boldsymbol\lambda = 0 with A~=diag⁡(α~j)\tilde A = \operatorname{diag}(\tilde\alpha_j) (equations (4) to (9) of the paper). Newton's method on these equations solves a block system with the matrix K=M−∑jλj∇2CjK = M - \sum_j \lambda_j \nabla^2 C_j (equation (12)). XPBD makes two simplifications. It replaces KK by MM, which drops the geometric stiffness and gives a quasi-Newton method. It also assumes that the first equation holds at every iterate. What remains is the system (∇C M−1∇CT+A~)Δλ=−C−A~λ(\nabla\mathbf C\, M^{-1} \nabla\mathbf C^T + \tilde A)\Delta\boldsymbol\lambda = -\mathbf C - \tilde A\boldsymbol\lambda, and line L6 is one Gauss-Seidel update of its row jj, with the gradient taken at the current positions (equation (18)). For a distance constraint, ∣∇iC∣=1|\nabla_i C| = 1 and the denominator is wi+wj+α~jw_i + w_j + \tilde\alpha_j.

The multiplier. The term α~jλj\tilde\alpha_j \lambda_j in L6 is what PBD lacks. It makes repeated visits to the same constraint converge to Cj+α~jλj=0C_j + \tilde\alpha_j \lambda_j = 0 instead of to Cj=0C_j = 0, so a soft constraint is not made stiffer by more sweeps. The force of the constraint is ∇CjTλj/Δt2\nabla C_j^T \lambda_j / \Delta t^2, a value that PBD does not give.

Damping. Equation (26) of the paper adds Rayleigh damping with a coefficient βj\beta_j: with β~j=Δt2βj\tilde\beta_j = \Delta t^2 \beta_j and γj=α~jβ~j/Δt\gamma_j = \tilde\alpha_j \tilde\beta_j / \Delta t, the update becomes Δλ=(−Cj−α~jλj−γj∇Cj(p−xn))/((1+γj) ∇CjM−1∇CjT+α~j)\Delta\lambda = (-C_j - \tilde\alpha_j\lambda_j - \gamma_j \nabla C_j (\mathbf p - \mathbf x^n)) / ((1 + \gamma_j)\, \nabla C_j M^{-1} \nabla C_j^T + \tilde\alpha_j). The code leaves damping out.

Example

One spring by hand. A free particle of mass 1 sits at (1.5,0)(1.5, 0) at rest, joined to a pin at the origin by a spring of rest length 1 and compliance α=0.01\alpha = 0.01 (stiffness 100). There is no gravity and Δt=0.1\Delta t = 0.1, so α~=1\tilde\alpha = 1 and the prediction is (1.5,0)(1.5, 0). Line L6 gives Δλ=(−0.5−0)/(1+1)=−0.25\Delta\lambda = (-0.5 - 0)/(1 + 1) = -0.25, and L7 moves the particle by −0.25-0.25 to 1.251.25, with the velocity −2.5-2.5. A second sweep gives Δλ=(−0.25+0.25)/2=0\Delta\lambda = (-0.25 + 0.25)/2 = 0. Backward Euler for this spring gives x=(1⋅1.5+0.01⋅100⋅1)/(1+0.01⋅100)=1.25x = (1 \cdot 1.5 + 0.01 \cdot 100 \cdot 1)/(1 + 0.01 \cdot 100) = 1.25, the same value. PBD with the stiffness kk would give 1+0.5(1−k)1 + 0.5(1 - k) after one sweep, which depends on how kk is tuned and not on the step.

Stretch against sweeps (measured). A chain of 11 particles of 1 kg, joined by 10 constraints of 0.1 m, is pinned at one end and falls from a horizontal start, with Δt=1/60\Delta t = 1/60 s. After 300 steps (5 s) the total length exceeds 1 m by

compliance α\alpha k=1k = 1 2 5 10 20 50
0 (PBD) 11.4% 5.7% 2.9% 1.5% 0.64% 0.16%
10−510^{-5} 12.5% 6.1% 3.3% 1.9% 1.13% 0.76%
10−410^{-4} 24.6% 7.6% 6.0% 5.6% 5.53% 5.52%

With α=10−4\alpha = 10^{-4} (stiffness 10410^4 N/m per link) the stretch settles near 5.5% from about 10 sweeps on. A chain of these springs hanging at rest would stretch by ∑i=110i⋅9.81/104=0.054\sum_{i=1}^{10} i \cdot 9.81 / 10^4 = 0.054 m, or 5.4%; the chain here still swings. With α=0\alpha = 0 the stretch keeps falling with more sweeps, which is the PBD behavior, and the row is the same as the table on the PBD page.

Distance from backward Euler (measured). A chain of 6 particles with α=10−4\alpha = 10^{-4} swings for 6 steps, then one step is taken from the same state with 500 sweeps and compared with a Newton solve of the backward Euler equations. The largest distance between the two answers is

Δt\Delta t 1/30 1/60 1/120 1/240 1/480
distance (m) 1.6×10−31.6 \times 10^{-3} 1.7×10−41.7 \times 10^{-4} 1.1×10−51.1 \times 10^{-5} 6.2×10−76.2 \times 10^{-7} 3.6×10−83.6 \times 10^{-8}
motion in the step (m) 0.045 0.020 0.0090 0.0043 0.0021

The gap comes from the second simplification: the gradients turn while the chain swings, so the converged answer is not exactly the backward Euler step. In this run the gap shrinks about 16 times when Δt\Delta t is halved. For a chain that only moves along its own line the gradients do not turn, and the gap is zero (claim 3 below).

Correctness

The claims are proved in proofs/correctness.md.

  1. Gauss-Seidel on a simplified Newton system (proved). Lines L6 to L8 are one Gauss-Seidel update of the Newton system of backward Euler with KK replaced by MM and the first residual set to zero.
  2. Fixed points (proved). If the sweeps converge, the limit satisfies Cj+α~jλj=0C_j + \tilde\alpha_j \lambda_j = 0 for every jj. The other backward Euler equation holds up to a residual that is a sum of gradient changes times multiplier updates, so it is zero when the gradients do not turn.
  3. Exact for linear constraints (proved). If every constraint is affine on the region of the iterates and every αj>0\alpha_j > 0, the sweeps converge for any order to the backward Euler step, because they are Gauss-Seidel for a symmetric positive definite system. The test runs a vertical chain against a Newton solve and reaches 10−1210^{-12} after 200 sweeps, with the error falling at every count.
  4. One spring (proved). For one spring on a pinned particle, one sweep gives the backward Euler step x=(my+Δt2kr)/(m+Δt2k)x = (m y + \Delta t^2 k r)/(m + \Delta t^2 k) with k=1/αk = 1/\alpha for every Δt\Delta t. The test checks 200 random cases across four step sizes.
  5. Zero compliance is PBD (proved). With αj=0\alpha_j = 0, L6 is the PBD projection with the sweep stiffness 1.
  6. Linear momentum (proved). With translation invariant constraints, no pins and no gravity, the step keeps ∑mivi\sum m_i \mathbf v_i. Angular momentum is not kept in general, for the same reason as in PBD.

The tests also check the gradient of the backward Euler objective against central differences, that the constraint forces sum to zero, that the swinging chain of the table is within 1% of the motion from backward Euler and closer at the smaller step, and free fall against the symplectic Euler value −5.3955-5.3955 m after 10 steps of 0.10.1 s.

Proof: XPBD is Gauss-Seidel on a simplified Newton system of backward Euler, and it is exact for linear constraintsfull

We use the notation of the page. There are nn particles with positions x∈R2n\mathbf x \in \mathbb R^{2n}, a diagonal mass matrix MM and inverse masses wi=1/miw_i = 1/m_i; a pinned particle has wi=0w_i = 0 and is left out of all sums over masses. There are cc constraints CjC_j with compliances αj≥0\alpha_j \ge 0, and α~j=αj/Δt2\tilde\alpha_j = \alpha_j / \Delta t^2. The matrix G(x)G(\mathbf x) has the rows ∇Cj(x)T\nabla C_j(\mathbf x)^T, and A~=diag⁡(α~j)\tilde A = \operatorname{diag}(\tilde\alpha_j). The prediction of line L1 is x~=xn+Δtvn+Δt2g\tilde{\mathbf x} = \mathbf x^n + \Delta t \mathbf v^n + \Delta t^2 \mathbf g on the free particles. Lines L6 and L7 apply to the constraint jj

Δλj=−Cj(p)−α~jλj∑iwi∣∇iCj(p)∣2+α~j,Δpi=wi∇iCj(p) Δλj,\Delta\lambda_j = \frac{-C_j(\mathbf p) - \tilde\alpha_j \lambda_j}{\sum_i w_i |\nabla_i C_j(\mathbf p)|^2 + \tilde\alpha_j}, \qquad \Delta \mathbf p_i = w_i \nabla_i C_j(\mathbf p)\, \Delta\lambda_j ,

which is equation (18) of Macklin et al. (2016). For a distance constraint ∣∇iCj∣=1|\nabla_i C_j| = 1, so the denominator is wi+wj+α~jw_i + w_j + \tilde\alpha_j.

The backward Euler step and its Newton system

Lemma 1. Let αj>0\alpha_j > 0 for all jj. The backward Euler step for the potential U(x)=∑j12αjCj(x)2U(\mathbf x) = \sum_j \frac{1}{2\alpha_j} C_j(\mathbf x)^2 is a stationary point of

E(x)=12(x−x~)TM(x−x~)+Δt2U(x).E(\mathbf x) = \tfrac12 (\mathbf x - \tilde{\mathbf x})^T M (\mathbf x - \tilde{\mathbf x}) + \Delta t^2 U(\mathbf x).

With λj=−Cj(x)/α~j\lambda_j = -C_j(\mathbf x)/\tilde\alpha_j, the condition ∇E=0\nabla E = 0 is equivalent to the two equations

h(x,λ):=M(x−x~)−G(x)Tλ=0,C(x)+A~λ=0.\mathbf h(\mathbf x, \boldsymbol\lambda) := M(\mathbf x - \tilde{\mathbf x}) - G(\mathbf x)^T \boldsymbol\lambda = 0, \qquad \mathbf C(\mathbf x) + \tilde A \boldsymbol\lambda = 0 .

Proof. Backward Euler is M(x−2xn+xn−1)/Δt2=−∇U(x)+MgM(\mathbf x - 2\mathbf x^n + \mathbf x^{n-1})/\Delta t^2 = -\nabla U(\mathbf x) + M\mathbf g with xn−xn−1=Δtvn\mathbf x^n - \mathbf x^{n-1} = \Delta t \mathbf v^n, that is M(x−x~)+Δt2∇U(x)=0M(\mathbf x - \tilde{\mathbf x}) + \Delta t^2 \nabla U(\mathbf x) = 0, and this is ∇E(x)=0\nabla E(\mathbf x) = 0. Now Δt2∇U=∑j(Δt2/αj)Cj∇Cj=−∑jλj∇Cj=−GTλ\Delta t^2 \nabla U = \sum_j (\Delta t^2/\alpha_j) C_j \nabla C_j = -\sum_j \lambda_j \nabla C_j = -G^T \boldsymbol\lambda by the definition of λj\lambda_j, and that definition is the second equation. □\square

The function h\mathbf h is the residual g\mathbf g of the paper; we write h\mathbf h to keep g\mathbf g for gravity. One Newton step on the two equations at (x,λ)(\mathbf x, \boldsymbol\lambda) solves

(K−GTGA~)(ΔxΔλ)=−(hC+A~λ),K=M−∑jλj∇2Cj,\begin{pmatrix} K & -G^T \\ G & \tilde A \end{pmatrix} \begin{pmatrix} \Delta\mathbf x \\ \Delta\boldsymbol\lambda \end{pmatrix} = -\begin{pmatrix} \mathbf h \\ \mathbf C + \tilde A \boldsymbol\lambda \end{pmatrix}, \qquad K = M - \sum_j \lambda_j \nabla^2 C_j ,

which is equation (12) of the paper.

Lemma 2. Replace KK by MM and h\mathbf h by 00. Then the system becomes (GM−1GT+A~)Δλ=−C−A~λ(G M^{-1} G^T + \tilde A)\Delta\boldsymbol\lambda = -\mathbf C - \tilde A\boldsymbol\lambda with Δx=M−1GTΔλ\Delta \mathbf x = M^{-1} G^T \Delta\boldsymbol\lambda. One Gauss-Seidel update of the row jj of this system, with GG evaluated at the current p\mathbf p, is lines L6 to L8.

Proof. The first block row gives MΔx=GTΔλM\Delta\mathbf x = G^T \Delta\boldsymbol\lambda. Put this into the second row: GM−1GTΔλ+A~Δλ=−C−A~λG M^{-1} G^T \Delta\boldsymbol\lambda + \tilde A \Delta\boldsymbol\lambda = -\mathbf C - \tilde A\boldsymbol\lambda. The diagonal entry of row jj is ∇CjTM−1∇Cj+α~j=∑iwi∣∇iCj∣2+α~j\nabla C_j^T M^{-1} \nabla C_j + \tilde\alpha_j = \sum_i w_i |\nabla_i C_j|^2 + \tilde\alpha_j. A Gauss-Seidel update solves row jj for Δλj\Delta\lambda_j with the other unknowns at their current values. Since each earlier update has already been applied to p\mathbf p and λ\boldsymbol\lambda, the right side of row jj is −Cj(p)−α~jλj-C_j(\mathbf p) - \tilde\alpha_j\lambda_j and the off-diagonal terms are already used up, so the update is the Δλj\Delta\lambda_j of line L6. The matching change of p\mathbf p is M−1∇CjΔλjM^{-1}\nabla C_j \Delta\lambda_j, which is line L7. □\square

Dropping the term ∑jλj∇2Cj\sum_j \lambda_j \nabla^2 C_j (the geometric stiffness) makes this a quasi-Newton method. It changes the path to the solution but not the equations that a fixed point must satisfy. Setting h=0\mathbf h = 0 is a different matter, as the next lemma shows.

Fixed points

Lemma 3. Suppose the sweeps converge, so that Δλj→0\Delta\lambda_j \to 0 for every jj and p→x∗\mathbf p \to \mathbf x^*, λ→λ∗\boldsymbol\lambda \to \boldsymbol\lambda^*. Then C(x∗)+A~λ∗=0\mathbf C(\mathbf x^*) + \tilde A\boldsymbol\lambda^* = 0. Also

h(x∗,λ∗)=∑updates u(∇Cj(u)(pu)−∇Cj(u)(x∗)) Δλu,\mathbf h(\mathbf x^*, \boldsymbol\lambda^*) = \sum_{\text{updates } u} \big(\nabla C_{j(u)}(\mathbf p_u) - \nabla C_{j(u)}(\mathbf x^*)\big)\, \Delta\lambda_u ,

where the sum runs over all updates of lines L6 and L7, pu\mathbf p_u is the state at which update uu was computed, and the gradients are stacked into R2n\mathbb R^{2n}.

Proof. The first claim is line L6 with Δλj=0\Delta\lambda_j = 0 and a finite denominator. For the second, line L3 sets p=x~\mathbf p = \tilde{\mathbf x} and line L2 sets λ=0\boldsymbol\lambda = 0. Each update adds M−1∇Cj(pu)ΔλuM^{-1}\nabla C_j(\mathbf p_u)\Delta\lambda_u to p\mathbf p and Δλu\Delta\lambda_u to λj\lambda_j. Summing, M(x∗−x~)=∑u∇Cj(u)(pu)ΔλuM(\mathbf x^* - \tilde{\mathbf x}) = \sum_u \nabla C_{j(u)}(\mathbf p_u)\Delta\lambda_u and G(x∗)Tλ∗=∑u∇Cj(u)(x∗)ΔλuG(\mathbf x^*)^T\boldsymbol\lambda^* = \sum_u \nabla C_{j(u)}(\mathbf x^*)\Delta\lambda_u. Subtract. □\square

So a converged XPBD step is a backward Euler step exactly when the residual h\mathbf h of Lemma 3 is zero, and the size of h\mathbf h depends on how much the constraint gradients turn during the step. This is a property of the method, not of the number of sweeps.

Theorem 4 (linear constraints). Let every CjC_j be affine on a region that holds all iterates, Cj(x)=Cj(x~)+ajT(x−x~)C_j(\mathbf x) = C_j(\tilde{\mathbf x}) + \mathbf a_j^T(\mathbf x - \tilde{\mathbf x}), let αj>0\alpha_j > 0 for all jj and let every constraint touch at least one free particle. Then the XPBD sweeps converge for any number of constraints and any order, and the limit is the backward Euler step of Lemma 1.

Proof. The gradients aj\mathbf a_j are constant, so the invariant of Lemma 3 reads p−x~=M−1GTλ\mathbf p - \tilde{\mathbf x} = M^{-1} G^T \boldsymbol\lambda at all times, where now GG is constant. Hence Cj(p)+α~jλj=(b+Aλ)jC_j(\mathbf p) + \tilde\alpha_j\lambda_j = (\mathbf b + A\boldsymbol\lambda)_j with b=C(x~)\mathbf b = \mathbf C(\tilde{\mathbf x}) and A=GM−1GT+A~A = G M^{-1} G^T + \tilde A, and line L6 is Δλj=−(b+Aλ)j/Ajj\Delta\lambda_j = -(\mathbf b + A\boldsymbol\lambda)_j / A_{jj}. This is the Gauss-Seidel method for Aλ=−bA\boldsymbol\lambda = -\mathbf b. The matrix AA is symmetric, and it is positive definite because zTAz=∣M−1/2GTz∣2+∑jα~jzj2>0\mathbf z^T A \mathbf z = |M^{-1/2} G^T \mathbf z|^2 + \sum_j \tilde\alpha_j z_j^2 > 0 for z≠0\mathbf z \ne 0 (here M−1/2M^{-1/2} acts on the free particles only). Gauss-Seidel converges for every symmetric positive definite matrix and every start, so λ→λ∗\boldsymbol\lambda \to \boldsymbol\lambda^* with Aλ∗=−bA\boldsymbol\lambda^* = -\mathbf b, and p→x∗\mathbf p \to \mathbf x^*. Then h(x∗,λ∗)=0\mathbf h(\mathbf x^*, \boldsymbol\lambda^*) = 0 by the invariant, and C(x∗)+A~λ∗=0\mathbf C(\mathbf x^*) + \tilde A\boldsymbol\lambda^* = 0 by Lemma 3. By Lemma 1, x∗\mathbf x^* is the backward Euler step. □\square

A distance constraint ∣xi−xj∣−d|\mathbf x_i - \mathbf x_j| - d is affine on every region where the direction of xi−xj\mathbf x_i - \mathbf x_j does not change, for example a vertical chain that only moves vertically.

Corollary 5 (one spring). Take a pinned particle at the origin and a free particle of mass mm on the xx axis, joined by one distance constraint of rest length rr and compliance α\alpha, with k=1/αk = 1/\alpha and no gravity. Let y=xn+Δtvn>0y = x^n + \Delta t v^n > 0 be the prediction. One sweep gives

xn+1=my+Δt2krm+Δt2k,x^{n+1} = \frac{m y + \Delta t^2 k r}{m + \Delta t^2 k},

the backward Euler step of the linear spring of stiffness kk, for every Δt>0\Delta t > 0.

Proof. With one constraint, Gauss-Seidel solves the 1×11 \times 1 system in one update. Directly: λ=−(y−r)/(w+α~)\lambda = -(y - r)/(w + \tilde\alpha) with w=1/mw = 1/m, and xn+1=y+wλ=y−y−r1+mα/Δt2=y−Δt2k(y−r)Δt2k+mx^{n+1} = y + w\lambda = y - \frac{y - r}{1 + m\alpha/\Delta t^2} = y - \frac{\Delta t^2 k (y - r)}{\Delta t^2 k + m}, which is the formula. The backward Euler equation m(x−y)/Δt2=−k(x−r)m(x - y)/\Delta t^2 = -k(x - r) has the same solution. □\square

In particular the stiffness of a spring in XPBD is k=1/αk = 1/\alpha for every Δt\Delta t and every number of sweeps once the sweeps have converged. With few sweeps the result is softer, since the sweeps stop early.

Zero compliance and momentum

Lemma 6. If αj=0\alpha_j = 0, line L6 is the PBD projection with the sweep stiffness 11.

Proof. With α~j=0\tilde\alpha_j = 0 the term α~jλj\tilde\alpha_j\lambda_j vanishes and Δλj=−Cj(p)/∑iwi∣∇iCj∣2\Delta\lambda_j = -C_j(\mathbf p)/\sum_i w_i|\nabla_i C_j|^2, which is −s-s in the notation of the PBD page. Then Δpi=−s wi∇iCj\Delta\mathbf p_i = -s\, w_i\nabla_i C_j. □\square

Theorem 7 (linear momentum). Let every CjC_j be invariant under a common translation of its particles, let no particle be pinned and let g=0\mathbf g = 0. Then ∑imivin+1=∑imivin\sum_i m_i \mathbf v_i^{n+1} = \sum_i m_i \mathbf v_i^n.

Proof. Translation invariance gives ∑i∇iCj=0\sum_i \nabla_i C_j = 0, so each update changes ∑imipi\sum_i m_i \mathbf p_i by Δλj∑i∇iCj=0\Delta\lambda_j\sum_i \nabla_i C_j = 0. Hence ∑mipi=∑mi(xin+Δtvin)\sum m_i \mathbf p_i = \sum m_i(\mathbf x_i^n + \Delta t \mathbf v_i^n) at the end of the sweeps, and line L9 gives the claim. □\square

Angular momentum is not kept in general. Each update is torque-free about the current p\mathbf p, as in Lemma 4 of the PBD proof, but the velocity of line L9 is measured from xn\mathbf x^n. The two-particle counterexample of Theorem 7 there applies without change when α=0\alpha = 0.

Lemma 8. With no constraints, one step is the symplectic Euler step 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}.

Proof. Line L1 computes xn+Δt(vn+Δtg)\mathbf x^n + \Delta t(\mathbf v^n + \Delta t\mathbf g), nothing changes it, and line L9 returns vn+Δtg\mathbf v^n + \Delta t\mathbf g. □\square

Cost

Lemma 9. A step with kk sweeps over cc distance constraints on nn particles costs Θ(n+kc)\Theta(n + kc) time and Θ(n+c)\Theta(n + c) memory.

Proof. Lines L1, L3 and L9 touch each particle once. Each constraint update in lines L6 to L8 does a constant amount of work for a constraint on two particles. The state is p\mathbf p, the velocities and one multiplier per constraint. □\square

Complexity

Each update of L6 to L8 costs O(1)O(1) for a constraint on a bounded number of particles, so a sweep costs Θ(c)\Theta(c) and a step O(n+kc)O(n + k c). The extra memory over PBD is one multiplier per constraint, so the memory is O(n+c)O(n + c). No matrix is built or factored. The number of sweeps needed for a given error is a property of the scene: Gauss-Seidel converges slowly on long chains and on stiff, well connected meshes.

Properties

  • Stiffness is a material constant when converged. A converged step gives the spring stiffness 1/α1/\alpha independent of Δt\Delta t and kk (claims 3 and 4). With few sweeps the material is softer than 1/α1/\alpha, as the table shows.
  • Approximate backward Euler. The method inherits the numerical damping of backward Euler, and it adds the gap of the second simplification when constraints turn.
  • Hard constraints. α=0\alpha = 0 is allowed and gives rigid constraints, as in PBD. Then the system has no compliance term; with redundant constraints its matrix is only positive semidefinite, and the convergence proof of claim 3 does not apply.
  • Order dependence. As in PBD, the result of a finite number of sweeps depends on the constraint order.
  • Momentum. Linear momentum is kept exactly for translation invariant constraints; angular momentum is not.

Variants and improvements

  • Small steps. Small steps use k=1k = 1 and divide the frame into many substeps. Macklin et al. (2019) measured lower error for the same cost on chains and cloth.
  • Rigid bodies. Müller, Macklin, Chentanez, Jeschke and Kim (2020) extended XPBD to rigid bodies with positional and angular constraints, joints and friction (Computer Graphics Forum 39(8)).
  • Jacobi and coloring. For a GPU, constraints are updated in parallel by averaging or by graph coloring, as in PBD.
  • Other solvers for the same step. Projective dynamics solves the same kind of backward Euler step by local projections and a constant global matrix, and vertex block descent does block coordinate descent over vertices. Optimization time integration uses Newton's method with a line search, which keeps the geometric stiffness.
  • Mass-spring view. Fast mass-spring solves the same backward Euler step for springs with a constant matrix.

When to use it

Use XPBD when you want the robustness and simple code of PBD, but the stiffness must be set in physical units and must not change with the step or the sweep count, for example cloth, ropes and soft bodies in games and tools. Use α=0\alpha = 0 for rigid constraints such as inextensible links and pins. It also gives constraint forces, which PBD does not.

Do not expect a converged backward Euler solution for very stiff, well connected meshes with few sweeps; use substeps or a Newton based solver then.

Pitfalls

  • Forgetting to reset λ\lambda. The multipliers start at zero in every step (L2). Keeping them from the last step changes the method.
  • Units. α\alpha is in units of the inverse of the stiffness, for example m/N for a distance constraint. Divide by Δt2\Delta t^2 to get α~\tilde\alpha; using α\alpha directly makes the material depend on Δt\Delta t again.
  • Few sweeps on stiff materials. With a small α\alpha and few sweeps the material is soft, as the table shows. More sweeps or substeps are needed.
  • Mixed compliances. Very different compliances in one system slow Gauss-Seidel down. Small steps help here.
  • Zero gradients and pinned pairs. Skip a constraint with a zero gradient or with only pinned particles, as in PBD.

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
extended_position_based_dynamics.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-position-based-dynamics/. The authors are listed in prov/553NT7.jsonl.

"""Extended position based dynamics (Macklin, Mueller and Chentanez 2016), in 2D.

Each constraint C_j has a compliance alpha_j (the inverse of a stiffness) and a
Lagrange multiplier lambda_j that starts at zero in every step. With
alpha~ = alpha / dt^2, one Gauss-Seidel sweep visits each constraint and
applies (equation (18) of the paper)

    dlambda = (-C_j(x) - alpha~ lambda_j) / (sum_i w_i |grad_i C_j(x)|^2 + alpha~),
    x_i <- x_i + w_i grad_i C_j(x) dlambda,   lambda_j <- lambda_j + dlambda.

This is a Gauss-Seidel solve of the Newton system of backward Euler for the
energy U = sum 1/(2 alpha_j) C_j^2, with the geometric stiffness dropped
(K ~ M) and the residual g = M (x - x~) - grad C^T lambda taken as zero.
With alpha_j = 0 the update is the PBD projection with stiffness 1.

The particles are lists of 2D points, w are inverse masses (0 for a pinned
particle) and a constraint is a tuple (i, j, rest, alpha) for the distance
constraint C = |x_i - x_j| - rest. One sweep costs Theta(c) for c
constraints, a step O(n + k c) for k sweeps, and the memory is O(n + c).
"""

import math

GRAVITY = (0.0, -9.81)


def distance_value_and_gradient(x, i, j, rest):
    """C = |x_i - x_j| - rest and the unit vector n = grad_i C = -grad_j C."""
    dx, dy = x[i][0] - x[j][0], x[i][1] - x[j][1]
    ln = math.hypot(dx, dy)
    if ln == 0.0:
        return -rest, (0.0, 0.0)
    return ln - rest, (dx / ln, dy / ln)


def xpbd_step(x, v, w, constraints, dt, iterations, gravity=GRAVITY):
    """One XPBD step. Return (x, v, lam) with the final multipliers."""
    n = len(x)
    xn = [tuple(p) for p in x]
    xt = [(xn[i][0] + dt * v[i][0] + dt * dt * gravity[0], xn[i][1] + dt * v[i][1] + dt * dt * gravity[1])
          if w[i] > 0.0 else xn[i] for i in range(n)]  # @line L1
    lam = [0.0] * len(constraints)  # @line L2
    p = list(xt)  # @line L3
    for _ in range(iterations):  # @line L4
        for k, (i, j, rest, alpha) in enumerate(constraints):  # @line L5
            at = alpha / (dt * dt)
            c, nrm = distance_value_and_gradient(p, i, j, rest)
            denom = w[i] + w[j] + at
            if denom == 0.0 or nrm == (0.0, 0.0):
                continue
            dl = (-c - at * lam[k]) / denom  # @line L6
            p[i] = (p[i][0] + w[i] * nrm[0] * dl, p[i][1] + w[i] * nrm[1] * dl)  # @line L7
            p[j] = (p[j][0] - w[j] * nrm[0] * dl, p[j][1] - w[j] * nrm[1] * dl)
            lam[k] += dl  # @line L8
    v_new = [((p[i][0] - xn[i][0]) / dt, (p[i][1] - xn[i][1]) / dt) for i in range(n)]  # @line L9
    return p, v_new, lam


def energy_objective(x, xt, w, constraints, dt):
    """The backward Euler objective 1/2 |x - x~|_M^2 + dt^2 sum 1/(2 alpha) C^2 (free particles only)."""
    g = 0.0
    for i, (p, q) in enumerate(zip(x, xt)):
        if w[i] > 0.0:
            g += 0.5 / w[i] * ((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
    for i, j, rest, alpha in constraints:
        c = math.dist(x[i], x[j]) - rest
        g += dt * dt * 0.5 / alpha * c * c
    return g


def constraint_force(x, constraints, lam, dt):
    """The force of each constraint: grad C^T lambda / dt^2, per particle."""
    f = [[0.0, 0.0] for _ in x]
    for k, (i, j, rest, alpha) in enumerate(constraints):
        _, nrm = distance_value_and_gradient(x, i, j, rest)
        s = lam[k] / (dt * dt)
        f[i][0] += s * nrm[0]
        f[i][1] += s * nrm[1]
        f[j][0] -= s * nrm[0]
        f[j][1] -= s * nrm[1]
    return [tuple(u) for u in f]


def chain(count, spacing, alpha, mass=1.0, vertical=False):
    """A chain pinned at particle 0, horizontal or hanging along -y. Return (x, v, w, constraints)."""
    if vertical:
        x = [(0.0, -i * spacing) for i in range(count)]
    else:
        x = [(i * spacing, 0.0) for i in range(count)]
    v = [(0.0, 0.0)] * count
    w = [0.0] + [1.0 / mass] * (count - 1)
    cons = [(i, i + 1, spacing, alpha) for i in range(count - 1)]
    return x, v, w, cons
test_extended_position_based_dynamics.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-position-based-dynamics/. The authors are listed in prov/553NT7.jsonl.

"""Tests of XPBD against closed forms, a Newton solve of backward Euler and conservation laws."""

import math
import random

from anim import num_grad, solve
import extended_position_based_dynamics as xpbd


def predict(x, v, w, dt, g):
    return [(p[0] + dt * u[0] + dt * dt * g[0], p[1] + dt * u[1] + dt * dt * g[1]) if wi > 0.0 else tuple(p)
            for p, u, wi in zip(x, v, w)]


def newton_backward_euler(xt, w, cons, dt, tol=1e-13):
    """Minimize 1/2 |x - x~|_M^2 + dt^2 sum C^2 / (2 alpha) by Newton's method with backtracking."""
    free = [i for i in range(len(xt)) if w[i] > 0.0]
    col = {i: k for k, i in enumerate(free)}
    x = [tuple(p) for p in xt]
    for _ in range(100):
        nf = 2 * len(free)
        grad = [0.0] * nf
        hess = [[0.0] * nf for _ in range(nf)]
        for i in free:
            for d in range(2):
                r = 2 * col[i] + d
                grad[r] += (x[i][d] - xt[i][d]) / w[i]
                hess[r][r] += 1.0 / w[i]
        for i, j, rest, alpha in cons:
            c, n = xpbd.distance_value_and_gradient(x, i, j, rest)
            ln = c + rest
            s = dt * dt / alpha
            blk = [[s * (n[a] * n[b] + c * ((1.0 if a == b else 0.0) - n[a] * n[b]) / ln) for b in range(2)]
                   for a in range(2)]
            for p, sp in ((i, 1.0), (j, -1.0)):
                if p not in col:
                    continue
                for a in range(2):
                    grad[2 * col[p] + a] += s * c * sp * n[a]
                for q, sq in ((i, 1.0), (j, -1.0)):
                    if q not in col:
                        continue
                    for a in range(2):
                        for b in range(2):
                            hess[2 * col[p] + a][2 * col[q] + b] += sp * sq * blk[a][b]
        if max(abs(gv) for gv in grad) < tol:
            break
        step = solve(hess, [-gv for gv in grad])
        f0 = xpbd.energy_objective(x, xt, w, cons, dt)
        t = 1.0
        while True:
            y = list(x)
            for i in free:
                y[i] = (x[i][0] + t * step[2 * col[i]], x[i][1] + t * step[2 * col[i] + 1])
            if xpbd.energy_objective(y, xt, w, cons, dt) <= f0 or t < 1e-12:
                break
            t *= 0.5
        x = y
    return x


def test_example_one_spring_is_backward_euler():
    x = [(0.0, 0.0), (1.5, 0.0)]
    v = [(0.0, 0.0), (0.0, 0.0)]
    w = [0.0, 1.0]
    x1, v1, lam = xpbd.xpbd_step(x, v, w, [(0, 1, 1.0, 0.01)], 0.1, 1, gravity=(0.0, 0.0))
    assert abs(lam[0] + 0.25) < 1e-15
    assert abs(x1[1][0] - 1.25) < 1e-15 and abs(v1[1][0] + 2.5) < 1e-13


def test_one_linear_spring_matches_backward_euler_for_any_step():
    """x = (m y + dt^2 k r) / (m + dt^2 k) with k = 1 / alpha, in one sweep."""
    rng = random.Random(11)
    for _ in range(200):
        dt = rng.choice([1e-3, 1e-2, 0.1, 1.0])
        alpha = 10 ** rng.uniform(-6, 0)
        m = rng.uniform(0.1, 3.0)
        r = rng.uniform(0.5, 2.0)
        x0 = rng.uniform(0.6, 3.0)
        v0 = rng.uniform(-1.0, 1.0)
        y = x0 + dt * v0
        x1, _, _ = xpbd.xpbd_step([(0.0, 0.0), (x0, 0.0)], [(0.0, 0.0), (v0, 0.0)], [0.0, 1.0 / m],
                                  [(0, 1, r, alpha)], dt, 1, gravity=(0.0, 0.0))
        k = 1.0 / alpha
        want = (m * y + dt * dt * k * r) / (m + dt * dt * k)
        assert abs(x1[1][0] - want) < 1e-9 * max(1.0, abs(want))


def test_zero_compliance_is_the_pbd_projection():
    rng = random.Random(12)
    for _ in range(200):
        x = [(rng.uniform(-1, 1), rng.uniform(-1, 1)), (rng.uniform(-1, 1), rng.uniform(-1, 1))]
        w = [rng.uniform(0.1, 2.0), rng.uniform(0.1, 2.0)]
        d = rng.uniform(0.1, 1.0)
        c, n = xpbd.distance_value_and_gradient(x, 0, 1, d)
        want0 = (x[0][0] - w[0] / (w[0] + w[1]) * c * n[0], x[0][1] - w[0] / (w[0] + w[1]) * c * n[1])
        want1 = (x[1][0] + w[1] / (w[0] + w[1]) * c * n[0], x[1][1] + w[1] / (w[0] + w[1]) * c * n[1])
        x1, _, _ = xpbd.xpbd_step(x, [(0.0, 0.0)] * 2, w, [(0, 1, d, 0.0)], 1.0, 1, gravity=(0.0, 0.0))
        assert max(abs(x1[0][k] - want0[k]) for k in range(2)) < 1e-14
        assert max(abs(x1[1][k] - want1[k]) for k in range(2)) < 1e-14


def test_collinear_chain_converges_to_backward_euler():
    """Linear constraints: the dropped terms are zero, and the sweeps converge to the Newton solution."""
    dt = 1.0 / 30.0
    x, v, w, cons = xpbd.chain(8, 0.1, 1e-3, vertical=True)
    xt = predict(x, v, w, dt, xpbd.GRAVITY)
    ref = newton_backward_euler(xt, w, cons, dt)
    errs = []
    for it in (1, 2, 5, 10, 200):
        x1, _, lam = xpbd.xpbd_step(x, v, w, cons, dt, it)
        errs.append(max(abs(a[1] - b[1]) for a, b in zip(x1, ref)))
    assert errs[0] > errs[1] > errs[2] > errs[3] > 0.0
    assert errs[0] > 1e-4 and errs[4] < 1e-12
    for k, (i, j, rest, alpha) in enumerate(cons):
        assert abs(math.dist(x1[i], x1[j]) - rest + alpha / dt ** 2 * lam[k]) < 1e-12


def test_nonlinear_chain_is_close_to_backward_euler():
    """A swinging chain: the converged XPBD step differs from backward Euler by the residual g (measured)."""
    x, v, w, cons = xpbd.chain(6, 0.1, 1e-4)
    for _ in range(6):
        x, v, _ = xpbd.xpbd_step(x, v, w, cons, 1.0 / 60.0, 50)
    errs = []
    for dt in (1.0 / 60.0, 1.0 / 120.0):
        xt = predict(x, v, w, dt, xpbd.GRAVITY)
        ref = newton_backward_euler(xt, w, cons, dt)
        x1, _, _ = xpbd.xpbd_step(x, v, w, cons, dt, 500)
        err = max(math.dist(a, b) for a, b in zip(x1, ref))
        move = max(math.dist(a, b) for a, b in zip(ref, x))
        assert 0.0 < err < 1e-2 * move
        errs.append(err)
    assert errs[1] < errs[0] / 4.0


def test_linear_momentum_is_conserved():
    rng = random.Random(13)
    x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(10)]
    v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(10)]
    w = [rng.uniform(0.5, 2.0) for _ in range(10)]
    cons = [(i, j, 0.9 * math.dist(x[i], x[j]), rng.choice([0.0, 1e-4, 1e-2]))
            for i in range(10) for j in range(i + 1, 10) if (i * j) % 4 == 1]
    p0 = [sum(u[k] / wi for u, wi in zip(v, w)) for k in range(2)]
    for _ in range(40):
        x, v, _ = xpbd.xpbd_step(x, v, w, cons, 0.01, 3, gravity=(0.0, 0.0))
    p1 = [sum(u[k] / wi for u, wi in zip(v, w)) for k in range(2)]
    scale = sum(math.hypot(*u) / wi for u, wi in zip(v, w))
    assert max(abs(p1[k] - p0[k]) for k in range(2)) < 1e-10 * scale


def test_objective_gradient_against_num_grad():
    """The gradient of the backward Euler objective, and the constraint forces sum to zero."""
    rng = random.Random(14)
    x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(4)]
    xt = [(p[0] + 0.01, p[1] - 0.02) for p in x]
    w = [0.5, 1.0, 2.0, 1.0]
    cons = [(0, 1, 0.3, 1e-2), (1, 2, 0.4, 1e-3), (2, 3, 0.2, 1e-1)]
    dt = 0.05
    lam = [rng.uniform(-1e-3, 1e-3) for _ in cons]
    flat = [u for p in x for u in p]

    def f(z):
        return xpbd.energy_objective([(z[2 * i], z[2 * i + 1]) for i in range(4)], xt, w, cons, dt)

    ng = num_grad(f, flat)
    for i in range(4):
        for k in range(2):
            want = (x[i][k] - xt[i][k]) / w[i]
            for j, (a, b, rest, alpha) in enumerate(cons):
                c, n = xpbd.distance_value_and_gradient(x, a, b, rest)
                if i == a:
                    want += dt * dt / alpha * c * n[k]
                if i == b:
                    want -= dt * dt / alpha * c * n[k]
            assert abs(ng[2 * i + k] - want) <= 1e-6 * max(1.0, abs(want))
    f_lam = xpbd.constraint_force(x, cons, lam, dt)
    assert abs(sum(u[0] for u in f_lam)) < 1e-12 and abs(sum(u[1] for u in f_lam)) < 1e-12


def test_free_fall_is_symplectic_euler():
    x, v, w = [(0.0, 0.0)], [(0.0, 0.0)], [1.0]
    for _ in range(10):
        x, v, _ = xpbd.xpbd_step(x, v, w, [], 0.1, 1)
    assert abs(x[0][1] + 5.3955) < 1e-12

History

Position based dynamics (Müller, Heidelberger, Hennix and Ratcliff, 2007) had stiffness that changed with the sweep count and the step. Macklin, Müller and Chentanez added the compliance and the multiplier at Motion in Games 2016, and showed results for a spring, a chain, a beam and cloth. Macklin and coauthors then showed in 2019 that substeps with one sweep each reduce the error further, and Müller and coauthors extended the method to rigid bodies in 2020.

References

  1. Miles Macklin, Matthias Müller and Nuttapong Chentanez, XPBD: position-based simulation of compliant constrained dynamics, Proceedings of the 9th International Conference on Motion in Games (MIG 2016), 49-54, 2016, equations (4) to (12) (the implicit step and its Newton system), equation (18) (the multiplier update), equation (26) (damping), Section 6 (the spring, chain, beam and cloth results)
  2. Matthias Müller, Miles Macklin, Nuttapong Chentanez, Stefan Jeschke and Tae-Yong Kim, Detailed rigid body simulation with extended position based dynamics, Computer Graphics Forum 39(8), 101-112, 2020, the whole paper (rigid bodies, joints and friction in XPBD)

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.step
  • a full proof of time.sweep
  • 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