Algorithm Search⌘K

Algorithmcore

Position based dynamics

Also called PBD.

Predict particle positions, then project them onto constraints one at a time in Gauss-Seidel sweeps, and set velocities from the change in position.

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 conservingdeterministicnot exactlinear momentum conservingstiffness depends on iterations
Origin
Matthias Müller, Bruno Heidelberger, Marcus Hennix, John Ratcliff, 2007

Position based dynamics (PBD) moves particles by working on their positions, not on forces. Each step predicts where the particles go with symplectic Euler, then moves the predicted positions so that they satisfy constraints such as fixed distances, one constraint at a time in Gauss-Seidel sweeps, and at the end takes each velocity as the change of position divided by Δt\Delta t. Müller, Heidelberger, Hennix and Ratcliff (2007) made it a general method for cloth, soft bodies and ropes in games. It is fast, simple and robust, but its stiffness depends on the time step and on the number of sweeps, so it is not a discretization of a fixed physical model.

In plain words

Think of a rope made of beads joined by sticks. First let every bead fly freely for one frame, as if the sticks were not there. Now the sticks have the wrong lengths. Go through the sticks one by one, and for each stick move its two beads along the stick until the length is right again. A heavy bead moves less than a light one. One pass does not fix everything, because fixing one stick spoils its neighbors, so do a few passes.

At the end, the velocity of each bead is where it ended up minus where it started, divided by the frame time. The beads never get a force that can blow up, so the rope never explodes. The price is that the rope feels softer with fewer passes or larger frames.

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), a set of constraints Cj(p)=0C_j(\mathbf p) = 0 or Cj(p)≥0C_j(\mathbf p) \ge 0, each on a few particles, external forces fext\mathbf f_{\text{ext}}, a step Δt\Delta t and a sweep count kk. The output is the state after one step. The aim is not to solve an equation of motion exactly. It is a motion that keeps the constraints and looks plausible at a fixed cost, as needed in games and interactive cloth simulation. The page uses 2D, yy up and g=(0,−9.81)\mathbf g = (0, -9.81) m/s².

The algorithm

  1. PBD-STEP(x, v, w, constraints, Δt, k)
  2. 1for each particle i: v_i <- v_i + Δt w_i f_ext,i ▷ the weight gives v_i + Δt g
  3. 2damp the velocities (optional)
  4. 3for each particle i: p_i <- x_i + Δt v_i ▷ prediction
  5. 4make a collision constraint for each particle whose path x_i -> p_i hits an obstacle
  6. 5repeat k times:
  7. 6for each constraint C_j in a fixed order: project p onto C_j
  8. 7for each particle i: v_i <- (p_i - x_i) / Δt
  9. 8for each particle i: x_i <- p_i

Projection (L6). For a constraint CC on the particles SS, PBD moves the particles along the gradients, weighted by the inverse masses (Section 3.3, equations (8) and (9) with masses):

s=C(p)∑j∈Swj∣∇jC(p)∣2,Δpi=−k′s wi∇iC(p).s = \frac{C(\mathbf p)}{\sum_{j \in S} w_j |\nabla_j C(\mathbf p)|^2}, \qquad \Delta \mathbf p_i = -k' s\, w_i \nabla_i C(\mathbf p).

This is the smallest correction in the mass norm that makes the linearized constraint zero, a Lagrange multiplier step. An inequality constraint is projected only when it is violated. For a distance constraint C=∣p1−p2∣−dC = |\mathbf p_1 - \mathbf p_2| - d with n=(p1−p2)/∣p1−p2∣\mathbf n = (\mathbf p_1 - \mathbf p_2)/|\mathbf p_1 - \mathbf p_2| it gives equations (10) and (11):

Δp1=−w1w1+w2(∣p1−p2∣−d) n,Δp2=+w2w1+w2(∣p1−p2∣−d) n.\Delta \mathbf p_1 = -\frac{w_1}{w_1 + w_2} (|\mathbf p_1 - \mathbf p_2| - d)\,\mathbf n, \qquad \Delta \mathbf p_2 = +\frac{w_2}{w_1 + w_2} (|\mathbf p_1 - \mathbf p_2| - d)\,\mathbf n .

Stiffness. A constraint with stiffness k∈[0,1]k \in [0, 1] scales its correction by k′=1−(1−k)1/nsk' = 1 - (1 - k)^{1/n_s}, where nsn_s is the sweep count, so that nsn_s sweeps of a single constraint remove the fraction kk of its error (Section 3.3). With many coupled constraints the effective stiffness still depends on nsn_s and on Δt\Delta t.

Collisions (L4). The paper tests each path xi→pi\mathbf x_i \to \mathbf p_i against the scene with collision detection and adds an inequality constraint for each hit, kept for the current step only (Section 3.4). The code uses a horizontal ground line, C=py−h≥0C = p_y - h \ge 0. The paper also changes the velocities of colliding particles after L7 for friction and restitution; the code leaves this out.

Damping (L2). Section 3.5 blends each velocity toward the rigid motion of the whole body with the same linear and angular momentum, vi←vi+kd(vcm+ω×ri−vi)\mathbf v_i \leftarrow \mathbf v_i + k_d (\mathbf v_{cm} + \boldsymbol\omega \times \mathbf r_i - \mathbf v_i). This damps the deformation and keeps both momenta. The factor kdk_d is a tuning value.

Order. Each projection uses the positions already moved by the earlier projections of the same sweep, as in Gauss-Seidel. The gradients are taken at the current positions p\mathbf p. The SHAKE algorithm of molecular dynamics also corrects positions one constraint at a time, but it takes the gradients at the old positions x\mathbf x and iterates until the constraints hold to a tolerance. Projected Gauss-Seidel for contact is also a sweep of this kind, but it works on velocities or impulses, and it solves a linear complementarity problem whose matrix does not change during the sweep, while PBD relinearizes the nonlinear constraints at every projection.

Example

One projection by hand. Particle 1 has m1=1m_1 = 1 at (0,0)(0, 0), particle 2 has m2=3m_2 = 3 at (1.5,0)(1.5, 0), and the rest length is d=1d = 1. Then w1=1w_1 = 1, w2=1/3w_2 = 1/3, n=(−1,0)\mathbf n = (-1, 0) and C=0.5C = 0.5, so s=0.5/(4/3)=0.375s = 0.5/(4/3) = 0.375. The corrections are Δp1=(0.375,0)\Delta \mathbf p_1 = (0.375, 0) and Δp2=(−0.125,0)\Delta \mathbf p_2 = (-0.125, 0). The new distance is 1.375−0.375=11.375 - 0.375 = 1, and the momentum change is 1⋅0.375+3⋅(−0.125)=01 \cdot 0.375 + 3 \cdot (-0.125) = 0.

A spinning rod loses angular momentum. Two particles of mass 1 at (∓0.5,0)(\mp 0.5, 0) with a rod of length 1 spin at ω=1\omega = 1 rad/s. With Δt=0.1\Delta t = 0.1 s, the prediction stretches the rod to (1+(ωΔt)2)1/2(1 + (\omega \Delta t)^2)^{1/2}, and the projection pulls both ends back toward the center. The angular momentum goes from 0.50.5 to 0.5/1.01=0.4975190.5/\sqrt{1.01} = 0.497519, the factor 0.9950370.995037 per step. With ωΔt=1\omega \Delta t = 1 the factor is 0.7071070.707107. The corrections are torque-free about the predicted positions, but the step does not keep the angular momentum.

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

sweeps kk 1 2 5 10 20 50
stretch 11.4% 5.7% 2.9% 1.5% 0.64% 0.16%

The rods have no stiffness parameter here (k=1k = 1), but the chain behaves like an elastic rope whose stiffness grows with the number of sweeps.

Correctness

The claims are proved in proofs/correctness.md. PBD does not converge to the solution of a time integrator, so its correctness is a list of exact properties of the discrete step, with their hypotheses.

  1. Smallest correction (proved). With k′=1k' = 1, each projection is the smallest correction in the mass norm that zeroes the linearized constraint, and a single distance constraint is satisfied exactly after one projection.
  2. Linear momentum (proved). If every constraint is invariant under translation, no particle is pinned and there is no ground, a step changes ∑mivi\sum m_i \mathbf v_i only by Δt∑mig\Delta t \sum m_i \mathbf g, for any number of sweeps. The test checks this to 10−1010^{-10} with random distance and area constraints and damping.
  3. Torque-free corrections (proved). If a constraint is also invariant under rotation, each projection satisfies ∑mipi×Δpi=0\sum m_i \mathbf p_i \times \Delta \mathbf p_i = 0 about the positions p\mathbf p where it acts. These are the conditions (1) and (2) of Section 3.3.
  4. Angular momentum is not kept (proved). The step changes L=∑mixi×viL = \sum m_i \mathbf x_i \times \mathbf v_i by 1Δt∑mixi×Δpi\frac{1}{\Delta t} \sum m_i \mathbf x_i \times \Delta \mathbf p_i, which is not zero in general; the spinning rod above loses the factor (1+(ωΔt)2)−1/2(1 + (\omega \Delta t)^2)^{-1/2} per step. Gradients at the old positions, as in SHAKE, would keep it.
  5. Damping (proved). The damping of L2 keeps the linear and the angular momentum.
  6. Stiffness per sweep (proved for one constraint). For a single constraint whose gradient direction does not change, nsn_s sweeps with k′k' leave the error (1−k)C0(1 - k) C_0. With coupled constraints the result depends on nsn_s, as the table shows (measured).

The tests also check the projection against a KKT solve, the gradients against central differences, the pins and the ground, and free fall against the symplectic Euler value −5.3955-5.3955 m after 10 steps of 0.10.1 s.

Proof: The PBD projection is the smallest mass-weighted correction, keeps linear momentum and is torque-free, but the step does not keep angular momentumfull

We use the notation of the page. There are nn particles with positions pi∈R2\mathbf p_i \in \mathbb R^2 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. A constraint CC depends on a set SS of particles, and ∇iC\nabla_i C is its gradient with respect to pi\mathbf p_i. The projection of line L6 with the sweep stiffness k′k' is

s=C(p)∑j∈Swj∣∇jC(p)∣2,Δpi=−k′s wi∇iC(p)(i∈S),s = \frac{C(\mathbf p)}{\sum_{j \in S} w_j |\nabla_j C(\mathbf p)|^2}, \qquad \Delta \mathbf p_i = -k' s\, w_i \nabla_i C(\mathbf p) \quad (i \in S),

which is equations (8) and (9) of Müller et al. (2007) with the masses put in. An inequality constraint C≥0C \ge 0 is projected only when C(p)<0C(\mathbf p) < 0.

The projection is a weighted least squares step

Lemma 1. Let ∇C(p)≠0\nabla C(\mathbf p) \ne 0 on the free particles. With k′=1k' = 1, the correction Δp\Delta \mathbf p is the unique minimizer of ∑i∈Smi∣Δpi∣2\sum_{i \in S} m_i |\Delta \mathbf p_i|^2 subject to the linearized constraint C(p)+∑i∈S∇iC⋅Δpi=0C(\mathbf p) + \sum_{i \in S} \nabla_i C \cdot \Delta \mathbf p_i = 0, where only free particles may move.

Proof. The objective is a strictly convex quadratic in the free unknowns, and the constraint is one affine equation that has a solution because some free ∇iC\nabla_i C is not zero. So the minimizer is unique, and it is the solution of the KKT system miΔpi=λ∇iCm_i \Delta \mathbf p_i = \lambda \nabla_i C for free ii, together with the constraint. Then Δpi=λwi∇iC\Delta \mathbf p_i = \lambda w_i \nabla_i C, and the constraint gives C+λ∑jwj∣∇jC∣2=0C + \lambda \sum_j w_j |\nabla_j C|^2 = 0, so λ=−s\lambda = -s. This is the correction of line L6. □\square

Corollary 2 (equations (10) and (11) of the paper). For C=∣p1−p2∣−dC = |\mathbf p_1 - \mathbf p_2| - d, let n=(p1−p2)/∣p1−p2∣\mathbf n = (\mathbf p_1 - \mathbf p_2)/|\mathbf p_1 - \mathbf p_2|. Then ∇1C=n\nabla_1 C = \mathbf n, ∇2C=−n\nabla_2 C = -\mathbf n, s=C/(w1+w2)s = C/(w_1 + w_2), and Δp1=−w1w1+w2(∣p1−p2∣−d) n\Delta \mathbf p_1 = -\frac{w_1}{w_1 + w_2} (|\mathbf p_1 - \mathbf p_2| - d)\, \mathbf n, Δp2=+w2w1+w2(∣p1−p2∣−d) n\Delta \mathbf p_2 = +\frac{w_2}{w_1 + w_2} (|\mathbf p_1 - \mathbf p_2| - d)\, \mathbf n. After the correction, p1−p2\mathbf p_1 - \mathbf p_2 keeps its direction and has the length dd, so one projection satisfies a single distance constraint exactly. □\square

Momentum of one projection

Lemma 3. If CC does not change when all its particles move by the same vector, then ∑i∈SmiΔpi=0\sum_{i \in S} m_i \Delta \mathbf p_i = 0, provided that all particles of SS are free.

Proof. Invariance under a translation by tet \mathbf e gives 0=ddtC(p+te)=∑i∇iC⋅e0 = \frac{d}{dt} C(\mathbf p + t \mathbf e) = \sum_i \nabla_i C \cdot \mathbf e for every e\mathbf e, so ∑i∇iC=0\sum_i \nabla_i C = 0. Then ∑imiΔpi=−k′s∑imiwi∇iC=−k′s∑i∇iC=0\sum_i m_i \Delta \mathbf p_i = -k' s \sum_i m_i w_i \nabla_i C = -k' s \sum_i \nabla_i C = 0. □\square

Lemma 4. If CC does not change when all its particles turn by the same rotation about the origin, then ∑i∈Smi pi×Δpi=0\sum_{i \in S} m_i\, \mathbf p_i \times \Delta \mathbf p_i = 0, where a×b=axby−aybx\mathbf a \times \mathbf b = a_x b_y - a_y b_x and p\mathbf p is the state before the projection. All particles of SS must be free.

Proof. Let JJ be the rotation by 90°90°. Invariance under the rotation by the angle tt gives 0=ddtC(R(t)p)∣t=0=∑i∇iC⋅Jpi0 = \frac{d}{dt} C(R(t)\mathbf p)|_{t=0} = \sum_i \nabla_i C \cdot J \mathbf p_i. Since g⋅Jp=−p×g\mathbf g \cdot J \mathbf p = -\mathbf p \times \mathbf g, this is ∑ipi×∇iC=0\sum_i \mathbf p_i \times \nabla_i C = 0. Then ∑imipi×Δpi=−k′s∑ipi×∇iC=0\sum_i m_i \mathbf p_i \times \Delta \mathbf p_i = -k' s \sum_i \mathbf p_i \times \nabla_i C = 0. □\square

Distance and area constraints satisfy both hypotheses. The ground constraint does not, because it fixes a line in space. These two lemmas are the conditions (1) and (2) of Section 3.3 of the paper.

Momentum of one step

Theorem 5 (linear momentum). Let every constraint satisfy the hypothesis of Lemma 3, let no particle be pinned and let there be no ground. Then one call of the step, with any number of sweeps and any damping factor, gives ∑imivin+1=∑imivin+Δt∑imig\sum_i m_i \mathbf v_i^{n+1} = \sum_i m_i \mathbf v_i^n + \Delta t \sum_i m_i \mathbf g.

Proof. Line L1 adds Δt∑mig\Delta t \sum m_i \mathbf g to the momentum. The damping of line L2 replaces vi\mathbf v_i by vi+kd(vcm+ωJri−vi)\mathbf v_i + k_d (\mathbf v_{cm} + \omega J \mathbf r_i - \mathbf v_i); since ∑miri=0\sum m_i \mathbf r_i = 0 and ∑mivi=Mtotvcm\sum m_i \mathbf v_i = M_{\text{tot}} \mathbf v_{cm}, the sum of mim_i times the change is zero. Lines L3 to L6 change p\mathbf p by a sum of corrections, each with ∑miΔpi=0\sum m_i \Delta \mathbf p_i = 0 by Lemma 3. So ∑mipi=∑mi(xi+Δtvi)\sum m_i \mathbf p_i = \sum m_i (\mathbf x_i + \Delta t \mathbf v_i) with the velocities after L2, and line L7 gives ∑mivin+1=∑mi(pi−xi)/Δt=∑mivi\sum m_i \mathbf v_i^{n+1} = \sum m_i (\mathbf p_i - \mathbf x_i)/\Delta t = \sum m_i \mathbf v_i. □\square

Lemma 6 (the damping keeps angular momentum). The damping of line L2 does not change ∑mixi×vi\sum m_i \mathbf x_i \times \mathbf v_i.

Proof. Write xi=xcm+ri\mathbf x_i = \mathbf x_{cm} + \mathbf r_i. The change of velocity is kdΔvik_d \Delta \mathbf v_i with Δvi=vcm+ωJri−vi\Delta \mathbf v_i = \mathbf v_{cm} + \omega J \mathbf r_i - \mathbf v_i. Its linear part sums to zero, as in Theorem 5, so the angular momentum changes by kd∑miri×Δvik_d \sum m_i \mathbf r_i \times \Delta \mathbf v_i. Here ∑miri×vcm=0\sum m_i \mathbf r_i \times \mathbf v_{cm} = 0, ∑miri×ωJri=ωI\sum m_i \mathbf r_i \times \omega J \mathbf r_i = \omega I with I=∑mi∣ri∣2I = \sum m_i |\mathbf r_i|^2, and ∑miri×vi=Lcm\sum m_i \mathbf r_i \times \mathbf v_i = L_{cm}. With ω=Lcm/I\omega = L_{cm}/I the sum is zero. □\square

Theorem 7 (angular momentum changes). With no external force, no damping and no pins, let Δpi\Delta \mathbf p_i be the sum of all corrections that particle ii gets in lines L5 and L6. Then

Ln+1−Ln=1Δt∑imi xin×Δpi,Ln=∑imixin×vin.L^{n+1} - L^n = \frac{1}{\Delta t} \sum_i m_i\, \mathbf x_i^n \times \Delta \mathbf p_i, \qquad L^n = \sum_i m_i \mathbf x_i^n \times \mathbf v_i^n .

This is not zero in general, even when every constraint satisfies the hypotheses of Lemmas 3 and 4.

Proof. Line L7 gives xn+1=xn+Δtvn+1\mathbf x^{n+1} = \mathbf x^n + \Delta t \mathbf v^{n+1}, so xin+1×vin+1=xin×vin+1\mathbf x_i^{n+1} \times \mathbf v_i^{n+1} = \mathbf x_i^n \times \mathbf v_i^{n+1}. Line L3 and the corrections give vin+1=vin+Δpi/Δt\mathbf v_i^{n+1} = \mathbf v_i^n + \Delta \mathbf p_i / \Delta t. Then Ln+1=∑mixin×vin+1=Ln+1Δt∑mixin×ΔpiL^{n+1} = \sum m_i \mathbf x_i^n \times \mathbf v_i^{n+1} = L^n + \frac{1}{\Delta t} \sum m_i \mathbf x_i^n \times \Delta \mathbf p_i. Lemma 4 makes each correction torque-free about the point where it acts, which is p\mathbf p and not xn\mathbf x^n.

For the counterexample, take two particles of mass 1 at (∓12,0)(\mp \tfrac12, 0) with one distance constraint of rest length 1, spinning at the rate ω\omega: v1,2=(0,∓12ω)\mathbf v_{1,2} = (0, \mp \tfrac12 \omega) and Ln=12ωL^n = \tfrac12 \omega. The prediction is p1,2=±(12,12ωΔt)\mathbf p_{1,2} = \pm(\tfrac12, \tfrac12 \omega \Delta t) with the sign flipped for particle 1, at the distance ℓ=(1+(ωΔt)2)1/2\ell = (1 + (\omega \Delta t)^2)^{1/2}. By Corollary 2 with equal masses, the projection scales both points by 1/ℓ1/\ell about the origin, and later sweeps do nothing. So v2n+1=(p2/ℓ−x2)/Δt\mathbf v_2^{n+1} = (\mathbf p_2/\ell - \mathbf x_2)/\Delta t, and by symmetry Ln+1=2 x2×v2n+1=2⋅12⋅12ωΔt/(ℓΔt)=12ω/ℓL^{n+1} = 2\, \mathbf x_2 \times \mathbf v_2^{n+1} = 2 \cdot \tfrac12 \cdot \tfrac12 \omega \Delta t / (\ell \Delta t) = \tfrac12 \omega / \ell. Hence Ln+1/Ln=(1+(ωΔt)2)−1/2<1L^{n+1}/L^n = (1 + (\omega \Delta t)^2)^{-1/2} < 1. □\square

If the gradients are taken at xn\mathbf x^n instead of at the current p\mathbf p, as in the SHAKE method of molecular dynamics, every correction is a multiple of wi∇iC(xn)w_i \nabla_i C(\mathbf x^n), and the argument of Lemma 4 at xn\mathbf x^n gives ∑imixin×Δpi=0\sum_i m_i \mathbf x_i^n \times \Delta \mathbf p_i = 0, so Theorem 7 gives Ln+1=LnL^{n+1} = L^n.

Stiffness per sweep

Lemma 8. Let one constraint have a gradient whose direction does not change under its own projection, for example a distance constraint between a pinned and a free particle. If it is projected nsn_s times in a row with k′=1−(1−k)1/nsk' = 1 - (1 - k)^{1/n_s}, its value goes from C0C_0 to (1−k)C0(1 - k) C_0.

Proof. By Corollary 2, one projection with k′k' moves the free particle along the fixed direction by k′k' times the full correction, so the value becomes (1−k′)C(1 - k') C. After nsn_s projections the value is (1−k′)nsC0=(1−k)C0(1 - k')^{n_s} C_0 = (1 - k) C_0. □\square

With several coupled constraints the error after nsn_s sweeps depends on the coupling, so the effective stiffness depends on the iteration count and on Δt\Delta t (Section 3.3 of the paper says this). This is the problem that XPBD addresses.

Free motion

Lemma 9. With no constraints and no damping, 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. Lines L1 and L3 compute exactly these two updates, and line L7 gives back the same velocity, since (p−xn)/Δt=vn+Δtg(\mathbf p - \mathbf x^n)/\Delta t = \mathbf v^n + \Delta t \mathbf g. □\square

Complexity

One projection costs O(1)O(1) for a constraint on a bounded number of particles, so one sweep costs Θ(c)\Theta(c). Lines L1 to L3 and L7 to L8 cost Θ(n)\Theta(n). The collision detection of L4 is a separate cost; with the ground line it is Θ(n)\Theta(n). A step costs O(n+kc)O(n + k c) time, and the state and the constraint list use O(n+c)O(n + c) memory. There is no matrix to build or factor. The number of sweeps that gives a usable stiffness is a measurement for each scene.

Properties

  • Robust, not accurate. The particles end where the projections put them, so a large correction cannot feed back as a large force. The paper argues that the method is unconditionally stable; this is an argument, not a theorem, and a stable answer can still be far from the motion of the physical model.
  • Stiffness is not a material constant. The behavior depends on Δt\Delta t, the sweep count and the constraint order. Two scenes with the same kk but different settings look different.
  • Order dependence. Gauss-Seidel sweeps depend on the constraint order. A Jacobi version projects all constraints from the same positions and averages, which is parallel but slower to converge.
  • Exact conservation. Linear momentum is kept for translation invariant constraints. Angular momentum is not kept exactly (claim 4).
  • Energy. There is no energy that the step decreases or keeps; the damping is a mix of the method itself and the tuning factor kdk_d.

Variants and improvements

  • XPBD. Extended position based dynamics adds a compliance and a Lagrange multiplier to each constraint, which removes the dependence on the sweep count and makes the method an approximate backward Euler solver.
  • Substeps. Small steps use many substeps with one sweep each instead of one step with many sweeps, which reduces the error of XPBD for the same cost.
  • Shape matching. Meshless shape matching pulls particles toward the best rigid fit of the rest shape, which is a position based method without a mesh.
  • Fluids. Position based fluids project a density constraint per particle with the same machinery.
  • Strain limiting. Provot strain limiting is an older position correction that shortens over-stretched springs after a force based step.
  • Jacobi and graph coloring. On a GPU, constraints are projected in parallel either by averaging (Jacobi) or by graph coloring, so that constraints of one color share no particle.

When to use it

Use PBD for interactive scenes where robustness and a fixed cost per frame matter more than a material that behaves the same at every step size: cloth, ropes, hair and soft objects in games, and controllers that move particles directly. It handles pins, collisions and other position goals easily, because they are all constraints.

Do not use plain PBD when the stiffness must match a material or stay the same when Δt\Delta t or the sweep count changes. Use XPBD then, or an implicit solver such as projective dynamics or optimization time integration.

Pitfalls

  • Stiffness changes with settings. Raising the sweep count makes cloth stiffer and changing the step changes the look. Tune with the final settings, or use XPBD.
  • Velocities from positions. Line L7 must use the position at the start of the step, xi\mathbf x_i, not the position after the external force. A collision projection that moves a particle far also gives it a large velocity; the paper corrects the velocities of colliding particles after L7.
  • Zero gradients. A distance constraint between two particles at the same point has no direction. Skip it, as the code does, instead of dividing by zero.
  • Pinned pairs. If all particles of a constraint are pinned, the denominator of ss is zero. Skip such constraints.
  • Angular momentum drift. A fast spinning body slows down by the factor of claim 4 per step. Use smaller steps or the SHAKE choice of gradients if this matters.

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

"""Position based dynamics (Mueller, Heidelberger, Hennix and Ratcliff 2007), in 2D.

A step predicts the positions with symplectic Euler, projects them onto the
constraints one at a time for a fixed number of Gauss-Seidel sweeps, and then
sets each velocity from the change in position (Section 3.1 of the paper).

A constraint has a value C(p) and one gradient for each of its particles. An
equality constraint is projected always; an inequality constraint C(p) >= 0
is projected only when C(p) < 0. The projection of one constraint is

    s = C(p) / sum_j w_j |grad_j C(p)|^2,   dp_i = -k' s w_i grad_i C(p),

with the inverse masses w_i (Section 3.3, equations (8) and (9) with masses)
and the stiffness per sweep k' = 1 - (1 - k)^(1 / n_s), so that n_s sweeps of
a linear constraint remove the part k of its error. A particle with w_i = 0 does
not move.

The cost of one sweep is Theta(c) for c constraints with a bounded number of
particles each; a step costs O(n + n_s c) time and O(n + c) memory.
"""

import math

GRAVITY = (0.0, -9.81)


class Distance:
    """C(p) = |p_i - p_j| - rest = 0 (equations (10) and (11) of the paper)."""

    equality = True

    def __init__(self, i, j, rest, stiffness=1.0):
        self.i, self.j, self.rest, self.stiffness = i, j, rest, stiffness

    def value(self, p):
        a, b = p[self.i], p[self.j]
        return math.hypot(a[0] - b[0], a[1] - b[1]) - self.rest

    def gradients(self, p):
        a, b = p[self.i], p[self.j]
        dx, dy = a[0] - b[0], a[1] - b[1]
        ln = math.hypot(dx, dy)
        if ln == 0.0:
            return [(self.i, (0.0, 0.0)), (self.j, (0.0, 0.0))]
        n = (dx / ln, dy / ln)
        return [(self.i, n), (self.j, (-n[0], -n[1]))]


class Area:
    """C(p) = signed area of the triangle (i, j, l) - rest = 0."""

    equality = True

    def __init__(self, i, j, l, rest, stiffness=1.0):
        self.i, self.j, self.l, self.rest, self.stiffness = i, j, l, rest, stiffness

    def value(self, p):
        a, b, c = p[self.i], p[self.j], p[self.l]
        return 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) - self.rest

    def gradients(self, p):
        a, b, c = p[self.i], p[self.j], p[self.l]
        return [
            (self.i, (0.5 * (b[1] - c[1]), 0.5 * (c[0] - b[0]))),
            (self.j, (0.5 * (c[1] - a[1]), 0.5 * (a[0] - c[0]))),
            (self.l, (0.5 * (a[1] - b[1]), 0.5 * (b[0] - a[0]))),
        ]


class Ground:
    """C(p) = p_i,y - height >= 0, a collision constraint with a horizontal ground line."""

    equality = False
    stiffness = 1.0

    def __init__(self, i, height=0.0):
        self.i, self.height = i, height

    def value(self, p):
        return p[self.i][1] - self.height

    def gradients(self, p):
        return [(self.i, (0.0, 1.0))]


def sweep_stiffness(k, iterations):
    """k' = 1 - (1 - k)^(1 / n_s) (Section 3.3)."""
    if k >= 1.0:
        return 1.0
    return 1.0 - (1.0 - k) ** (1.0 / iterations)


def project(constraint, p, w, k_sweep):
    """Project p (a list of points, changed in place) onto one constraint. Return the correction per particle."""
    c = constraint.value(p)
    if not constraint.equality and c >= 0.0:
        return []
    grads = constraint.gradients(p)
    denom = sum(w[i] * (g[0] * g[0] + g[1] * g[1]) for i, g in grads)
    if denom == 0.0:
        return []
    s = c / denom
    out = []
    for i, g in grads:
        d = (-k_sweep * s * w[i] * g[0], -k_sweep * s * w[i] * g[1])
        p[i] = (p[i][0] + d[0], p[i][1] + d[1])
        out.append((i, d))
    return out


def damp_velocities(x, v, w, k_damping):
    """The damping of Section 3.5 in 2D: blend each velocity toward the rigid motion with the same momenta."""
    idx = [i for i in range(len(x)) if w[i] > 0.0]
    if not idx or k_damping == 0.0:
        return list(v)
    m = {i: 1.0 / w[i] for i in idx}
    mt = sum(m.values())
    xc = (sum(m[i] * x[i][0] for i in idx) / mt, sum(m[i] * x[i][1] for i in idx) / mt)
    vc = (sum(m[i] * v[i][0] for i in idx) / mt, sum(m[i] * v[i][1] for i in idx) / mt)
    big_l = 0.0
    inertia = 0.0
    for i in idx:
        r = (x[i][0] - xc[0], x[i][1] - xc[1])
        big_l += m[i] * (r[0] * v[i][1] - r[1] * v[i][0])
        inertia += m[i] * (r[0] * r[0] + r[1] * r[1])
    om = big_l / inertia if inertia > 0.0 else 0.0
    out = list(v)
    for i in idx:
        r = (x[i][0] - xc[0], x[i][1] - xc[1])
        dv = (vc[0] - om * r[1] - v[i][0], vc[1] + om * r[0] - v[i][1])
        out[i] = (v[i][0] + k_damping * dv[0], v[i][1] + k_damping * dv[1])
    return out


def pbd_step(x, v, w, constraints, dt, iterations, gravity=GRAVITY, k_damping=0.0, ground=None):
    """One step of position based dynamics.

    x, v: lists of 2D points and velocities. w: inverse masses (0 for a pinned
    particle). constraints: objects with value, gradients, equality and
    stiffness. The external force is the weight m g. If ground is a number,
    a Ground constraint is made for each particle whose prediction is below it.
    Return the new (x, v) as lists of tuples.
    """
    n = len(x)
    v = [(v[i][0] + dt * gravity[0], v[i][1] + dt * gravity[1]) if w[i] > 0.0 else tuple(v[i])
         for i in range(n)]  # @line L1
    v = damp_velocities(x, v, w, k_damping)  # @line L2
    p = [(x[i][0] + dt * v[i][0], x[i][1] + dt * v[i][1]) for i in range(n)]  # @line L3
    coll = [Ground(i, ground) for i in range(n) if ground is not None and p[i][1] < ground]  # @line L4
    work = list(constraints) + coll
    ks = [sweep_stiffness(c.stiffness, iterations) for c in work]
    for _ in range(iterations):  # @line L5
        for c, k in zip(work, ks):
            project(c, p, w, k)  # @line L6
    v_new = [((p[i][0] - x[i][0]) / dt, (p[i][1] - x[i][1]) / dt) for i in range(n)]  # @line L7
    return p, v_new  # @line L8


def chain(count, spacing, mass=1.0, pin_first=True):
    """A horizontal chain of particles joined by distance constraints. Return (x, v, w, constraints)."""
    x = [(i * spacing, 0.0) for i in range(count)]
    v = [(0.0, 0.0)] * count
    w = [1.0 / mass] * count
    if pin_first:
        w[0] = 0.0
    cons = [Distance(i, i + 1, spacing) for i in range(count - 1)]
    return x, v, w, cons


def momentum(x, v, w):
    """Linear and angular momentum (about the origin) of the particles with w > 0."""
    px = py = big_l = 0.0
    for xi, vi, wi in zip(x, v, w):
        if wi > 0.0:
            m = 1.0 / wi
            px += m * vi[0]
            py += m * vi[1]
            big_l += m * (xi[0] * vi[1] - xi[1] * vi[0])
    return px, py, big_l
test_position_based_dynamics.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/position-based-dynamics/. The authors are listed in prov/AGQN60.jsonl.

"""Tests of position based dynamics against closed forms, a KKT solve and conservation laws."""

import math
import random

from anim import num_grad, solve
import position_based_dynamics as pbd


def test_example_two_particles():
    p = [(0.0, 0.0), (1.5, 0.0)]
    w = [1.0, 1.0 / 3.0]
    out = dict(pbd.project(pbd.Distance(0, 1, 1.0), p, w, 1.0))
    assert abs(out[0][0] - 0.375) < 1e-15 and abs(out[1][0] + 0.125) < 1e-15
    assert abs(1.0 * out[0][0] + 3.0 * out[1][0]) < 1e-15
    assert abs(math.dist(p[0], p[1]) - 1.0) < 1e-15


def test_distance_projection_closed_form():
    """Equations (10) and (11): dp1 = -w1 / (w1 + w2) (|p12| - d) n, dp2 = +w2 / (w1 + w2) (|p12| - d) n."""
    rng = random.Random(3)
    for _ in range(200):
        p = [(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)
        dx, dy = p[0][0] - p[1][0], p[0][1] - p[1][1]
        ln = math.hypot(dx, dy)
        n = (dx / ln, dy / ln)
        e = ln - d
        want0 = (-w[0] / (w[0] + w[1]) * e * n[0], -w[0] / (w[0] + w[1]) * e * n[1])
        want1 = (w[1] / (w[0] + w[1]) * e * n[0], w[1] / (w[0] + w[1]) * e * n[1])
        got = dict(pbd.project(pbd.Distance(0, 1, d), p, w, 1.0))
        assert max(abs(got[0][k] - want0[k]) for k in range(2)) < 1e-14
        assert max(abs(got[1][k] - want1[k]) for k in range(2)) < 1e-14


def test_projection_equals_kkt_solve():
    """The correction is the smallest in the mass norm that zeroes the linearized constraint."""
    rng = random.Random(4)
    for _ in range(100):
        p = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(3)]
        w = [rng.uniform(0.2, 2.0) for _ in range(3)]
        c = pbd.Area(0, 1, 2, rng.uniform(-0.3, 0.3))
        cv = c.value(p)
        g = dict(c.gradients(p))
        # KKT: M dp - grad^T lam = 0, grad dp = -C, unknowns (dp in R^6, lam)
        a = [[0.0] * 7 for _ in range(7)]
        b = [0.0] * 7
        for i in range(3):
            for k in range(2):
                r = 2 * i + k
                a[r][r] = 1.0 / w[i]
                a[r][6] = -g[i][k]
                a[6][r] = g[i][k]
        b[6] = -cv
        sol = solve(a, b)
        q = list(p)
        got = dict(pbd.project(c, q, w, 1.0))
        for i in range(3):
            for k in range(2):
                assert abs(got[i][k] - sol[2 * i + k]) < 1e-11


def test_gradients_against_num_grad():
    rng = random.Random(5)
    for _ in range(30):
        p = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(3)]
        for c in (pbd.Distance(0, 2, 0.5), pbd.Area(0, 1, 2, 0.1), pbd.Ground(1, 0.2)):
            flat = [u for q in p for u in q]

            def f(z, c=c):
                return c.value([(z[0], z[1]), (z[2], z[3]), (z[4], z[5])])

            ng = num_grad(f, flat)
            g = dict(c.gradients(p))
            for i in range(3):
                gi = g.get(i, (0.0, 0.0))
                for k in range(2):
                    assert abs(gi[k] - ng[2 * i + k]) <= 1e-6 * max(1.0, abs(ng[2 * i + k]))


def test_torque_free_corrections():
    """Each projection keeps sum m dp = 0 and sum m p x dp = 0 at the positions where it acts (equations (1) and (2))."""
    rng = random.Random(6)
    for _ in range(100):
        p = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(3)]
        w = [rng.uniform(0.2, 2.0) for _ in range(3)]
        for c in (pbd.Distance(0, 1, 0.3), pbd.Area(0, 1, 2, 0.05)):
            q = list(p)
            corr = pbd.project(c, q, w, 1.0)
            lin = [sum(d[k] / w[i] for i, d in corr) for k in range(2)]
            ang = sum((p[i][0] * d[1] - p[i][1] * d[0]) / w[i] for i, d in corr)
            assert max(abs(lin[0]), abs(lin[1]), abs(ang)) < 1e-14


def test_linear_momentum_is_conserved():
    rng = random.Random(7)
    x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(12)]
    v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(12)]
    w = [rng.uniform(0.5, 2.0) for _ in range(12)]
    cons = [pbd.Distance(i, j, 0.8 * math.dist(x[i], x[j])) for i in range(12) for j in range(i + 1, 12) if (i + j) % 3 == 0]
    cons += [pbd.Area(i, i + 1, i + 2, 0.0) for i in range(0, 9, 3)]
    p0 = pbd.momentum(x, v, w)
    for _ in range(50):
        x, v = pbd.pbd_step(x, v, w, cons, 0.01, 4, gravity=(0.0, 0.0), k_damping=0.1)
    p1 = pbd.momentum(x, v, w)
    scale = sum(math.hypot(*vi) / wi for vi, wi in zip(v, w))
    assert abs(p1[0] - p0[0]) < 1e-10 * scale and abs(p1[1] - p0[1]) < 1e-10 * scale


def test_spinning_dumbbell_loses_angular_momentum():
    """One step of a rigid rod spinning at omega multiplies L by 1 / sqrt(1 + (omega dt)^2)."""
    for omega, dt in ((1.0, 0.1), (1.0, 1.0), (3.0, 0.05)):
        x = [(-0.5, 0.0), (0.5, 0.0)]
        v = [(0.0, -0.5 * omega), (0.0, 0.5 * omega)]
        w = [1.0, 1.0]
        l0 = pbd.momentum(x, v, w)[2]
        x1, v1 = pbd.pbd_step(x, v, w, [pbd.Distance(0, 1, 1.0)], dt, 3, gravity=(0.0, 0.0))
        l1 = pbd.momentum(x1, v1, w)[2]
        assert abs(l1 / l0 - 1.0 / math.sqrt(1.0 + (omega * dt) ** 2)) < 1e-14


def test_damping_keeps_momenta():
    rng = random.Random(8)
    x = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(8)]
    v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(8)]
    w = [rng.uniform(0.5, 2.0) for _ in range(8)]
    vd = pbd.damp_velocities(x, v, w, 0.7)
    a, b = pbd.momentum(x, v, w), pbd.momentum(x, vd, w)
    assert max(abs(a[k] - b[k]) for k in range(3)) < 1e-12
    vr = pbd.damp_velocities(x, v, w, 1.0)
    # k_damping = 1 leaves a rigid motion: every pair keeps its distance to first order
    for i in range(8):
        for j in range(8):
            dx = (x[i][0] - x[j][0], x[i][1] - x[j][1])
            dv = (vr[i][0] - vr[j][0], vr[i][1] - vr[j][1])
            assert abs(dx[0] * dv[0] + dx[1] * dv[1]) < 1e-12


def test_sweep_stiffness_gives_k_after_n_sweeps():
    """For one particle on a pinned rod along x, n_s sweeps leave the error (1 - k) e."""
    for k in (0.1, 0.5, 0.9):
        for ns in (1, 3, 10):
            p = [(0.0, 0.0), (1.5, 0.0)]
            c = pbd.Distance(0, 1, 1.0, stiffness=k)
            kp = pbd.sweep_stiffness(k, ns)
            for _ in range(ns):
                pbd.project(c, p, [0.0, 1.0], kp)
            assert abs(c.value(p) - (1.0 - k) * 0.5) < 1e-12


def test_pinned_particle_and_ground():
    x, v, w, cons = pbd.chain(6, 0.2)
    for _ in range(200):
        x, v = pbd.pbd_step(x, v, w, cons, 1.0 / 60.0, 10, ground=-0.5)
        assert x[0] == (0.0, 0.0)
        assert min(p[1] for p in x) >= -0.5 - 1e-12


def test_residual_decreases_with_iterations():
    """The stretch of a falling chain depends on the iteration count: the reason for XPBD."""
    stretch = []
    for it in (1, 5, 50):
        x, v, w, cons = pbd.chain(11, 0.1)
        for _ in range(300):
            x, v = pbd.pbd_step(x, v, w, cons, 1.0 / 60.0, it)
        stretch.append(sum(math.dist(x[i], x[i + 1]) for i in range(10)) - 1.0)
    assert stretch[0] > stretch[1] > stretch[2] > 0.0
    assert stretch[0] > 0.1 and stretch[2] < 0.002


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 = pbd.pbd_step(x, v, w, [], 0.1, 1)
    assert abs(x[0][1] + 5.3955) < 1e-12

History

Jakobsen (2001) described a position based approach with Verlet integration and sticks projected one at a time for the characters of the game Hitman, at the Game Developers Conference. Müller, Heidelberger, Hennix and Ratcliff generalized it to arbitrary constraints with mass weighting, stiffness, collisions and damping, first at VRIPHYS 2006 and then in the Journal of Visual Communication and Image Representation in 2007. Macklin, Müller and Chentanez added compliance in 2016 with XPBD, and Macklin, Storey, Lu, Terdiman, Chentanez, Jeschke and Müller showed in 2019 that small substeps work better than many sweeps.

References

  1. Matthias Müller, Bruno Heidelberger, Marcus Hennix and John Ratcliff, Position based dynamics, Journal of Visual Communication and Image Representation 18(2), 109-118, 2007, Section 3.1 (the algorithm, lines (1) to (17)), Section 3.2 (the solver), Section 3.3 (constraint projection, equations (1) to (11) and the stiffness per iteration), Section 3.4 (collisions), Section 3.5 (damping), Section 3.6 (attachments)

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